package com.qmth.sop.server.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.sop.business.bean.result.DingElementResult;
import com.qmth.sop.business.bean.result.ServiceRegionDetailResult;
import com.qmth.sop.business.bean.result.TBCrmResult;
import com.qmth.sop.business.entity.TBCrm;
import com.qmth.sop.business.service.TBCrmService;
import com.qmth.sop.business.service.TBServiceRegionDetailService;
import com.qmth.sop.common.annotation.OperationLog;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.LogTypeEnum;
import com.qmth.sop.common.enums.ProductTypeEnum;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Objects;

/**
 * 派单信息表 控制器
 *
 * @author: shudonghui
 * @date: 2023-08-14 15:55:18
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Api(tags = "派单信息表 Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_CRM)
public class TBCrmController {


    @Resource
    TBCrmService tBCrmService;
    @Resource
    TBServiceRegionDetailService tbServiceRegionDetailService;


    @ApiOperation(value = "派单信息表查询接口")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "派单信息表查询结果", response = TBCrmResult.class)})
    public Result query(
            @ApiParam(value = "服务单元") @RequestParam(required = false) Long serviceId,
            @ApiParam(value = "是否绑定") @RequestParam(required = false) Boolean isBind,
            @ApiParam(value = "大区经理") @RequestParam(required = false) Long leadId,
            @ApiParam(value = "派单人") @RequestParam(required = false) Long crmUserId,
            @ApiParam(value = "客户类型") @RequestParam(required = false) ProductTypeEnum type,
            @ApiParam(value = "客户名称（模糊查询）") @RequestParam(required = false) String custom,
            @ApiParam(value = "项目单号（模糊查询） ") @RequestParam(required = false) String crmNo,
            @ApiParam(value = "派单时间开始") @RequestParam(required = false) Long startTime,
            @ApiParam(value = "派单时间结束") @RequestParam(required = false) Long endTime,
            @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
            @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        IPage<TBCrmResult> resultIPage = tBCrmService.query(new Page<>(pageNumber, pageSize), serviceId, isBind, leadId, crmUserId, type, custom, crmNo, startTime, endTime);

        return ResultUtil.ok(resultIPage);
    }


    @ApiOperation(value = "派单信息表新增修改接口")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.EDIT)
    public Result save(@Valid @ApiParam(value = "派单信息表信息", required = true) @RequestBody(required = true) TBCrm tBCrm, BindingResult bindingResult) throws InterruptedException {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultUtil.ok(tBCrmService.saveTBCrm(tBCrm));
    }


    @ApiOperation(value = "派单信息表删除接口")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.DELETE)
    public Result delete(@ApiParam(value = "派单信息表id", required = true) @RequestParam(required = true) long id) {
        return ResultUtil.ok(tBCrmService.delete(id));
    }


    @ApiOperation(value = "派单信息表获取单个接口")
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "派单信息表信息", response = TBCrm.class)})
    public Result get(@ApiParam(value = "派单信息表id", required = true) @RequestParam long id) {
        return ResultUtil.ok(tBCrmService.getById(id));
    }

    //批量禁用
    @ApiOperation(value = "批量禁用接口")
    @RequestMapping(value = "/batchDisable", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.UPDATE)
    public Result batchDisable(@ApiParam(value = "派单信息表id", required = true) @RequestParam(required = true) long[] crmIds) {
        return ResultUtil.ok(tBCrmService.batchDisable(crmIds));
    }

    //统计待划定数量

    @ApiOperation(value = "统计待划定数量接口")
    @RequestMapping(value = "/countWaitZone", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    public Result countWaitZone(@ApiParam(value = "服务单元") @RequestParam(required = false) Long serviceId,
                                @ApiParam(value = "是否绑定") @RequestParam(required = false) Boolean isBind,
                                @ApiParam(value = "大区经理") @RequestParam(required = false) Long leadId,
                                @ApiParam(value = "派单人") @RequestParam(required = false) Long crmUserId,
                                @ApiParam(value = "客户类型") @RequestParam(required = false) ProductTypeEnum type,
                                @ApiParam(value = "客户名称（模糊查询）") @RequestParam(required = false) String custom,
                                @ApiParam(value = "项目单号（模糊查询） ") @RequestParam(required = false) String crmNo,
                                @ApiParam(value = "派单时间开始") @RequestParam(required = false) Long startTime,
                                @ApiParam(value = "派单时间结束") @RequestParam(required = false) Long endTime) {
        return ResultUtil.ok(tBCrmService.count(serviceId, isBind, leadId, crmUserId, type, custom, crmNo, startTime, endTime));
    }

    @ApiOperation(value = "查询项目派单信息")
    @RequestMapping(value = "/crm_project_info", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = DingElementResult.class)})
    public Result findDingInfo(@ApiParam(value = "sop单号") @RequestParam(required = false) String sopNo,
                               @ApiParam(value = "crm单号") @RequestParam(required = false) String crmNo) {
        return ResultUtil.ok(tBCrmService.findCrmProjectBySopNoOrCrmNo(sopNo, crmNo));
    }

    @ApiOperation(value = "派单数据刷新（测试用）")
    @RequestMapping(value = "/crm_update", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    @Aac(auth = false)
    public void updateData() {
        List<TBCrm> tbCrmList = tBCrmService.list();
        for (TBCrm tbCrm : tbCrmList) {
            Long serviceId = tbCrm.getServiceId();
            String crmNo = tbCrm.getCrmNo();
            Long leadId = tbCrm.getLeadId();

            if (serviceId != null && serviceId > 0) {
                ServiceRegionDetailResult result = tbServiceRegionDetailService.findRegionDetail(serviceId, crmNo);
                if (Objects.nonNull(result)) {
                    if (!Objects.equals(result.getLeadId(), leadId)) {
                        System.out.println("大区经理不匹配 : " + crmNo);
                    }
                    tbCrm.setRegionId(result.getServiceRegionId());
                    tbCrm.setRegionDetailId(result.getServiceRegionDetailId());
                    tbCrm.setLeadId(result.getLeadId());
                }
            }
            tBCrmService.updateById(tbCrm);
        }
    }
}