package com.loan.system.controller.wechat;

import com.loan.system.domain.dto.ApprovalDTO;
import com.loan.system.domain.dto.PreApprovalDTO;
import com.loan.system.domain.entity.*;
import com.loan.system.domain.enums.DecisionEnum;
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.*;
import com.loan.system.properties.JwtProperties;
import com.loan.system.service.*;
import com.loan.system.service.Impl.UserServiceImpl;
import com.loan.system.utils.JwtUtil;
import com.loan.system.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

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

@RestController
@RequestMapping("/wechat/")
@Api(tags = "业务审核接口")
public class ApprovalController {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private LoanService loanCaseService;
    @Autowired
    private ApprovalService approvalService;
    @Autowired
    private DocumentService documentService;
    @Autowired
    private StepService stepService;
    @Autowired
    private JwtProperties jwtProperties;
//    @Autowired
//    private WxService wxService;

    @GetMapping("/loan_case/{id}")
    @ApiOperation("获取业务客户信息")
    //TODO：给前端展示的VO补充完整
    public Result info(@PathVariable Long id) {
        log.info("获取业务客户信息: {}", id);
        LoanCaseVO loanCase = loanCaseService.findLoanCaseByIdAndIsDelete(id,false);
        if(loanCase == null){
            log.info("业务客户信息: 空");
        }
        log.info("业务客户信息: {}", loanCase.getCustomer().getId());
        CustomerVO customer = customerService.findByCustomerIdAndIsDelete(loanCase.getCustomer().getId(), false);
        StepVO step = stepService.findByStepNameAndCaseId(StepPropertyEnum.PRE_TRIAL.getLabel(),id);
        //List<Document> documentList = documentService.findDocumentByCaseIdAndIsDelete(customer.getId());
        User user1= userService.findByIdAndIsDelete(step.getUserId1());
        User user2= userService.findByIdAndIsDelete(step.getUserId2());
        LoanCasePreApprovalVo loanCasePreApprovalVo = new LoanCasePreApprovalVo();
        if(user1!=null){
            loanCasePreApprovalVo.setLead_Sales(user1.getRealName());
        }
        if(user2!=null){
            loanCasePreApprovalVo.setAssist_Sales(user2.getRealName());
        }
        //TODO 补充业务信息、客户信息


        return ResultUtil.success("success",loanCasePreApprovalVo);
    }
    @PostMapping("/preapproval-assist/{caseId}/pass")
    @PreAuthorize("@pms.hasRole('ASSIST_SALES')")
    @ApiOperation("副业务员审核")
    public Result pre_approval_save_primary(PreApprovalDTO preApprovalDTO, HttpServletRequest request) {
        //请求头根据token获取用户信息
        //String token = request.getHeader("Authorization").substring(7); // 去掉"Bearer "前缀
        String token = request.getHeader("Authorization");
        Long userId=Long.parseLong(JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token).get("userId").toString());
        log.info("用户id: {}", userId);
        User user = userService.findByIdAndIsDelete(userId);
        log.info("用户: {}", user.getMobile());
        LoanCaseVO loanCase = loanCaseService.findLoanCaseByIdAndIsDelete(preApprovalDTO.getCaseId(),false);
        if(loanCase == null){
            return ResultUtil.error(PROJECT_NOT_EXIST.getCode(), PROJECT_NOT_EXIST.getMsg());
        }
        StepVO step = stepService.findByStepNameAndCaseId(StepPropertyEnum.PRE_TRIAL.getLabel(), preApprovalDTO.getCaseId());
        if(step.getUserId2()!=null&&userId!=step.getUserId2()){
            return ResultUtil.error(STEP_USER_NOT_EXPECTED.getCode(), "环节处理人不是预期用户");
        }
        if(Objects.equals(step.getStatus(), StepEnum.COMPLETED.getMsg())){
            return ResultUtil.error(STEP_HAS_COMPLETEED.getCode(), "环节已完成，无法重复审批");
        }
        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(preApprovalDTO.getCaseId(),StepPropertyEnum.PRE_TRIAL.getLabel(),userId);
        if (approvalRecord_origin == null) {
            // 创建审批记录
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(preApprovalDTO.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.PRE_TRIAL.getLabel());
            approvalRecord.setApproverId(user.getId());
            approvalRecord.setDecision(DecisionEnum.PASS.getMsg());
            approvalRecord.setComments(preApprovalDTO.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);
            stepService.updateUserId2ByCaseIdAndStepName(StepPropertyEnum.PRE_TRIAL.getLabel(), user.getId(), preApprovalDTO.getCaseId());
        }else {
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.PASS.getMsg(), preApprovalDTO.getCaseId(), StepPropertyEnum.PRE_TRIAL.getLabel(), preApprovalDTO.getComments(), userId);
        }
        stepService.updateUserId2ByCaseIdAndStepName(StepPropertyEnum.PRE_TRIAL.getLabel(),userId,preApprovalDTO.getCaseId());
        //更新步骤状态
        stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(), StepPropertyEnum.PRE_TRIAL_PARENT.getLabel(), preApprovalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(), StepPropertyEnum.PRE_TRIAL.getLabel(), preApprovalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(), StepPropertyEnum.APPROVAL_PARENT.getLabel(), preApprovalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(), StepPropertyEnum.APPROVAL.getLabel(), preApprovalDTO.getCaseId());
        loanCaseService.updateUpdatetimeByIdAndIsDeleted(preApprovalDTO.getCaseId(),false);
        //TODO:微信推送预审通过消息和通知下一环节
//        wxService.sendTemplateMessage(loanCase.getCustomer().getMobile(),new TemplateMessage());
        return ResultUtil.success("success","预审通过");
    }

//    @PostMapping("/approval-lead/{caseId}/pass")
//    @PreAuthorize("@pms.hasRole('LEAD_SALES')")
//    @ApiOperation("主业务员审核")
//    public Result pre_approval_save_assist(PreApprovalDTO preApprovalDTO, HttpServletRequest request) {
//        //请求头根据token获取用户信息
//        //String token = request.getHeader("Authorization").substring(7); // 去掉"Bearer "前缀
//        String token = request.getHeader("Authorization");
//        Long userId=Long.parseLong(JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token).get("userId").toString());
//        log.info("用户id: {}", userId);
//        User user = userService.findByIdAndIsDelete(userId);
//        log.info("用户: {}", user.getMobile());
//        LoanCase loanCase = loanCaseService.findByIdAndIsDelete(preApprovalDTO.getCaseId());
//        if(loanCase == null){
//            return ResultUtil.error(PROJECT_NOT_EXIST.getCode(), PROJECT_NOT_EXIST.getMsg());
//        }
//        // TODO: 使用userId进行后续操作
//        // 创建新的审批记录
//        ApprovalRecord approvalRecord = new ApprovalRecord();
//        approvalRecord.setCaseId(preApprovalDTO.getCaseId());
//        approvalRecord.setStepName(StepPropertyEnum.PRE_TRIAL.getLabel());
//        approvalRecord.setApproverId(userId);
//        approvalRecord.setDecision(DecisionEnum.PASS.getMsg());
//        approvalRecord.setComments(preApprovalDTO.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);
//        stepService.updateUserId1ByCaseIdAndStepName(StepPropertyEnum.PRE_TRIAL.getLabel(),userId,preApprovalDTO.getCaseId());
//        Step step = stepService.findByStepNameAndCaseId(StepPropertyEnum.PRE_TRIAL.getLabel(),preApprovalDTO.getCaseId());
//        if(step.getUserId1()!=null && step.getUserId2()!=null){
//            stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(), StepPropertyEnum.PRE_TRIAL_PARENT.getLabel(),preApprovalDTO.getCaseId());
//            stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(), StepPropertyEnum.PRE_TRIAL.getLabel(),preApprovalDTO.getCaseId());
//            stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(), StepPropertyEnum.APPROVAL_PARENT.getLabel(),preApprovalDTO.getCaseId());
//            stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(), StepPropertyEnum.APPROVAL.getLabel(),preApprovalDTO.getCaseId());
//            //TODO: 添加业务逻辑 ，通知下一个环节审批人
//        }
//        log.info("业务id: {}", preApprovalDTO.getCaseId());
//        loanCaseService.updateUpdatetimeByIdAndIsDeleted(preApprovalDTO.getCaseId(),false);
//        return ResultUtil.success("success","审批通过");
//    }

    @PostMapping("/preapproval-records/{caseId}/reject")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES','ASSIST_SALES')")
    @ApiOperation("业务预审拒绝")
    public Result pre_approval_reject(PreApprovalDTO preApprovalDTO, HttpServletRequest request) {
        //请求头根据token获取用户信息
        //String token = request.getHeader("Authorization").substring(7); // 去掉"Bearer "前缀
        String token = request.getHeader("Authorization");
        Long userId=Long.parseLong(JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token).get("userId").toString());
        log.info("用户id: {}", userId);
        User user = userService.findByIdAndIsDelete(userId);
        log.info("用户: {}", user.getMobile());
        LoanCaseVO loanCase = loanCaseService.findLoanCaseByIdAndIsDelete(preApprovalDTO.getCaseId(),false);
        if(loanCase == null){
            return ResultUtil.error(PROJECT_NOT_EXIST.getCode(), PROJECT_NOT_EXIST.getMsg());
        }
        StepVO step = stepService.findByStepNameAndCaseId(StepPropertyEnum.PRE_TRIAL.getLabel(), preApprovalDTO.getCaseId());
        //判断过去处理人与目前处理人是否一致
        if(step.getUserId2()!=null&&userId!=step.getUserId2()){
            return ResultUtil.error(STEP_USER_NOT_EXPECTED.getCode(), "环节处理人不是预期用户");
        }
        if(Objects.equals(step.getStatus(), StepEnum.COMPLETED.getMsg())){
            return ResultUtil.error(STEP_HAS_COMPLETEED.getCode(), "环节已完成，无法重复审批");
        }

        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(preApprovalDTO.getCaseId(),StepPropertyEnum.PRE_TRIAL.getLabel(),userId);
        if(approvalRecord_origin == null) {
            log.info("没找到对应以前审批记录");
            // 创建审批记录
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(preApprovalDTO.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.PRE_TRIAL.getLabel());
            approvalRecord.setApproverId(userId);
            approvalRecord.setDecision(DecisionEnum.REJECT.getMsg());
            approvalRecord.setComments(preApprovalDTO.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{
            log.info("找到对应以前审批记录");
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.REJECT.getMsg(),preApprovalDTO.getCaseId(),StepPropertyEnum.PRE_TRIAL.getLabel(),preApprovalDTO.getComments(),userId);
        }
        stepService.updateUserId2ByCaseIdAndStepName(StepPropertyEnum.PRE_TRIAL.getLabel(),userId,preApprovalDTO.getCaseId());
        loanCaseService.updateUpdatetimeByIdAndIsDeleted(preApprovalDTO.getCaseId(),false);

        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(), StepPropertyEnum.BUSINESS_ACCEPT_PARENT.getLabel(), preApprovalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(), StepPropertyEnum.BUSINESS_ACCEPT.getLabel(), preApprovalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.UNSTART.getMsg(), StepPropertyEnum.PRE_TRIAL_PARENT.getLabel(), preApprovalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.UNSTART.getMsg(), StepPropertyEnum.PRE_TRIAL.getLabel(), preApprovalDTO.getCaseId());
        loanCaseService.updateUpdatetimeByIdAndIsDeleted(preApprovalDTO.getCaseId(),false);
        //TODO:微信推送预审拒绝消息和通知下一环节
//        wxService.sendTemplateMessage(loanCase.getCustomer().getMobile(),new TemplateMessage());
        return ResultUtil.success("success","预审拒绝");
    }

    @PostMapping("/approval/{caseId}/pass")
    @PreAuthorize("@pms.hasRole('APPROVER')")
    @ApiOperation("业务审批通过")
    public Result approval_pass(ApprovalDTO approvalDTO, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long userId=Long.parseLong(JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token).get("userId").toString());
        log.info("用户id: {}", userId);
        //审批业务逻辑
        LoanCaseVO loanCase = loanCaseService.findLoanCaseByIdAndIsDelete(approvalDTO.getCaseId(), false);
        if(loanCase == null){
            return ResultUtil.error(PROJECT_NOT_EXIST.getCode(), PROJECT_NOT_EXIST.getMsg());
        }
        StepVO step = stepService.findByStepNameAndCaseId(StepPropertyEnum.APPROVAL.getLabel(), approvalDTO.getCaseId());
        //判断过去处理人与目前处理人是否一致
        if(step.getUserId1()!=null&&step.getUserId2()!=null&& !userId.equals(step.getUserId2()) && !userId.equals(step.getUserId1())){
            return ResultUtil.error(STEP_USER_NOT_EXPECTED.getCode(), "环节处理人不是预期用户");
        }
        if(Objects.equals(step.getStatus(), StepEnum.COMPLETED.getMsg())){
            return ResultUtil.error(STEP_HAS_COMPLETEED.getCode(), "环节已完成，无法重复审批");
        }

        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(approvalDTO.getCaseId(),StepPropertyEnum.APPROVAL.getLabel(),userId);
        if(approvalRecord_origin == null) {
            log.info("没找到对应以前审批记录");
            // 创建审批记录
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(approvalDTO.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.APPROVAL.getLabel());
            approvalRecord.setApproverId(userId);
            approvalRecord.setDecision(DecisionEnum.PASS.getMsg());
            approvalRecord.setComments(approvalDTO.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{
            log.info("找到对应以前审批记录");
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.PASS.getMsg(),approvalDTO.getCaseId(),StepPropertyEnum.APPROVAL.getLabel(),approvalDTO.getComments(),userId);
        }
        if(step.getUserId1()== null){
            stepService.updateUserId1ByCaseIdAndStepName(StepPropertyEnum.APPROVAL.getLabel(),userId,approvalDTO.getCaseId());
        }else if(step.getUserId2()== null&&!userId.equals(step.getUserId1())){
            stepService.updateUserId2ByCaseIdAndStepName(StepPropertyEnum.APPROVAL.getLabel(),userId,approvalDTO.getCaseId());
        }
        if(step.getUserId1()!=null&&step.getUserId2()!=null){
            ApprovalRecordVO approvalRecord_user1 = approvalService.findByCaseIdAndIsDeleteAndStepName(approvalDTO.getCaseId(),StepPropertyEnum.APPROVAL.getLabel(),step.getUserId1());
            ApprovalRecordVO approvalRecord_user2 = approvalService.findByCaseIdAndIsDeleteAndStepName(approvalDTO.getCaseId(),StepPropertyEnum.APPROVAL.getLabel(),step.getUserId2());
            if(Objects.equals(approvalRecord_user1.getDecision(), DecisionEnum.PASS.getMsg()) && Objects.equals(approvalRecord_user2.getDecision(), DecisionEnum.PASS.getMsg())){
                stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(),StepPropertyEnum.APPROVAL_PARENT.getLabel(),approvalDTO.getCaseId());
                stepService.updateStatusByCaseId(StepEnum.COMPLETED.getMsg(),StepPropertyEnum.APPROVAL.getLabel(),approvalDTO.getCaseId());
                stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.CONTRACT_SIGN_PARENT.getLabel(),approvalDTO.getCaseId());
                stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.CONTRACT_SIGN.getLabel(),approvalDTO.getCaseId());
                //TODO微信推送审批通过消息和通知下一环节
            }
        }else{
            //TODO微信推送另一个审批人审批
        }

        return ResultUtil.success("success","审批通过");

    }

    @PostMapping("/approval/{caseId}/reject")
    @PreAuthorize("@pms.hasRole('APPROVER')")
    @ApiOperation("业务审批拒绝")
    public Result approval_reject(ApprovalDTO approvalDTO, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long userId=Long.parseLong(JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token).get("userId").toString());
        log.info("用户id: {}", userId);
        //审批业务逻辑
        LoanCaseVO loanCase = loanCaseService.findLoanCaseByIdAndIsDelete(approvalDTO.getCaseId(),false);
        if(loanCase == null){
            return ResultUtil.error(PROJECT_NOT_EXIST.getCode(), PROJECT_NOT_EXIST.getMsg());
        }
        StepVO step = stepService.findByStepNameAndCaseId(StepPropertyEnum.APPROVAL.getLabel(), approvalDTO.getCaseId());
        //判断过去处理人与目前处理人是否一致
        if(step.getUserId1()!=null&&step.getUserId2()!=null&&userId!=step.getUserId2()&&userId!=step.getUserId1()){
            return ResultUtil.error(STEP_USER_NOT_EXPECTED.getCode(), "环节处理人不是预期用户");
        }
        if(Objects.equals(step.getStatus(), StepEnum.COMPLETED.getMsg())){
            return ResultUtil.error(STEP_HAS_COMPLETEED.getCode(), "环节已完成，无法重复审批");
        }
        //审批记录处理
        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(approvalDTO.getCaseId(),StepPropertyEnum.APPROVAL.getLabel(),userId);
        if(approvalRecord_origin == null) {
            log.info("没找到对应以前审批记录");
            // 创建审批记录
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(approvalDTO.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.APPROVAL.getLabel());
            approvalRecord.setApproverId(userId);
            approvalRecord.setDecision(DecisionEnum.REJECT.getMsg());
            approvalRecord.setComments(approvalDTO.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{
            log.info("找到对应以前审批记录");
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.REJECT.getMsg(),approvalDTO.getCaseId(),StepPropertyEnum.APPROVAL.getLabel(),approvalDTO.getComments(),userId);
        }
        if(step.getUserId1()== null){
            stepService.updateUserId1ByCaseIdAndStepName(StepPropertyEnum.APPROVAL.getLabel(),userId,approvalDTO.getCaseId());
        }else if(step.getUserId2()== null&&!userId.equals(step.getUserId1())){
            stepService.updateUserId2ByCaseIdAndStepName(StepPropertyEnum.APPROVAL.getLabel(),userId,approvalDTO.getCaseId());
        }
        //更新环节状态
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.BUSINESS_ACCEPT_PARENT.getLabel(),approvalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.PROCESS.getMsg(),StepPropertyEnum.BUSINESS_ACCEPT.getLabel(),approvalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.UNSTART.getMsg(),StepPropertyEnum.PRE_TRIAL_PARENT.getLabel(),approvalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.UNSTART.getMsg(),StepPropertyEnum.PRE_TRIAL.getLabel(),approvalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.UNSTART.getMsg(),StepPropertyEnum.APPROVAL_PARENT.getLabel(),approvalDTO.getCaseId());
        stepService.updateStatusByCaseId(StepEnum.UNSTART.getMsg(),StepPropertyEnum.APPROVAL.getLabel(),approvalDTO.getCaseId());
        //TODO微信推送审批驳回消息和通知重新受理（到业务受理）

        return ResultUtil.success("success","审批驳回");
    }
    @PostMapping("/approval/{caseId}/terminate")
    @PreAuthorize("@pms.hasRole('APPROVER')")
    @ApiOperation("业务审批终结")
    public Result approval_end(ApprovalDTO approvalDTO, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long userId=Long.parseLong(JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token).get("userId").toString());
        log.info("用户id: {}", userId);
        //审批业务逻辑
        LoanCaseVO loanCase = loanCaseService.findLoanCaseByIdAndIsDelete(approvalDTO.getCaseId(),false);
        if(loanCase == null){
            return ResultUtil.error(PROJECT_NOT_EXIST.getCode(), PROJECT_NOT_EXIST.getMsg());
        }
        StepVO step = stepService.findByStepNameAndCaseId(StepPropertyEnum.APPROVAL.getLabel(), approvalDTO.getCaseId());
        //判断过去处理人与目前处理人是否一致
        if(step.getUserId1()!=null&&step.getUserId2()!=null&& !userId.equals(step.getUserId2()) && !userId.equals(step.getUserId1())){
            return ResultUtil.error(STEP_USER_NOT_EXPECTED.getCode(), "环节处理人不是预期用户");
        }
        if(Objects.equals(step.getStatus(), StepEnum.COMPLETED.getMsg())){
            return ResultUtil.error(STEP_HAS_COMPLETEED.getCode(), "环节已完成，无法重复审批");
        }
        //审批记录处理
        ApprovalRecordVO approvalRecord_origin = approvalService.findByCaseIdAndIsDeleteAndStepName(approvalDTO.getCaseId(),StepPropertyEnum.APPROVAL.getLabel(),userId);
        if(approvalRecord_origin == null) {
            log.info("没找到对应以前审批记录");
            // 创建审批记录
            ApprovalRecord approvalRecord = new ApprovalRecord();
            approvalRecord.setCaseId(approvalDTO.getCaseId());
            approvalRecord.setStepName(StepPropertyEnum.APPROVAL.getLabel());
            approvalRecord.setApproverId(userId);
            approvalRecord.setDecision(DecisionEnum.TERMINATE.getMsg());
            approvalRecord.setComments(approvalDTO.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{
            log.info("找到对应以前审批记录");
            approvalService.updateDecisionByCaseIdAndStepNameAndIsDelete(DecisionEnum.TERMINATE.getMsg(),approvalDTO.getCaseId(),StepPropertyEnum.APPROVAL.getLabel(),approvalDTO.getComments(),userId);
        }
        if(step.getUserId1()== null){
            stepService.updateUserId1ByCaseIdAndStepName(StepPropertyEnum.APPROVAL.getLabel(),userId,approvalDTO.getCaseId());
        }else if(step.getUserId2()== null&&!userId.equals(step.getUserId1())){
            stepService.updateUserId2ByCaseIdAndStepName(StepPropertyEnum.APPROVAL.getLabel(),userId,approvalDTO.getCaseId());
        }
        //更新项目和环节状态 作逻辑删除
        loanCaseService.logic_delete(approvalDTO.getCaseId());
        List<StepVO> steps = stepService.getStepByCaseId(approvalDTO.getCaseId());
        for (StepVO step_each : steps){
            stepService.logic_delete(step_each.getId());
        }
        //TODO微信推送审批驳回消息和通知重新受理（到业务受理）

        return ResultUtil.success("success","业务终结");
    }
}

