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.Opportunity;
import cn.ibizlab.businesscentral.core.sales.service.IOpportunityService;
import cn.ibizlab.businesscentral.core.sales.filter.OpportunitySearchContext;

@Slf4j
@Api(tags = {"商机" })
@RestController("CentralApi-opportunity")
@RequestMapping("")
public class OpportunityResource {

    @Autowired
    public IOpportunityService opportunityService;

    @Autowired
    @Lazy
    public OpportunityMapping opportunityMapping;

    @PostAuthorize("hasPermission(this.opportunityMapping.toDomain(returnObject.body),'iBizBusinessCentral-Opportunity-Get')")
    @ApiOperation(value = "获取商机", tags = {"商机" },  notes = "获取商机")
	@RequestMapping(method = RequestMethod.GET, value = "/opportunities/{opportunity_id}")
    public ResponseEntity<OpportunityDTO> get(@PathVariable("opportunity_id") String opportunity_id) {
        Opportunity domain = opportunityService.get(opportunity_id);
        OpportunityDTO dto = opportunityMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取商机草稿", tags = {"商机" },  notes = "获取商机草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/opportunities/getdraft")
    public ResponseEntity<OpportunityDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(opportunityMapping.toDto(opportunityService.getDraft(new Opportunity())));
    }

    @PreAuthorize("hasPermission(this.opportunityMapping.toDomain(#opportunitydto),'iBizBusinessCentral-Opportunity-Create')")
    @ApiOperation(value = "新建商机", tags = {"商机" },  notes = "新建商机")
	@RequestMapping(method = RequestMethod.POST, value = "/opportunities")
    @Transactional
    public ResponseEntity<OpportunityDTO> create(@RequestBody OpportunityDTO opportunitydto) {
        Opportunity domain = opportunityMapping.toDomain(opportunitydto);
		opportunityService.create(domain);
        OpportunityDTO dto = opportunityMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.opportunityMapping.toDomain(#opportunitydtos),'iBizBusinessCentral-Opportunity-Create')")
    @ApiOperation(value = "批量新建商机", tags = {"商机" },  notes = "批量新建商机")
	@RequestMapping(method = RequestMethod.POST, value = "/opportunities/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<OpportunityDTO> opportunitydtos) {
        opportunityService.createBatch(opportunityMapping.toDomain(opportunitydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.opportunityService.get(#opportunity_id),'iBizBusinessCentral-Opportunity-Remove')")
    @ApiOperation(value = "删除商机", tags = {"商机" },  notes = "删除商机")
	@RequestMapping(method = RequestMethod.DELETE, value = "/opportunities/{opportunity_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("opportunity_id") String opportunity_id) {
         return ResponseEntity.status(HttpStatus.OK).body(opportunityService.remove(opportunity_id));
    }

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

    @PreAuthorize("hasPermission(this.opportunityService.get(#opportunity_id),'iBizBusinessCentral-Opportunity-Update')")
    @ApiOperation(value = "更新商机", tags = {"商机" },  notes = "更新商机")
	@RequestMapping(method = RequestMethod.PUT, value = "/opportunities/{opportunity_id}")
    @Transactional
    public ResponseEntity<OpportunityDTO> update(@PathVariable("opportunity_id") String opportunity_id, @RequestBody OpportunityDTO opportunitydto) {
		Opportunity domain  = opportunityMapping.toDomain(opportunitydto);
        domain .setOpportunityid(opportunity_id);
		opportunityService.update(domain );
		OpportunityDTO dto = opportunityMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.opportunityService.getOpportunityByEntities(this.opportunityMapping.toDomain(#opportunitydtos)),'iBizBusinessCentral-Opportunity-Update')")
    @ApiOperation(value = "批量更新商机", tags = {"商机" },  notes = "批量更新商机")
	@RequestMapping(method = RequestMethod.PUT, value = "/opportunities/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<OpportunityDTO> opportunitydtos) {
        opportunityService.updateBatch(opportunityMapping.toDomain(opportunitydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "检查商机", tags = {"商机" },  notes = "检查商机")
	@RequestMapping(method = RequestMethod.POST, value = "/opportunities/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody OpportunityDTO opportunitydto) {
        return  ResponseEntity.status(HttpStatus.OK).body(opportunityService.checkKey(opportunityMapping.toDomain(opportunitydto)));
    }

    @PreAuthorize("hasPermission(this.opportunityMapping.toDomain(#opportunitydto),'iBizBusinessCentral-Opportunity-Save')")
    @ApiOperation(value = "保存商机", tags = {"商机" },  notes = "保存商机")
	@RequestMapping(method = RequestMethod.POST, value = "/opportunities/save")
    public ResponseEntity<Boolean> save(@RequestBody OpportunityDTO opportunitydto) {
        return ResponseEntity.status(HttpStatus.OK).body(opportunityService.save(opportunityMapping.toDomain(opportunitydto)));
    }

    @PreAuthorize("hasPermission(this.opportunityMapping.toDomain(#opportunitydtos),'iBizBusinessCentral-Opportunity-Save')")
    @ApiOperation(value = "批量保存商机", tags = {"商机" },  notes = "批量保存商机")
	@RequestMapping(method = RequestMethod.POST, value = "/opportunities/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<OpportunityDTO> opportunitydtos) {
        opportunityService.saveBatch(opportunityMapping.toDomain(opportunitydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Opportunity-Default-all')")
	@ApiOperation(value = "获取DEFAULT", tags = {"商机" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/opportunities/fetchdefault")
	public ResponseEntity<List<OpportunityDTO>> fetchDefault(OpportunitySearchContext context) {
        Page<Opportunity> domains = opportunityService.searchDefault(context) ;
        List<OpportunityDTO> list = opportunityMapping.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-Opportunity-Default-all')")
	@ApiOperation(value = "查询DEFAULT", tags = {"商机" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/opportunities/searchdefault")
	public ResponseEntity<Page<OpportunityDTO>> searchDefault(@RequestBody OpportunitySearchContext context) {
        Page<Opportunity> domains = opportunityService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(opportunityMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

