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.sales.domain.CompetitorProduct;
import cn.ibizlab.businesscentral.core.sales.service.ICompetitorProductService;
import cn.ibizlab.businesscentral.core.sales.filter.CompetitorProductSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"竞争对手产品" })
@RestController("CentralApi-competitorproduct")
@RequestMapping("")
public class CompetitorProductResource {

    @Autowired
    public ICompetitorProductService competitorproductService;

    @Autowired
    @Lazy
    public CompetitorProductMapping competitorproductMapping;

    @PreAuthorize("hasPermission(this.competitorproductMapping.toDomain(#competitorproductdto),'iBizBusinessCentral-CompetitorProduct-Create')")
    @ApiOperation(value = "新建竞争对手产品", tags = {"竞争对手产品" },  notes = "新建竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitorproducts")
    @Transactional
    public ResponseEntity<CompetitorProductDTO> create(@RequestBody CompetitorProductDTO competitorproductdto) {
        CompetitorProduct domain = competitorproductMapping.toDomain(competitorproductdto);
		competitorproductService.create(domain);
        CompetitorProductDTO dto = competitorproductMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.competitorproductMapping.toDomain(#competitorproductdtos),'iBizBusinessCentral-CompetitorProduct-Create')")
    @ApiOperation(value = "批量新建竞争对手产品", tags = {"竞争对手产品" },  notes = "批量新建竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitorproducts/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<CompetitorProductDTO> competitorproductdtos) {
        competitorproductService.createBatch(competitorproductMapping.toDomain(competitorproductdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "competitorproduct" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.competitorproductService.get(#competitorproduct_id),'iBizBusinessCentral-CompetitorProduct-Update')")
    @ApiOperation(value = "更新竞争对手产品", tags = {"竞争对手产品" },  notes = "更新竞争对手产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/competitorproducts/{competitorproduct_id}")
    @Transactional
    public ResponseEntity<CompetitorProductDTO> update(@PathVariable("competitorproduct_id") String competitorproduct_id, @RequestBody CompetitorProductDTO competitorproductdto) {
		CompetitorProduct domain  = competitorproductMapping.toDomain(competitorproductdto);
        domain .setRelationshipsid(competitorproduct_id);
		competitorproductService.update(domain );
		CompetitorProductDTO dto = competitorproductMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.competitorproductService.getCompetitorproductByEntities(this.competitorproductMapping.toDomain(#competitorproductdtos)),'iBizBusinessCentral-CompetitorProduct-Update')")
    @ApiOperation(value = "批量更新竞争对手产品", tags = {"竞争对手产品" },  notes = "批量更新竞争对手产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/competitorproducts/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<CompetitorProductDTO> competitorproductdtos) {
        competitorproductService.updateBatch(competitorproductMapping.toDomain(competitorproductdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.competitorproductService.get(#competitorproduct_id),'iBizBusinessCentral-CompetitorProduct-Remove')")
    @ApiOperation(value = "删除竞争对手产品", tags = {"竞争对手产品" },  notes = "删除竞争对手产品")
	@RequestMapping(method = RequestMethod.DELETE, value = "/competitorproducts/{competitorproduct_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("competitorproduct_id") String competitorproduct_id) {
         return ResponseEntity.status(HttpStatus.OK).body(competitorproductService.remove(competitorproduct_id));
    }

    @PreAuthorize("hasPermission(this.competitorproductService.getCompetitorproductByIds(#ids),'iBizBusinessCentral-CompetitorProduct-Remove')")
    @ApiOperation(value = "批量删除竞争对手产品", tags = {"竞争对手产品" },  notes = "批量删除竞争对手产品")
	@RequestMapping(method = RequestMethod.DELETE, value = "/competitorproducts/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        competitorproductService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.competitorproductMapping.toDomain(returnObject.body),'iBizBusinessCentral-CompetitorProduct-Get')")
    @ApiOperation(value = "获取竞争对手产品", tags = {"竞争对手产品" },  notes = "获取竞争对手产品")
	@RequestMapping(method = RequestMethod.GET, value = "/competitorproducts/{competitorproduct_id}")
    public ResponseEntity<CompetitorProductDTO> get(@PathVariable("competitorproduct_id") String competitorproduct_id) {
        CompetitorProduct domain = competitorproductService.get(competitorproduct_id);
        CompetitorProductDTO dto = competitorproductMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取竞争对手产品草稿", tags = {"竞争对手产品" },  notes = "获取竞争对手产品草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/competitorproducts/getdraft")
    public ResponseEntity<CompetitorProductDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(competitorproductMapping.toDto(competitorproductService.getDraft(new CompetitorProduct())));
    }

    @ApiOperation(value = "检查竞争对手产品", tags = {"竞争对手产品" },  notes = "检查竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitorproducts/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody CompetitorProductDTO competitorproductdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(competitorproductService.checkKey(competitorproductMapping.toDomain(competitorproductdto)));
    }

    @PreAuthorize("hasPermission(this.competitorproductMapping.toDomain(#competitorproductdto),'iBizBusinessCentral-CompetitorProduct-Save')")
    @ApiOperation(value = "保存竞争对手产品", tags = {"竞争对手产品" },  notes = "保存竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitorproducts/save")
    public ResponseEntity<Boolean> save(@RequestBody CompetitorProductDTO competitorproductdto) {
        return ResponseEntity.status(HttpStatus.OK).body(competitorproductService.save(competitorproductMapping.toDomain(competitorproductdto)));
    }

    @PreAuthorize("hasPermission(this.competitorproductMapping.toDomain(#competitorproductdtos),'iBizBusinessCentral-CompetitorProduct-Save')")
    @ApiOperation(value = "批量保存竞争对手产品", tags = {"竞争对手产品" },  notes = "批量保存竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitorproducts/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<CompetitorProductDTO> competitorproductdtos) {
        competitorproductService.saveBatch(competitorproductMapping.toDomain(competitorproductdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-CompetitorProduct-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-CompetitorProduct-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"竞争对手产品" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/competitorproducts/fetchdefault")
	public ResponseEntity<List<CompetitorProductDTO>> fetchDefault(CompetitorProductSearchContext context) {
        Page<CompetitorProduct> domains = competitorproductService.searchDefault(context) ;
        List<CompetitorProductDTO> list = competitorproductMapping.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-CompetitorProduct-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-CompetitorProduct-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"竞争对手产品" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/competitorproducts/searchdefault")
	public ResponseEntity<Page<CompetitorProductDTO>> searchDefault(@RequestBody CompetitorProductSearchContext context) {
        Page<CompetitorProduct> domains = competitorproductService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(competitorproductMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasPermission(this.competitorproductMapping.toDomain(#competitorproductdto),'iBizBusinessCentral-CompetitorProduct-Create')")
    @ApiOperation(value = "根据竞争对手建立竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手建立竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/{competitor_id}/competitorproducts")
    @Transactional
    public ResponseEntity<CompetitorProductDTO> createByCompetitor(@PathVariable("competitor_id") String competitor_id, @RequestBody CompetitorProductDTO competitorproductdto) {
        CompetitorProduct domain = competitorproductMapping.toDomain(competitorproductdto);
        domain.setEntityid(competitor_id);
		competitorproductService.create(domain);
        CompetitorProductDTO dto = competitorproductMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.competitorproductMapping.toDomain(#competitorproductdtos),'iBizBusinessCentral-CompetitorProduct-Create')")
    @ApiOperation(value = "根据竞争对手批量建立竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手批量建立竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/{competitor_id}/competitorproducts/batch")
    public ResponseEntity<Boolean> createBatchByCompetitor(@PathVariable("competitor_id") String competitor_id, @RequestBody List<CompetitorProductDTO> competitorproductdtos) {
        List<CompetitorProduct> domainlist=competitorproductMapping.toDomain(competitorproductdtos);
        for(CompetitorProduct domain:domainlist){
            domain.setEntityid(competitor_id);
        }
        competitorproductService.createBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "competitorproduct" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.competitorproductService.get(#competitorproduct_id),'iBizBusinessCentral-CompetitorProduct-Update')")
    @ApiOperation(value = "根据竞争对手更新竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手更新竞争对手产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/competitors/{competitor_id}/competitorproducts/{competitorproduct_id}")
    @Transactional
    public ResponseEntity<CompetitorProductDTO> updateByCompetitor(@PathVariable("competitor_id") String competitor_id, @PathVariable("competitorproduct_id") String competitorproduct_id, @RequestBody CompetitorProductDTO competitorproductdto) {
        CompetitorProduct domain = competitorproductMapping.toDomain(competitorproductdto);
        domain.setEntityid(competitor_id);
        domain.setRelationshipsid(competitorproduct_id);
		competitorproductService.update(domain);
        CompetitorProductDTO dto = competitorproductMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.competitorproductService.getCompetitorproductByEntities(this.competitorproductMapping.toDomain(#competitorproductdtos)),'iBizBusinessCentral-CompetitorProduct-Update')")
    @ApiOperation(value = "根据竞争对手批量更新竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手批量更新竞争对手产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/competitors/{competitor_id}/competitorproducts/batch")
    public ResponseEntity<Boolean> updateBatchByCompetitor(@PathVariable("competitor_id") String competitor_id, @RequestBody List<CompetitorProductDTO> competitorproductdtos) {
        List<CompetitorProduct> domainlist=competitorproductMapping.toDomain(competitorproductdtos);
        for(CompetitorProduct domain:domainlist){
            domain.setEntityid(competitor_id);
        }
        competitorproductService.updateBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.competitorproductService.get(#competitorproduct_id),'iBizBusinessCentral-CompetitorProduct-Remove')")
    @ApiOperation(value = "根据竞争对手删除竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手删除竞争对手产品")
	@RequestMapping(method = RequestMethod.DELETE, value = "/competitors/{competitor_id}/competitorproducts/{competitorproduct_id}")
    @Transactional
    public ResponseEntity<Boolean> removeByCompetitor(@PathVariable("competitor_id") String competitor_id, @PathVariable("competitorproduct_id") String competitorproduct_id) {
		return ResponseEntity.status(HttpStatus.OK).body(competitorproductService.remove(competitorproduct_id));
    }

    @PreAuthorize("hasPermission(this.competitorproductService.getCompetitorproductByIds(#ids),'iBizBusinessCentral-CompetitorProduct-Remove')")
    @ApiOperation(value = "根据竞争对手批量删除竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手批量删除竞争对手产品")
	@RequestMapping(method = RequestMethod.DELETE, value = "/competitors/{competitor_id}/competitorproducts/batch")
    public ResponseEntity<Boolean> removeBatchByCompetitor(@RequestBody List<String> ids) {
        competitorproductService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.competitorproductMapping.toDomain(returnObject.body),'iBizBusinessCentral-CompetitorProduct-Get')")
    @ApiOperation(value = "根据竞争对手获取竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手获取竞争对手产品")
	@RequestMapping(method = RequestMethod.GET, value = "/competitors/{competitor_id}/competitorproducts/{competitorproduct_id}")
    public ResponseEntity<CompetitorProductDTO> getByCompetitor(@PathVariable("competitor_id") String competitor_id, @PathVariable("competitorproduct_id") String competitorproduct_id) {
        CompetitorProduct domain = competitorproductService.get(competitorproduct_id);
        CompetitorProductDTO dto = competitorproductMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "根据竞争对手获取竞争对手产品草稿", tags = {"竞争对手产品" },  notes = "根据竞争对手获取竞争对手产品草稿")
    @RequestMapping(method = RequestMethod.GET, value = "/competitors/{competitor_id}/competitorproducts/getdraft")
    public ResponseEntity<CompetitorProductDTO> getDraftByCompetitor(@PathVariable("competitor_id") String competitor_id) {
        CompetitorProduct domain = new CompetitorProduct();
        domain.setEntityid(competitor_id);
        return ResponseEntity.status(HttpStatus.OK).body(competitorproductMapping.toDto(competitorproductService.getDraft(domain)));
    }

    @ApiOperation(value = "根据竞争对手检查竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手检查竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/{competitor_id}/competitorproducts/checkkey")
    public ResponseEntity<Boolean> checkKeyByCompetitor(@PathVariable("competitor_id") String competitor_id, @RequestBody CompetitorProductDTO competitorproductdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(competitorproductService.checkKey(competitorproductMapping.toDomain(competitorproductdto)));
    }

    @PreAuthorize("hasPermission(this.competitorproductMapping.toDomain(#competitorproductdto),'iBizBusinessCentral-CompetitorProduct-Save')")
    @ApiOperation(value = "根据竞争对手保存竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手保存竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/{competitor_id}/competitorproducts/save")
    public ResponseEntity<Boolean> saveByCompetitor(@PathVariable("competitor_id") String competitor_id, @RequestBody CompetitorProductDTO competitorproductdto) {
        CompetitorProduct domain = competitorproductMapping.toDomain(competitorproductdto);
        domain.setEntityid(competitor_id);
        return ResponseEntity.status(HttpStatus.OK).body(competitorproductService.save(domain));
    }

    @PreAuthorize("hasPermission(this.competitorproductMapping.toDomain(#competitorproductdtos),'iBizBusinessCentral-CompetitorProduct-Save')")
    @ApiOperation(value = "根据竞争对手批量保存竞争对手产品", tags = {"竞争对手产品" },  notes = "根据竞争对手批量保存竞争对手产品")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/{competitor_id}/competitorproducts/savebatch")
    public ResponseEntity<Boolean> saveBatchByCompetitor(@PathVariable("competitor_id") String competitor_id, @RequestBody List<CompetitorProductDTO> competitorproductdtos) {
        List<CompetitorProduct> domainlist=competitorproductMapping.toDomain(competitorproductdtos);
        for(CompetitorProduct domain:domainlist){
             domain.setEntityid(competitor_id);
        }
        competitorproductService.saveBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-CompetitorProduct-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-CompetitorProduct-Get')")
	@ApiOperation(value = "根据竞争对手获取DEFAULT", tags = {"竞争对手产品" } ,notes = "根据竞争对手获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/competitors/{competitor_id}/competitorproducts/fetchdefault")
	public ResponseEntity<List<CompetitorProductDTO>> fetchCompetitorProductDefaultByCompetitor(@PathVariable("competitor_id") String competitor_id,CompetitorProductSearchContext context) {
        context.setN_entityid_eq(competitor_id);
        Page<CompetitorProduct> domains = competitorproductService.searchDefault(context) ;
        List<CompetitorProductDTO> list = competitorproductMapping.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-CompetitorProduct-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-CompetitorProduct-Get')")
	@ApiOperation(value = "根据竞争对手查询DEFAULT", tags = {"竞争对手产品" } ,notes = "根据竞争对手查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/competitors/{competitor_id}/competitorproducts/searchdefault")
	public ResponseEntity<Page<CompetitorProductDTO>> searchCompetitorProductDefaultByCompetitor(@PathVariable("competitor_id") String competitor_id, @RequestBody CompetitorProductSearchContext context) {
        context.setN_entityid_eq(competitor_id);
        Page<CompetitorProduct> domains = competitorproductService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(competitorproductMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

