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.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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

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

@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;

    @GetMapping("/dealing")
    @ApiOperation("显示处理中的业务")
    public Result findLoanCaseByIsComplete(@RequestParam("isComplete") Boolean isComplete ){
        List<LoanCaseVO> loanCases = loanService.findLoanCaseByIsComplete(isComplete,false);
        return ResultUtil.success("success",loanCases);
    }

    @GetMapping("/{id}/details")
    @ApiOperation("显示业务详情")
    public Result findLoanCaseDetails(@PathVariable("id")Long caseId){
        return ResultUtil.success("success",loanService.findLoanCaseDetailsById(caseId));
    }

    @PostMapping("/create")
    @ApiOperation("创建业务")
    public Result createLoanCase(@RequestParam("customerId") Long customerId){
        //创建订单
        LoanCaseVO loanCase = loanService.addLoanCaseByCustomerId(customerId);
        //创建流程
        stepService.addStepByCaseId(loanCase.getId());
        return ResultUtil.success("success",loanCase);
    }

    /*
    1.添加业务，开启业务流程
    2.绑定阶段和业务
     */
    @PostMapping("/{id}")//请求中操作复杂，putmapping仅适用于更新操作
    @ApiOperation("提交/保存业务")
    public Result saveLoanCase(@PathVariable("id")Long caseId, @RequestBody LoanCaseDTO loanCaseDTO, @RequestParam("IsComplete")Boolean isComplete){//isComplete 若保存，则设置为未完成，若提交，则设置为已完成
        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.BUSINESS_ACCEPT.getLabel(),caseId);
        if(stepVO.getStatus().equals(StepEnum.COMPLETED.getMsg()))
            throw new DescribeException(ExceptionEnum.LOANCASE_IS_Completed);

        //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));
        }
//        //4.设置附件
//        for(DocumentDTO documentDTO : loanCaseDTO.getDocuments()){
//            //若存在，则修改
//
//            //若不存在，则添加
//        }
        //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.设置阶段负责人与状态（如果第一个人是辅办人员，那第二个人必须是主办）
        stepService.updateUserByCaseId(StepPropertyEnum.BUSINESS_ACCEPT.getLabel(),BaseContext.getCurrentId(),caseId);
        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);
        }

        //8.消息推送

        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");
//    }
//


    @PutMapping("/{id}/preApprove/cancel")
    @ApiOperation("取消预审")
    public Result cancelPreApprove(@PathVariable("id")Long caseId){
        //设置预审核阶段已完成，审批阶段开始
        completePreApproveMethod(caseId);
        StepVO stepVO = 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");
    }

//    @PutMapping("/{id}/preApprove/commit")
//    @ApiOperation("预审提交")
//    public Result preApproveCommit(@RequestBody ApprovalRecordDTO approvalRecordDTO, @PathVariable("id")Long caseId ){
//        //修改阶段负责人
//        StepVO  stepVo = stepService.updateUserByCaseId(approvalRecordDTO.getStepName(), approvalRecordDTO.getApproverId(), caseId);
//        //添加审批记录
//        approveService.addApprovalRecord(approvalRecordDTO);
//        //修改阶段状态
//        if (stepVo.getUserId2()!= null)
//            completePreApproveMethod(caseId);
//
//        List<StepVO> list = stepService.getStepByCaseId(caseId);
//
//        return ResultUtil.success("success",list);
//    }
//
//    @PutMapping("/{id}/preApprove/back")
//    @ApiOperation("预审退回(未)")//驳回后的负责人还是同一个吗
//    public Result preApproveBack(@RequestBody ApprovalRecordDTO approvalRecordDTO, @PathVariable("id")Long caseId ){
//        //修改阶段负责人
//        stepService.updateUserByCaseId(approvalRecordDTO.getStepName(),approvalRecordDTO.getApproverId(),caseId);
//        //添加审批记录
//        approveService.addApprovalRecord(approvalRecordDTO);
//        //修改阶段状态
//        completePreApproveMethod(caseId);
//
//        List<StepVO> list = stepService.getStepByCaseId(caseId);
//        return ResultUtil.success("success",list);
//    }

    private void completePreApproveMethod(Long caseId){
        //设置预审核阶段已完成，审批阶段开始
        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);
    }

}