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.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.ExemptionApprovalRisk;
import com.sunxung.factoring.entity.financing.payment.PaymentApply;
import com.sunxung.factoring.entity.financing.payment.PaymentInfo;
import com.sunxung.factoring.mapper.financing.payment.ExemptionApprovalRiskMapper;
import com.sunxung.factoring.service.financing.apply.ICFinancingBasicInfoService;
import com.sunxung.factoring.service.financing.payment.IExemptionApprovalRiskService;
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_riskService")
public class ExemptionApprovalRiskServiceImpl extends ServiceImpl<ExemptionApprovalRiskMapper, ExemptionApprovalRisk>
        implements IExemptionApprovalRiskService {

    @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(ExemptionApprovalRisk exemptionApprovalRisk) {

        CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(exemptionApprovalRisk.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, "未查询到付款申请信息！");
        }
        exemptionApprovalRisk.setPaymentApplyId(paymentApply.getId());
        save(exemptionApprovalRisk);
        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.PAYMENT_APPROVAL_CANDIDATE,
                assigneeService.getCandidateByBusiness(financingBasicInfo.getId(), key, ConstantUtil.ASSIGNEE_LEGAL_SPECIALIST));
        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.LEGAL_SPECIALIST + "角色内无任何用户！");
        }
        //流程处理
        //流程图里叫退回，所以此处判断一下
        String conclusion = ConstantConversionUtil.processApprovalResult.get(exemptionApprovalRisk.getApprovalConclusion()).equals("驳回") ?
                "退回" : ConstantConversionUtil.processApprovalResult.get(exemptionApprovalRisk.getApprovalConclusion());
        Boolean result = flowableService.completeMyTask(exemptionApprovalRisk.getTaskId(), financingBasicInfo, procVariables,
                conclusion, exemptionApprovalRisk.getId(), msgVariables, key, legalSpecialists);
        if (result == null || !result) {
            throw new ValidatorException(CodeUtil.FAIL, "豁免风控负责人审批提交出错啦！");
        }
    }

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