package com.loan.system.controller.wechat;

import com.loan.system.context.BaseContext;
import com.loan.system.domain.dto.ApprovalRecordDTO;
import com.loan.system.domain.dto.DisbursementDTO;
import com.loan.system.domain.dto.DisbursementRecordDTO;
import com.loan.system.domain.entity.*;
import com.loan.system.domain.enums.*;
import com.loan.system.domain.pojo.Result;
import com.loan.system.domain.vo.*;
import com.loan.system.exception.DescribeException;
import com.loan.system.service.*;
import com.loan.system.service.DisbursementRecordService;
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.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.loan.system.domain.enums.ExceptionEnum.*;

@RestController
@RequestMapping("/wechat/disbursement")
@Api(tags = "出款接口")
public class DisbursementController {
    @Autowired
    private DisbursementService disbursementService;
    @Autowired
    private StepService stepService;
    @Autowired
    private LoanService loanService;
    @Autowired
    private DocumentService documentService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private ContractSeqService contractSeqService;
    @Autowired
    private ApprovalService approvalService;
    @Autowired
    private UserService userService;
    @Autowired
    private DisbursementRecordService disbursementRecordService;
    @Autowired
    private RepaymentService repaymentService;
    @Autowired
    private MessageService messageService;

    @GetMapping("/planDetails")
    @ApiOperation("显示计划详情")//与loanContraller的方法一致，但为了规范
    @PreAuthorize("@pms.hasAnyRoles('SYSTEM_ADMIN','APPROVER','LEAD_SALES', 'ASSIST_SALES', 'FINANCE', 'BACK_OFFICE')")
    public Result findLoanCaseDetails(@RequestParam Long caseId){
        if(caseId == null||!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        DisbursementDetailVO disbursementDetailVO = disbursementService.getLoanCaseAndCustomerByCaseId(caseId);
        //填充
        Disbursement disbursementByCaseId = disbursementService.getDisbursementByCaseId(caseId);
        disbursementDetailVO.setDisbursementAmount(disbursementByCaseId.getPlannedAmount());
        disbursementDetailVO.setCurrentLocation(disbursementByCaseId.getPlannedLocation());

        return ResultUtil.success("success",disbursementDetailVO);
    }


    @PostMapping
    @ApiOperation(value = "上报出款计划")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES', 'ASSIST_SALES')")
    public Result addDisbursement(@RequestBody DisbursementDTO disbursementDTO) {
        if(ObjectUtils.isEmpty(disbursementDTO)||disbursementDTO.getCaseId()==null)
            throw new DescribeException(INPUT_ERROR);

        if(!loanService.existsByIdAndIsDelete(disbursementDTO.getCaseId()))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.PLAN_REPORT.getLabel(),disbursementDTO.getCaseId());
        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);
        }

        //上报计划
        DisbursementVO disbursementVO = disbursementService.addDisbursement(disbursementDTO);

        //修改状态
        stepService.updateUserByCaseId(StepPropertyEnum.PLAN_REPORT.getLabel(), BaseContext.getCurrentId(), disbursementDTO.getCaseId());
        stepService.updateStatusByCaseId( StepEnum.COMPLETED.getMsg(), StepPropertyEnum.PLAN_REPORT.getLabel(),disbursementDTO.getCaseId());
        stepService.updateStatusByCaseId( StepEnum.PROCESS.getMsg(),StepPropertyEnum.PLAN_AUDIT.getLabel(),disbursementDTO.getCaseId());

        return ResultUtil.success("success",disbursementVO);
    }

    @GetMapping("/approvalDetails")
    @ApiOperation("显示计划审批详情")//与loanContraller的方法一致，但为了规范
    @PreAuthorize("@pms.hasAnyRoles('SYSTEM_ADMIN','APPROVER','LEAD_SALES', 'ASSIST_SALES', 'FINANCE', 'BACK_OFFICE')")
    public Result findLoanCaseDetails2(@RequestParam Long caseId){
        if(caseId == null||!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        DisbursementDetailVO disbursementDetailVO = disbursementService.getLoanCaseAndCustomerByCaseId(caseId);
        //填充
        ApprovalRecordVO approvalRecord = approvalService.findByCaseIdAndIsDeleteAndStepName(caseId,StepPropertyEnum.PLAN_AUDIT.getLabel(),BaseContext.getCurrentId());
        disbursementDetailVO.setApprovalComment(approvalRecord.getComments());
        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.REPAY_START.getLabel(),caseId);
        disbursementDetailVO.setRepaymentUser(userService.findByIdAndIsDelete(stepVO.getUserId1()));

        return ResultUtil.success("success",disbursementDetailVO);

    }

    //TODO:选择回款业务员-在userController中

    @PostMapping("/approval/pass1")
    @ApiOperation(value = "计划审批")
    @PreAuthorize("@pms.hasRole('APPROVER')")
    public Result disbursementPlanApproval(@RequestBody ApprovalRecordDTO approvalRecordDTO, @RequestParam Long chargeId) {
        if (ObjectUtils.isEmpty(approvalRecordDTO)||approvalRecordDTO.getCaseId()==null)
            throw new DescribeException(INPUT_ERROR);

        Long caseId = approvalRecordDTO.getCaseId();
        if(!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.PLAN_AUDIT.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);
        }
        //选择回款负责人,开启回款开始环节，创建回款单
        stepService.updateUserId1ByCaseIdAndStepName(StepPropertyEnum.REPAY_START.getLabel(),chargeId,caseId);
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.REPAY_PARENT.getLabel(),caseId);
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.REPAY_START.getLabel(),caseId);

        Repayment repayment = new Repayment();
        repayment.setCaseId(caseId);
        repayment.setStartUserId(chargeId);
        repayment.setTotalAmount(disbursementService.getDisbursementByCaseId(caseId).getPlannedAmount());
        repaymentService.addRepayment(repayment);

        //填写审批意见
        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(caseId,StepPropertyEnum.PLAN_AUDIT.getLabel(),BaseContext.getCurrentId());
        if (approvalRecord_origin == null) {
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(approvalRecord.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.PLAN_AUDIT.getLabel());
            approvalRecord.setApproverId(BaseContext.getCurrentId());
            approvalRecord.setDecision(DecisionEnum.PASS.getMsg());
            approvalRecord.setComments(approvalRecordDTO.getComments());
            approvalRecord.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            approvalRecord.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            approvalRecord.setIsDelete(false);

            approvalService.save(approvalRecord);
        }else{
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.PASS.getMsg(),caseId, StepPropertyEnum.PLAN_AUDIT.getLabel(), approvalRecordDTO.getComments(), BaseContext.getCurrentId());
        }

        //修改状态
        stepService.updateUserByCaseId(StepPropertyEnum.PLAN_AUDIT.getLabel(), BaseContext.getCurrentId(), caseId);
        stepService.updateStatusByCaseId( StepEnum.COMPLETED.getMsg(),StepPropertyEnum.PLAN_AUDIT.getLabel(),caseId);
        stepService.updateStatusByCaseId( StepEnum.PROCESS.getMsg(), StepPropertyEnum.DISBURSE_START.getLabel(),caseId);

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


        return ResultUtil.success("success");
    }

    @PostMapping("/approval/reject1")
    @ApiOperation(value = "计划审批驳回")
    @PreAuthorize("@pms.hasRole('APPROVER')")
    public Result disbursementPlanApprovalReject(@RequestBody ApprovalRecordDTO approvalRecordDTO, @RequestParam Long chargeId) {
        if (ObjectUtils.isEmpty(approvalRecordDTO)||approvalRecordDTO.getCaseId()==null)
            throw new DescribeException(INPUT_ERROR);

        Long caseId = approvalRecordDTO.getCaseId();
        if(!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.PLAN_AUDIT.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);
        }

        //选择回款负责人,但驳回不应该开启回款开始环节
        stepService.updateUserId1ByCaseIdAndStepName(StepPropertyEnum.REPAY_START.getLabel(),chargeId,caseId);
//        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.REPAY_PARENT.getLabel(),caseId);
//        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.REPAY_START.getLabel(),caseId);

        Repayment repayment = new Repayment();
        repayment.setCaseId(caseId);
        repayment.setStartUserId(chargeId);
        repayment.setTotalAmount(disbursementService.getDisbursementByCaseId(caseId).getPlannedAmount());
        repaymentService.addRepayment(repayment);

        //填写驳回
        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(caseId,StepPropertyEnum.PLAN_AUDIT.getLabel(),BaseContext.getCurrentId());
        if (approvalRecord_origin == null) {
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(approvalRecord.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.PLAN_AUDIT.getLabel());
            approvalRecord.setApproverId(BaseContext.getCurrentId());
            approvalRecord.setDecision(DecisionEnum.REJECT.getMsg());
            approvalRecord.setComments(approvalRecordDTO.getComments());
            approvalRecord.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            approvalRecord.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            approvalRecord.setIsDelete(false);

            approvalService.save(approvalRecord);
        }else{
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.REJECT.getMsg(),caseId, StepPropertyEnum.PLAN_AUDIT.getLabel(), approvalRecordDTO.getComments(), BaseContext.getCurrentId());
        }

        //修改状态
        stepService.updateUserByCaseId(StepPropertyEnum.PLAN_AUDIT.getLabel(), BaseContext.getCurrentId(), caseId);
        stepService.updateStatusByCaseId( StepEnum.PROCESS.getMsg(), StepPropertyEnum.PLAN_REPORT.getLabel(),caseId);
        stepService.updateStatusByCaseId(StepEnum.UNSTART.getMsg(), StepPropertyEnum.PLAN_AUDIT.getLabel(),caseId);

        //TODO:微信推送预审通过消息和通知下一环节
//        SysMessage message = new SysMessage();
//        StepVO stepVO1 = stepService.findByStepNameAndCaseId(StepPropertyEnum.PLAN_REPORT.getLabel(), caseId);
//        message.setMobile(userService.findByIdAndIsDelete(stepVO1.getUserId1()).getMobile());
//        message.setUserRole(null);
//        message.setMessageTitle("");
//        message.setMessageContent("");
//        message.setStepName(StepPropertyEnum.PLAN_AUDIT.getLabel());
//        message.setRelatedId(caseId);
//        message.setRelatedType("");
 //       messageService.addMessage(message);
//        wxService.sendTemplateMessage(loanCase.getCustomer().getMobile(),new TemplateMessage());

        return ResultUtil.success("success");
    }

    //上传文件UploadController
    //显示文件列表
    @GetMapping("/{caseId}/files")
    @ApiOperation("显示文件列表")
    public Result findByCaseId(@PathVariable("caseId")Long caseId){

        return ResultUtil.success("success",documentService.findByCaseId(caseId));
    }

    @PutMapping("/commit")
    @ApiOperation(value = "出款启动")
    @PreAuthorize("@pms.hasAnyRoles('APPROVER','LEAD_SALES')")
    public Result commitDisbursement(@RequestParam Long caseId) {
        if(caseId == null ||!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.DISBURSE_START.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);
        }

        //修改状态
        stepService.updateUserByCaseId(StepPropertyEnum.DISBURSE_START.getLabel(), BaseContext.getCurrentId(), caseId);
        stepService.updateStatusByCaseId( StepEnum.COMPLETED.getMsg(),StepPropertyEnum.DISBURSE_START.getLabel(),caseId);
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.DISBURSE_AUDIT.getLabel(),  caseId);

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


        return ResultUtil.success("success");
    }


    @PostMapping("/approval/pass2")
    @ApiOperation(value = "出款审批")
    @PreAuthorize("@pms.hasRole('APPROVER')")
    public Result disbursementApproval(@RequestBody ApprovalRecordDTO approvalRecordDTO) {
        if(ObjectUtils.isEmpty(approvalRecordDTO)||approvalRecordDTO .getCaseId()== null)
            throw new DescribeException(INPUT_ERROR);

        Long caseId = approvalRecordDTO.getCaseId();
        if(!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.DISBURSE_AUDIT.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);
        }

        //填写审批意见 //驳回呢？
        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(caseId,StepPropertyEnum.DISBURSE_AUDIT.getLabel(),BaseContext.getCurrentId());
        if (approvalRecord_origin == null) {
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(approvalRecord.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.DISBURSE_AUDIT.getLabel());
            approvalRecord.setApproverId(BaseContext.getCurrentId());
            approvalRecord.setDecision(DecisionEnum.PASS.getMsg());
            approvalRecord.setComments(approvalRecordDTO.getComments());
            approvalRecord.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            approvalRecord.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            approvalRecord.setIsDelete(false);

            approvalService.save(approvalRecord);
        }else{
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.PASS.getMsg(),caseId, StepPropertyEnum.DISBURSE_AUDIT.getLabel(), approvalRecordDTO.getComments(), BaseContext.getCurrentId());
        }

        //修改出款单
        disbursementService.updateApprovalUserById(BaseContext.getCurrentId(),disbursementService.getDisbursementByCaseId(caseId).getId());

        //修改状态
        stepService.updateUserByCaseId(StepPropertyEnum.DISBURSE_AUDIT.getLabel(), BaseContext.getCurrentId(), caseId);
        stepService.updateStatusByCaseId(StepPropertyEnum.DISBURSE_AUDIT.getLabel(), StepEnum.COMPLETED.getMsg(),caseId);
        stepService.updateStatusByCaseId(StepPropertyEnum.FINANCE_DISBURSE.getLabel(), StepEnum.PROCESS.getMsg(), caseId);

        return ResultUtil.success("success");
    }

    @PostMapping("/approval/reject2")
    @ApiOperation(value = "出款审批驳回")
    @PreAuthorize("@pms.hasRole('APPROVER')")
    public Result disbursementApprovalReject(@RequestBody ApprovalRecordDTO approvalRecordDTO) {
        if (ObjectUtils.isEmpty(approvalRecordDTO)||approvalRecordDTO.getCaseId() == null)
            throw new DescribeException(INPUT_ERROR);

        Long caseId = approvalRecordDTO.getCaseId();
        if(!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.DISBURSE_AUDIT.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);
        }

//        //TODO:专门用于审批驳回，驳回后若上个步骤未重新提交，则无法审批
//        StepVO stepVO1 = stepService.findByStepNameAndCaseId(StepPropertyEnum.DISBURSE_START.getLabel(),caseId);
//        if (stepVO1.getStatus().equals(StepEnum.PROCESS.getMsg()))
//            throw new DescribeException(PRE_STEP_NOT_COMPLETE);

        //填写驳回意见
        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(caseId,StepPropertyEnum.DISBURSE_AUDIT.getLabel(),BaseContext.getCurrentId());
        if (approvalRecord_origin == null) {
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(approvalRecord.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.DISBURSE_AUDIT.getLabel());
            approvalRecord.setApproverId(BaseContext.getCurrentId());
            approvalRecord.setDecision(DecisionEnum.REJECT.getMsg());
            approvalRecord.setComments(approvalRecordDTO.getComments());
            approvalRecord.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            approvalRecord.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            approvalRecord.setIsDelete(false);

            approvalService.save(approvalRecord);
        }else{
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.REJECT.getMsg(),caseId, StepPropertyEnum.DISBURSE_AUDIT.getLabel(), approvalRecordDTO.getComments(), BaseContext.getCurrentId());
        }

        //修改出款单
        disbursementService.updateApprovalUserById(BaseContext.getCurrentId(),disbursementService.getDisbursementByCaseId(caseId).getId());

        //修改状态
        stepService.updateUserByCaseId(StepPropertyEnum.DISBURSE_AUDIT.getLabel(), BaseContext.getCurrentId(), caseId);
        stepService.updateStatusByCaseId( StepEnum.PROCESS.getMsg(),StepPropertyEnum.DISBURSE_START.getLabel(),caseId);//重新出款
        stepService.updateStatusByCaseId( StepEnum.UNSTART.getMsg(),StepPropertyEnum.DISBURSE_AUDIT.getLabel(),caseId);

        return ResultUtil.success("success");
    }

    @GetMapping("/financeDetails")
    @ApiOperation("显示财务出款详情")//与loanContraller的方法一致，但为了规范
    @PreAuthorize("@pms.hasAnyRoles('SYSTEM_ADMIN','APPROVER','LEAD_SALES', 'ASSIST_SALES', 'FINANCE', 'BACK_OFFICE')")
    public Result findLoanCaseDetails3(@RequestParam Long caseId){
        if(caseId == null || !loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        DisbursementDetailVO disbursementDetailVO = disbursementService.getLoanCaseAndCustomerByCaseId(caseId);
        //填充
        List<DisbursementRecordVO> records = disbursementRecordService.findRecordById(disbursementService.getDisbursementByCaseId(caseId).getId());
        disbursementDetailVO.setDisbursementRecords(records);
        disbursementDetailVO.setTotalAmount(disbursementService.getDisbursementByCaseId(caseId).getPlannedAmount());

        return ResultUtil.success("success",loanService.findLoanCaseDetailsById(caseId));
    }

    @PostMapping("/amount")
    @ApiOperation(value = "财务出款")
    @PreAuthorize("@pms.hasRole('FINANCE')")
    public Result financeDisbursement(@RequestBody DisbursementRecordDTO disbursementRecordDTO,@RequestParam Long caseId) {
        if (ObjectUtils.isEmpty(disbursementRecordDTO)||disbursementRecordDTO.getDisbursementId() == null)
            throw new DescribeException(INPUT_ERROR);

        if(!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.FINANCE_DISBURSE.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);
//        }

        //修改出款单
        //disbursementService.updateOperationUserById(BaseContext.getCurrentId(),disbursementService.getDisbursementByCaseId(caseId).getId());

        //添加出款记录
        disbursementRecordService.addDisbursementRecord(disbursementRecordDTO);

        //修改状态
        //stepService.updateUserByCaseId(StepPropertyEnum.FINANCE_DISBURSE.getLabel(), BaseContext.getCurrentId(), caseId);TODO:分多次出款，不一定是同一个人
        stepService.updateStatusByCaseId( StepEnum.COMPLETED.getMsg(),StepPropertyEnum.FINANCE_DISBURSE.getLabel(),caseId);
        stepService.updateStatusByCaseId( StepEnum.PROCESS.getMsg(),StepPropertyEnum.DISBURSE_CONFIRM.getLabel(), caseId);

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


        return ResultUtil.success("success");
    }

    @GetMapping("/confirmDetails")
    @ApiOperation("显示业务确认详情")//与loanContraller的方法一致，但为了规范
    @PreAuthorize("@pms.hasAnyRoles('SYSTEM_ADMIN','APPROVER','LEAD_SALES', 'ASSIST_SALES', 'FINANCE', 'BACK_OFFICE')")
    public Result findLoanCaseDetails4(@RequestParam Long caseId){
        if(caseId == null ||!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        DisbursementDetailVO disbursementDetailVO = disbursementService.getLoanCaseAndCustomerByCaseId(caseId);
        //填充
        List<DisbursementRecordVO> records = disbursementRecordService.findRecordById(disbursementService.getDisbursementByCaseId(caseId).getId());
        disbursementDetailVO.setDisbursementRecords(records);

        Disbursement disbursement = disbursementService.getDisbursementByCaseId(caseId);
        disbursementDetailVO.setTotalAmount(disbursement.getPlannedAmount());
        disbursementDetailVO.setConfirmComment(disbursement.getComments());

        return ResultUtil.success("success",loanService.findLoanCaseDetailsById(caseId));
    }

    @PostMapping("/confirm")
    @ApiOperation(value = "业务确认")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES', 'ASSIST_SALES')")
    public Result confirmDisbursement(@RequestParam("caseId") Long caseId,@RequestParam("comments") String comments) {
        if(caseId == null ||!loanService.existsByIdAndIsDelete(caseId))
            throw new DescribeException(ExceptionEnum.PROJECT_NOT_EXIST);

        StepVO stepVO = stepService.findByStepNameAndCaseId(StepPropertyEnum.DISBURSE_CONFIRM.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);
        }

        //设置说明
        disbursementService.updateCommentsById(comments,disbursementService.getDisbursementByCaseId(caseId).getId());

        //修改状态
        stepService.updateUserByCaseId(StepPropertyEnum.DISBURSE_CONFIRM.getLabel(), BaseContext.getCurrentId(), caseId);
        stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(),StepPropertyEnum.DISBURSE_CONFIRM.getLabel(), caseId);

        //填写合同编号
        List<ContractVO> contractByCaseId = contractService.findContractByCaseId(caseId);
        String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        contractByCaseId.forEach(contractVO -> {
            String prefix= contractVO.getBusinessAttr().equals(BusinessAttrEnum.ESTATE_MORTGAGE.getMsg()) ? "宝押字": "宝质字";

            ContractSeq contractSeq = contractSeqService.findSeqBySeqDataAndBusinessAttr(today,prefix);
            if (ObjectUtils.isEmpty(contractSeq))
                contractSeq =contractSeqService.addSeq(today,prefix);

            //合同编号
            String contractNo = String.format("%s%s-%s-%03d",
                    prefix,
                    today.substring(0, 4),        // 年份
                    today.substring(4),           // 月日
                    contractSeq.getNextSeq());

            //更新号码
            contractSeqService.updateSeqById(contractSeq.getId(),contractSeq.getNextSeq()+1);

            //更新合同编号
            contractService.updateContractNoById(contractVO.getId(),contractNo);
        });

        return ResultUtil.success("success");
    }


}
