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.Lead;
import cn.ibizlab.businesscentral.core.sales.service.ILeadService;
import cn.ibizlab.businesscentral.core.sales.filter.LeadSearchContext;

@Slf4j
@Api(tags = {"潜在顾客" })
@RestController("CentralApi-lead")
@RequestMapping("")
public class LeadResource {

    @Autowired
    public ILeadService leadService;

    @Autowired
    @Lazy
    public LeadMapping leadMapping;

    @PreAuthorize("hasPermission(this.leadService.get(#lead_id),'iBizBusinessCentral-Lead-Update')")
    @ApiOperation(value = "更新潜在顾客", tags = {"潜在顾客" },  notes = "更新潜在顾客")
	@RequestMapping(method = RequestMethod.PUT, value = "/leads/{lead_id}")
    @Transactional
    public ResponseEntity<LeadDTO> update(@PathVariable("lead_id") String lead_id, @RequestBody LeadDTO leaddto) {
		Lead domain  = leadMapping.toDomain(leaddto);
        domain .setLeadid(lead_id);
		leadService.update(domain );
		LeadDTO dto = leadMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.leadService.getLeadByEntities(this.leadMapping.toDomain(#leaddtos)),'iBizBusinessCentral-Lead-Update')")
    @ApiOperation(value = "批量更新潜在顾客", tags = {"潜在顾客" },  notes = "批量更新潜在顾客")
	@RequestMapping(method = RequestMethod.PUT, value = "/leads/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<LeadDTO> leaddtos) {
        leadService.updateBatch(leadMapping.toDomain(leaddtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "获取潜在顾客草稿", tags = {"潜在顾客" },  notes = "获取潜在顾客草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/leads/getdraft")
    public ResponseEntity<LeadDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(leadMapping.toDto(leadService.getDraft(new Lead())));
    }

    @ApiOperation(value = "检查潜在顾客", tags = {"潜在顾客" },  notes = "检查潜在顾客")
	@RequestMapping(method = RequestMethod.POST, value = "/leads/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody LeadDTO leaddto) {
        return  ResponseEntity.status(HttpStatus.OK).body(leadService.checkKey(leadMapping.toDomain(leaddto)));
    }

    @PostAuthorize("hasPermission(this.leadMapping.toDomain(returnObject.body),'iBizBusinessCentral-Lead-Get')")
    @ApiOperation(value = "获取潜在顾客", tags = {"潜在顾客" },  notes = "获取潜在顾客")
	@RequestMapping(method = RequestMethod.GET, value = "/leads/{lead_id}")
    public ResponseEntity<LeadDTO> get(@PathVariable("lead_id") String lead_id) {
        Lead domain = leadService.get(lead_id);
        LeadDTO dto = leadMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.leadMapping.toDomain(#leaddto),'iBizBusinessCentral-Lead-Save')")
    @ApiOperation(value = "保存潜在顾客", tags = {"潜在顾客" },  notes = "保存潜在顾客")
	@RequestMapping(method = RequestMethod.POST, value = "/leads/save")
    public ResponseEntity<Boolean> save(@RequestBody LeadDTO leaddto) {
        return ResponseEntity.status(HttpStatus.OK).body(leadService.save(leadMapping.toDomain(leaddto)));
    }

    @PreAuthorize("hasPermission(this.leadMapping.toDomain(#leaddtos),'iBizBusinessCentral-Lead-Save')")
    @ApiOperation(value = "批量保存潜在顾客", tags = {"潜在顾客" },  notes = "批量保存潜在顾客")
	@RequestMapping(method = RequestMethod.POST, value = "/leads/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<LeadDTO> leaddtos) {
        leadService.saveBatch(leadMapping.toDomain(leaddtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.leadMapping.toDomain(#leaddto),'iBizBusinessCentral-Lead-Create')")
    @ApiOperation(value = "新建潜在顾客", tags = {"潜在顾客" },  notes = "新建潜在顾客")
	@RequestMapping(method = RequestMethod.POST, value = "/leads")
    @Transactional
    public ResponseEntity<LeadDTO> create(@RequestBody LeadDTO leaddto) {
        Lead domain = leadMapping.toDomain(leaddto);
		leadService.create(domain);
        LeadDTO dto = leadMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.leadMapping.toDomain(#leaddtos),'iBizBusinessCentral-Lead-Create')")
    @ApiOperation(value = "批量新建潜在顾客", tags = {"潜在顾客" },  notes = "批量新建潜在顾客")
	@RequestMapping(method = RequestMethod.POST, value = "/leads/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<LeadDTO> leaddtos) {
        leadService.createBatch(leadMapping.toDomain(leaddtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.leadService.get(#lead_id),'iBizBusinessCentral-Lead-Remove')")
    @ApiOperation(value = "删除潜在顾客", tags = {"潜在顾客" },  notes = "删除潜在顾客")
	@RequestMapping(method = RequestMethod.DELETE, value = "/leads/{lead_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("lead_id") String lead_id) {
         return ResponseEntity.status(HttpStatus.OK).body(leadService.remove(lead_id));
    }

    @PreAuthorize("hasPermission(this.leadService.getLeadByIds(#ids),'iBizBusinessCentral-Lead-Remove')")
    @ApiOperation(value = "批量删除潜在顾客", tags = {"潜在顾客" },  notes = "批量删除潜在顾客")
	@RequestMapping(method = RequestMethod.DELETE, value = "/leads/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        leadService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Lead-Default-all')")
	@ApiOperation(value = "获取DEFAULT", tags = {"潜在顾客" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/leads/fetchdefault")
	public ResponseEntity<List<LeadDTO>> fetchDefault(LeadSearchContext context) {
        Page<Lead> domains = leadService.searchDefault(context) ;
        List<LeadDTO> list = leadMapping.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-Lead-Default-all')")
	@ApiOperation(value = "查询DEFAULT", tags = {"潜在顾客" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/leads/searchdefault")
	public ResponseEntity<Page<LeadDTO>> searchDefault(@RequestBody LeadSearchContext context) {
        Page<Lead> domains = leadService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(leadMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

