package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.Territory;
import cn.ibizlab.businesscentral.core.base.service.ITerritoryService;
import cn.ibizlab.businesscentral.core.base.filter.TerritorySearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"区域" })
@RestController("CentralApi-territory")
@RequestMapping("")
public class TerritoryResource {

    @Autowired
    public ITerritoryService territoryService;

    @Autowired
    @Lazy
    public TerritoryMapping territoryMapping;

    @PreAuthorize("hasPermission(this.territoryMapping.toDomain(#territorydto),'iBizBusinessCentral-Territory-Create')")
    @ApiOperation(value = "新建区域", tags = {"区域" },  notes = "新建区域")
	@RequestMapping(method = RequestMethod.POST, value = "/territories")
    @Transactional
    public ResponseEntity<TerritoryDTO> create(@RequestBody TerritoryDTO territorydto) {
        Territory domain = territoryMapping.toDomain(territorydto);
		territoryService.create(domain);
        TerritoryDTO dto = territoryMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.territoryMapping.toDomain(#territorydtos),'iBizBusinessCentral-Territory-Create')")
    @ApiOperation(value = "批量新建区域", tags = {"区域" },  notes = "批量新建区域")
	@RequestMapping(method = RequestMethod.POST, value = "/territories/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<TerritoryDTO> territorydtos) {
        territoryService.createBatch(territoryMapping.toDomain(territorydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "territory" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.territoryService.get(#territory_id),'iBizBusinessCentral-Territory-Update')")
    @ApiOperation(value = "更新区域", tags = {"区域" },  notes = "更新区域")
	@RequestMapping(method = RequestMethod.PUT, value = "/territories/{territory_id}")
    @Transactional
    public ResponseEntity<TerritoryDTO> update(@PathVariable("territory_id") String territory_id, @RequestBody TerritoryDTO territorydto) {
		Territory domain  = territoryMapping.toDomain(territorydto);
        domain .setTerritoryid(territory_id);
		territoryService.update(domain );
		TerritoryDTO dto = territoryMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.territoryService.getTerritoryByEntities(this.territoryMapping.toDomain(#territorydtos)),'iBizBusinessCentral-Territory-Update')")
    @ApiOperation(value = "批量更新区域", tags = {"区域" },  notes = "批量更新区域")
	@RequestMapping(method = RequestMethod.PUT, value = "/territories/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<TerritoryDTO> territorydtos) {
        territoryService.updateBatch(territoryMapping.toDomain(territorydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.territoryService.get(#territory_id),'iBizBusinessCentral-Territory-Remove')")
    @ApiOperation(value = "删除区域", tags = {"区域" },  notes = "删除区域")
	@RequestMapping(method = RequestMethod.DELETE, value = "/territories/{territory_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("territory_id") String territory_id) {
         return ResponseEntity.status(HttpStatus.OK).body(territoryService.remove(territory_id));
    }

    @PreAuthorize("hasPermission(this.territoryService.getTerritoryByIds(#ids),'iBizBusinessCentral-Territory-Remove')")
    @ApiOperation(value = "批量删除区域", tags = {"区域" },  notes = "批量删除区域")
	@RequestMapping(method = RequestMethod.DELETE, value = "/territories/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        territoryService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.territoryMapping.toDomain(returnObject.body),'iBizBusinessCentral-Territory-Get')")
    @ApiOperation(value = "获取区域", tags = {"区域" },  notes = "获取区域")
	@RequestMapping(method = RequestMethod.GET, value = "/territories/{territory_id}")
    public ResponseEntity<TerritoryDTO> get(@PathVariable("territory_id") String territory_id) {
        Territory domain = territoryService.get(territory_id);
        TerritoryDTO dto = territoryMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取区域草稿", tags = {"区域" },  notes = "获取区域草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/territories/getdraft")
    public ResponseEntity<TerritoryDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(territoryMapping.toDto(territoryService.getDraft(new Territory())));
    }

    @ApiOperation(value = "检查区域", tags = {"区域" },  notes = "检查区域")
	@RequestMapping(method = RequestMethod.POST, value = "/territories/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody TerritoryDTO territorydto) {
        return  ResponseEntity.status(HttpStatus.OK).body(territoryService.checkKey(territoryMapping.toDomain(territorydto)));
    }

    @PreAuthorize("hasPermission(this.territoryMapping.toDomain(#territorydto),'iBizBusinessCentral-Territory-Save')")
    @ApiOperation(value = "保存区域", tags = {"区域" },  notes = "保存区域")
	@RequestMapping(method = RequestMethod.POST, value = "/territories/save")
    public ResponseEntity<Boolean> save(@RequestBody TerritoryDTO territorydto) {
        return ResponseEntity.status(HttpStatus.OK).body(territoryService.save(territoryMapping.toDomain(territorydto)));
    }

    @PreAuthorize("hasPermission(this.territoryMapping.toDomain(#territorydtos),'iBizBusinessCentral-Territory-Save')")
    @ApiOperation(value = "批量保存区域", tags = {"区域" },  notes = "批量保存区域")
	@RequestMapping(method = RequestMethod.POST, value = "/territories/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<TerritoryDTO> territorydtos) {
        territoryService.saveBatch(territoryMapping.toDomain(territorydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Territory-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Territory-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"区域" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/territories/fetchdefault")
	public ResponseEntity<List<TerritoryDTO>> fetchDefault(TerritorySearchContext context) {
        Page<Territory> domains = territoryService.searchDefault(context) ;
        List<TerritoryDTO> list = territoryMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Territory-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Territory-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"区域" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/territories/searchdefault")
	public ResponseEntity<Page<TerritoryDTO>> searchDefault(@RequestBody TerritorySearchContext context) {
        Page<Territory> domains = territoryService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(territoryMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

