package com.loan.system.controller.wechat;

import com.loan.system.context.BaseContext;
import com.loan.system.domain.dto.*;
import com.loan.system.domain.entity.*;
import com.loan.system.domain.enums.ExceptionEnum;
import com.loan.system.domain.enums.RoleEnum;
import com.loan.system.domain.enums.StepEnum;
import com.loan.system.domain.enums.StepPropertyEnum;
import com.loan.system.domain.pojo.Result;
import com.loan.system.domain.vo.LoanCaseVO;
import com.loan.system.domain.vo.StepVO;
import com.loan.system.exception.DescribeException;
import com.loan.system.service.*;
import com.loan.system.utils.ResultUtil;
import com.mysql.cj.protocol.Message;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.loan.system.domain.enums.ExceptionEnum.STEP_HAS_NOT_PROCESS;
import static com.loan.system.domain.enums.ExceptionEnum.STEP_USER_NOT_EXPECTED;

@RestController
@RequestMapping("/wechat/case")
@Api(tags = "业务受理接口")
public class LoanController {

    @Autowired
    private LoanService loanService;
    @Autowired
    private StepService stepService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private ApprovalService approveService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerOtherService customerOtherService;
    @Autowired
    private CollateralService collateralService;
    @Autowired
    private ContractAndCollateralService contractAndCollateralService;
    @Autowired
    private MessageService messageService;

    @GetMapping("/dealing")
    @ApiOperation("显示处理中的业务")
    @PreAuthorize("@pms.hasAnyRoles('SYSTEM_ADMIN','APPROVER','LEAD_SALES', 'ASSIST_SALES', 'FINANCE', 'BACK_OFFICE')")
    public Result findLoanCaseByIsComplete(@RequestParam(value = "isComplete",defaultValue =  "false") Boolean isComplete ,Integer pageNum, Integer pageSize){
        List<LoanCaseVO> loanCases = loanService.findLoanCaseByIsComplete(pageNum, pageSize,isComplete,false);
        return ResultUtil.success("success",loanCases);
    }

    @GetMapping("/{id}/details")
    @ApiOperation("显示业务详情")
    @PreAuthorize("@pms.hasAnyRoles('SYSTEM_ADMIN','APPROVER','LEAD_SALES', 'ASSIST_SALES', 'FINANCE', 'BACK_OFFICE')")
    public Result findLoanCaseDetails(@PathVariable("id")Long caseId){
        return ResultUtil.success("success",loanService.findLoanCaseDetailsById(caseId));
    }

    @PostMapping("/create")
    @ApiOperation("创建业务")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES','ASSIST_SALES')")
    public Result createLoanCase(@RequestParam("customerId") Long customerId){
        if(!customerService.existsByIdAndIsDelete(customerId))
            throw new DescribeException(ExceptionEnum.USER_NOT_EXIST);
        //创建订单
        LoanCaseVO loanCase = loanService.addLoanCaseByCustomerId(customerId);
        //创建流程
        stepService.addStepByCaseId(loanCase.getId());
        //设置当前处理人
        stepService.updateUserByCaseId(StepPropertyEnum.BUSINESS_ACCEPT.getLabel(),BaseContext.getCurrentId(),loanCase.getId());
        return ResultUtil.success("success",loanCase);
    }

    /*
    1.添加业务，开启业务流程
    2.绑定阶段和业务
     */
    @PostMapping("/{id}")//请求中操作复杂，putmapping仅适用于更新操作
    @ApiOperation("提交/保存业务")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES', 'ASSIST_SALES')")
    public Result saveLoanCase(@PathVariable("id")Long caseId, @RequestBody LoanCaseDTO loanCaseDTO, @RequestParam("isComplete")Boolean isComplete){//isComplete 若保存，则设置为未完成，若提交，则设置为已完成
        if(!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        if (ObjectUtils.isEmpty(loanCaseDTO))
            throw new DescribeException(ExceptionEnum.INPUT_ERROR);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.BUSINESS_ACCEPT.getLabel(),caseId);
        if(ObjectUtils.isEmpty(stepVO) || !stepVO.getStatus().equals(StepEnum.PROCESS.getMsg()))
            throw new DescribeException(STEP_HAS_NOT_PROCESS);

        Long currentId = stepVO.getUserId1();
        if(currentId!=null && !BaseContext.getCurrentId().equals(currentId)){
            throw new DescribeException(STEP_USER_NOT_EXPECTED);
        }

        //1.补充业务信息
        loanService.updateLoanCaseById(loanCaseDTO,caseId);

        //2.设置合同（若存在则修改）
        contractService.deleteAllByCaseId(caseId);
        List<Contract> contracts = new ArrayList<>();//新增的合同
        for(ContractDTO contractDTO : loanCaseDTO.getContracts()){
            Contract c = contractService.saveContract(contractDTO);

            contracts.add(c);
        }

        //3.设置押品
        collateralService.deleteAllByCaseId(caseId);
        List<Long> collateralIds = new ArrayList<>();
        for(CollateralDTO collateralDTO : loanCaseDTO.getCollateral()){
            Collateral collateral = collateralService.saveCollateral(collateralDTO);

            collateralIds.add(collateral.getId());
        }

        //4.设置合同、押品关联
        contractAndCollateralService.deleteAllByCaseId(caseId);
        for(int i=0 ; i < loanCaseDTO.getCollateralAndContract().size(); i++){
            Contract contract = contracts.get( i);
            List<Integer> collaterals = loanCaseDTO.getCollateralAndContract().get(i).get(contract.getBusinessAttr());

            for (Integer collateralId : collaterals)
                contractAndCollateralService.addContractAndCollateral(contract.getId(),collateralIds.get(collateralId-1),caseId);
        }

        //5.添加其它客户
        customerOtherService.deleteAllByCaseId(caseId);
        if(!ObjectUtils.isEmpty(loanCaseDTO.getCustomers1()))
            customerOtherService.addCustomers(loanCaseDTO.getCustomers1());

        if (!ObjectUtils.isEmpty(loanCaseDTO.getCustomers2()))
            customerOtherService.addCustomers(loanCaseDTO.getCustomers2());


        //6.设置客户婚姻
        customerService.updateMarriedStatusById(loanCaseDTO.getCustomerId(),loanCaseDTO.getMarriedStatus());

        //7.设置阶段负责人与状态（如果第一个人是辅办人员，那第二个人必须是主办）
        if(isComplete){
            stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(),StepPropertyEnum.BUSINESS_ACCEPT_PARENT.getLabel(),caseId);
            stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(),StepPropertyEnum.BUSINESS_ACCEPT.getLabel(),caseId);
            //设置当阶段为完成，下阶段为开始
            stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.PRE_TRIAL_PARENT.getLabel(),caseId);
            stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.PRE_TRIAL.getLabel(),caseId);

            //TODO:8.微信推送预审通过消息和通知下一环节
//            SysMessage message = new SysMessage();
//            message.setMobile(null);
 //           message.setUserRole(RoleEnum.ASSIST_SALES.getMsg());
//            message.setMessageTitle("");
//            message.setMessageContent("");
 //           message.setStepName(StepPropertyEnum.PRE_TRIAL.getLabel());
  //          message.setRelatedId(caseId);
//            message.setRelatedType("");
 //           messageService.addMessage(message);
//            wxService.sendTemplateMessage(loanCase.getCustomer().getMobile(),new TemplateMessage());

        }

        return ResultUtil.success("success");
    }


//    @PostMapping("/{id}/save")//请求中操作复杂，putmapping仅适用于更新操作
//    @ApiOperation("随时保存业务（未）")
//    public Result saveLoanCase(@PathVariable("id")Long caseId, @RequestBody LoanCaseDTO loanCaseDTO, @RequestParam("IsComplete")Boolean isComplete){//isComplete 若保存，则设置为未完成，若提交，则设置为已完成
//        //1.补充业务信息
//       loanService.updateLoanCaseById(loanCaseDTO,caseId);
//
//        //2.设置合同（若存在则修改）
//        List<Contract> contract = new ArrayList<>();//新增的合同
//        for(ContractDTO contractDTO : loanCaseDTO.getContracts()){
//            //contract.setCaseId(caseId);
//            Contract c =contractService.findContractByCaseIdAndBusinessAttr( caseId,contractDTO.getBusinessAttr(),false);
//            if(ObjectUtils.isEmpty(c))
//                c = contractService.saveContract(contractDTO);
//            else
//                contractService.updateContractById(c.getId(),contractDTO,false);
//
//            //考虑删除合同/押品的情况
//            contract.add(c);
//        }
//
//        //3.设置押品
//        List<Long> collateralIds = new ArrayList<>();
//        for(CollateralDTO collateralDTO : loanCaseDTO.getCollateral()){
//            Collateral collateral = collateralService.findCollateralByNameAndCaseId(collateralDTO.getCollateralName(),caseId,false);
//            if(ObjectUtils.isEmpty(collateral))
//                collateral = collateralService.saveCollateral(collateralDTO);
//            else
//                collateralService.updateCollateralById(collateral.getId(),collateralDTO,false);
//
//            collateralIds.add(collateral.getId());
//        }
////        //4.设置附件
////        for(DocumentDTO documentDTO : loanCaseDTO.getDocuments()){
////            //若存在，则修改
////
////            //若不存在，则添加
////        }
//
//        //5.设置客户婚姻
//        customerService.updateMarriedStatusById(loanCaseDTO.getCustomerId(),loanCaseDTO.getMarriedStatus());
//
//        //6.设置阶段负责人与状态（如果第一个人是辅办人员，那第二个人必须是主办）
//        stepService.updateUserByCaseId(StepPropertyEnum.BUSINESS_ACCEPT.getLabel(),BaseContext.getCurrentId(),caseId);
//
//        return ResultUtil.success("success");
//    }
//


    @PostMapping("/{id}/preApprove/cancel")
    @ApiOperation("取消预审")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES', 'ASSIST_SALES')")
    public Result cancelPreApprove(@PathVariable("id")Long caseId){
        if(!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO step = stepService.findByStepNameAndCaseId(StepPropertyEnum.PRE_TRIAL.getLabel(),caseId);
        if(ObjectUtils.isEmpty( step)||!step.getStatus().equals(StepEnum.PROCESS.getMsg()))
            throw new DescribeException(STEP_HAS_NOT_PROCESS);

        Long currentId = step.getUserId1();
        if(currentId!=null && !BaseContext.getCurrentId().equals(currentId)){
            throw new DescribeException(STEP_USER_NOT_EXPECTED);
        }

        //设置预审核阶段已完成，审批阶段开始
        stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(),StepPropertyEnum.PRE_TRIAL_PARENT.getLabel(),caseId);
        stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(),StepPropertyEnum.PRE_TRIAL.getLabel(),caseId);

        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.APPROVAL_PARENT.getLabel(),caseId);
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.APPROVAL.getLabel(),caseId);

        stepService.updateUserByCaseId(StepPropertyEnum.PRE_TRIAL.getLabel(), BaseContext.getCurrentId(), caseId);

        //添加审批记录
        approveService.addPreApprovalRecord(StepPropertyEnum.PRE_TRIAL.getLabel(),BaseContext.getCurrentId(),caseId);

        //List<StepVO> list = stepService.getStepByCaseId(caseId);

        return ResultUtil.success("success");
    }


}