package com.loan.system.controller.wechat;

import com.loan.system.context.BaseContext;
import com.loan.system.domain.dto.DisbursementDTO;
import com.loan.system.domain.dto.DisbursementRecordDTO;
import com.loan.system.domain.dto.DocumentDTO;
import com.loan.system.domain.entity.ContractSeq;
import com.loan.system.domain.entity.Disbursement;
import com.loan.system.domain.enums.BusinessAttrEnum;
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.ContractVO;
import com.loan.system.domain.vo.DisbursementVO;
import com.loan.system.domain.vo.StepVO;
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.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;

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

    @GetMapping("/{caseId}/details")
    @ApiOperation("显示业务详情")//与loanContraller的方法一致，但为了规范
    public Result findLoanCaseDetails(@PathVariable("caseId")Long caseId){
        return ResultUtil.success("success",loanService.findLoanCaseDetailsById(caseId));
    }

    @GetMapping("/{caseId}/details2")
    @ApiOperation("显示出款计划详情")
    public Result findDisbursementDetails(@PathVariable("caseId")Long caseId){
        return ResultUtil.success("success",disbursementService.findDisbursementDetailsById(caseId));
    }

    @PostMapping
    @ApiOperation(value = "上报出款计划")
    public Result addDisbursement(@RequestBody DisbursementDTO disbursementDTO) {

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

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

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

    //上传文件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.hasRole(RoleEnum.LEAD_SALES.getMsg())")
    public Result commitDisbursement(@RequestBody DocumentDTO documentDTO) {

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

        return ResultUtil.success("success");
    }

    @PostMapping("/{id}/amount")
    @ApiOperation(value = "财务出款")
    public Result disbursement(@RequestBody DisbursementRecordDTO disbursementRecordDTO) {
        //添加出款记录

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


        return ResultUtil.success("success");
    }

    @PostMapping("/confirm")
    @ApiOperation(value = "业务确认")
    public Result confirmDisbursement(@RequestBody DisbursementDTO disbursementDTO) {
        //修改状态
        stepService.updateUserByCaseId(StepPropertyEnum.DISBURSE_CONFIRM.getLabel(), BaseContext.getCurrentId(), disbursementDTO.getCaseId());
        stepService.updateStatusByCaseId(StepPropertyEnum.DISBURSE_CONFIRM.getLabel(), StepEnum.COMPLETED.getMsg(),disbursementDTO.getCaseId());

        //填写合同编号
        List<ContractVO> contractByCaseId = contractService.findContractByCaseId(disbursementDTO.getCaseId());
        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");
    }






}
