package com.sunxung.factoring.service.financing.payment.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.enums.FinancingCurrentStageEnum;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.ConstantConversionUtil;
import com.sunxung.factoring.component.util.ConstantUtil;
import com.sunxung.factoring.entity.financing.apply.CFinancingBasicInfo;
import com.sunxung.factoring.entity.financing.payment.ExemptionApprovalBusiness;
import com.sunxung.factoring.entity.financing.payment.PaymentApply;
import com.sunxung.factoring.entity.financing.payment.PaymentInfo;
import com.sunxung.factoring.mapper.financing.payment.ExemptionApprovalBusinessMapper;
import com.sunxung.factoring.service.financing.apply.ICFinancingBasicInfoService;
import com.sunxung.factoring.service.financing.payment.IExemptionApprovalBusinessService;
import com.sunxung.factoring.service.financing.payment.IPaymentApplyService;
import com.sunxung.factoring.service.financing.payment.IPaymentInfoService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 豁免审批表（业务） 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-04-19
 */
@Service("exemption_approval_businessService")
public class ExemptionApprovalBusinessServiceImpl extends ServiceImpl<ExemptionApprovalBusinessMapper, ExemptionApprovalBusiness>
        implements IExemptionApprovalBusinessService {

    @Autowired
    private FlowableService flowableService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private IPaymentApplyService applyService;
    @Autowired
    private IPaymentInfoService paymentInfoService;
    @Autowired
    private ICFinancingBasicInfoService financingBasicInfoService;
    @Autowired
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(ExemptionApprovalBusiness exemptionApprovalBusiness) {

        CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(exemptionApprovalBusiness.getFinancingBasicInfoId());
        if (financingBasicInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "未查询到融资申请信息！");
        }
        PaymentInfo paymentInfo = paymentInfoService.getOne(new QueryWrapper<PaymentInfo>().eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        if (paymentInfo == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应付款信息");
        }
        PaymentApply paymentApply = applyService.getOne(new QueryWrapper<PaymentApply>().eq("payment_info_id", paymentInfo.getId())
                .eq("visible", true).orderByDesc("id").last("LIMIT 1"));
        if (paymentApply == null) {
            throw new ValidatorException(CodeUtil.FAIL, "未查询到付款申请信息！");
        }
        exemptionApprovalBusiness.setPaymentApplyId(paymentApply.getId());
        save(exemptionApprovalBusiness);
        String key = ConstantUtil.FINANCING_APPLY;
        //发送的消息
        Map<String, Object> msgVariables = new HashMap<>(2);
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, financingBasicInfo.getBusinessNumber());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT, "业务编号为“" + financingBasicInfo.getBusinessNumber() + "”的项目已inOut“"
                + ConstantConversionUtil.flowBusinessKeyNames.get(key) + "—formBusiness”阶段，");
        //风控审核人
        Map<String, Object> procVariables = new HashMap<>(1);
        procVariables.put(ConstantUtil.EXEMPTION_APPROVAL_RISK_CANDIDATE,
                assigneeService.getCandidateByBusiness(financingBasicInfo.getId(), key, ConstantUtil.ASSIGNEE_RISK_OWNER));
        List<Long> riskOwnerList = userService.findUserIdByRole(ConstantUtil.RISK_CONTROL_OWNER);
        if (riskOwnerList == null || riskOwnerList.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.RISK_CONTROL_OWNER + "角色内无任何用户！");
        }
        //流程处理
        //流程图里叫退回，所以此处判断一下
        String conclusion = ConstantConversionUtil.processApprovalResult.get(exemptionApprovalBusiness.getApprovalConclusion()).equals("驳回") ?
                "退回" : ConstantConversionUtil.processApprovalResult.get(exemptionApprovalBusiness.getApprovalConclusion());
        Boolean result = flowableService.completeMyTask(exemptionApprovalBusiness.getTaskId(), financingBasicInfo, procVariables,
                conclusion, exemptionApprovalBusiness.getId(), msgVariables, key, riskOwnerList);
        if (result == null || !result) {
            throw new ValidatorException(CodeUtil.FAIL, "豁免业务负责人审批提交出错啦！");
        }
        if (ConstantConversionUtil.APPROVAL_RESULT_BACK.equals(exemptionApprovalBusiness.getApprovalConclusion())) {
            //修改融资申请当前阶段
            financingBasicInfo.setCurrentStage(FinancingCurrentStageEnum.PAYMENT_APPLY.getCode());
            financingBasicInfoService.updateById(financingBasicInfo);
        }
    }

    @Override
    public ExemptionApprovalBusiness getView(Long id) {
        return getById(id);
    }
}
