package com.sunxung.factoring.service.salescontractmanagement.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.ConstantConversionUtil;
import com.sunxung.factoring.component.util.ConstantUtil;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContract;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesSignConfirmation;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesSignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.salescontractmanagement.SalesSignConfirmationApproval;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.mapper.salescontractmanagement.SalesSignConfirmationApprovalMapper;
import com.sunxung.factoring.service.salescontractmanagement.ICSalesSignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.salescontractmanagement.ICSalesSignConfirmationService;
import com.sunxung.factoring.service.salescontractmanagement.ISalesSignConfirmationApprovalService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 销售合同-签署确认审核表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-12-11
 */
@Service("sign_confirmation_approvalService")
public class SalesSignConfirmationApprovalServiceImpl extends ServiceImpl<SalesSignConfirmationApprovalMapper, SalesSignConfirmationApproval>
        implements ISalesSignConfirmationApprovalService {

    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private ICSalesSignConfirmationElectronicInfoService salesSignConfirmationElectronicInfoService;
    @Autowired
    private ICSalesSignConfirmationService salesSignConfirmationService;
    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public SalesSignConfirmationApproval approval(Long id) {

        SalesSignConfirmationApproval confirmationApproval = new SalesSignConfirmationApproval();
        CSalesSignConfirmation salesSignConfirmation = salesSignConfirmationService.lambdaQuery()
                .eq(CSalesSignConfirmation::getcSalesContractManagementId, id).one();
        List<CSalesSignConfirmationElectronicInfo> list = salesSignConfirmationElectronicInfoService
                .lambdaQuery().eq(CSalesSignConfirmationElectronicInfo::getcSalesSignConfirmationId, salesSignConfirmation.getId())
                .list();
        List<FileStorage> files = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(r -> {
                FileStorage old = fileStorageService.get(r.getFileId());
                FileStorage fileStorage = fileStorageService.get(r.getBackFileId());
                fileStorage.setOriginalName(old.getOriginalName());
                files.add(fileStorage);
            });
        }
        confirmationApproval.setFiles(files);
        return confirmationApproval;

    }

    @Override
    public void doApproval(SalesSignConfirmationApproval salesSignConfirmationApproval) {

        CSalesContract contractManagement = salesContractService.getById(salesSignConfirmationApproval.getcSalesContractManagementId());
        save(salesSignConfirmationApproval);

        //流程处理
        handleProcess(contractManagement, salesSignConfirmationApproval);

    }

    @Override
    public SalesSignConfirmationApproval getView(Long id) {

        SalesSignConfirmationApproval confirmationApproval = getById(id);
        CSalesSignConfirmation salesSignConfirmation = salesSignConfirmationService.lambdaQuery()
                .eq(CSalesSignConfirmation::getcSalesContractManagementId, confirmationApproval.getcSalesContractManagementId()).one();
        if (salesSignConfirmation != null) {
            List<CSalesSignConfirmationElectronicInfo> list = salesSignConfirmationElectronicInfoService
                    .lambdaQuery().eq(CSalesSignConfirmationElectronicInfo::getcSalesSignConfirmationId, salesSignConfirmation.getId())
                    .list();
            List<FileStorage> files = new ArrayList<>();

            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(r -> {
                    FileStorage old = fileStorageService.get(r.getFileId());
                    FileStorage fileStorage = fileStorageService.get(r.getBackFileId());
                    fileStorage.setOriginalName(old.getOriginalName());
                    files.add(fileStorage);
                });
            }
            confirmationApproval.setFiles(files);
        }

        return confirmationApproval;
    }

    private void handleProcess(CSalesContract contractManagement, SalesSignConfirmationApproval approval) {
        //流程处理
        String processKey = ConstantUtil.SALES_CONTRACT;


        Map<String, Object> msgVariables = new HashMap<>(2);
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, contractManagement.getBusinessNumber());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为" + contractManagement.getBusinessNumber() + "”的项目已inOut“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(processKey) + "—formBusiness”阶段，");
        Boolean success = flowableService.completeMyTask(approval.getTaskId(), contractManagement, null,
                ConstantConversionUtil.processApprovalResult.get(approval.getApprovalConclusion()),
                approval.getId(), msgVariables, processKey);
        if (success == null || !success) {
            throw new ValidatorException(CodeUtil.FAIL, "销售合同审批出错啦！");
        }

        //如果审核结论为通过、修改合同状态为已审核
        if (approval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
            contractManagement.setContractStatus(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());
        }

        salesContractService.updateById(contractManagement);
    }

}
