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.*;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.mapper.salescontractmanagement.SalesSupplementSignConfirmationApprovalMapper;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.salescontractmanagement.*;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 销售合同变更-签署确认审核表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-12-13
 */
@Service("supplement_sign_confirmation_approvalService")
public class SalesSupplementSignConfirmationApprovalServiceImpl extends ServiceImpl<SalesSupplementSignConfirmationApprovalMapper,
        SalesSupplementSignConfirmationApproval> implements ISalesSupplementSignConfirmationApprovalService {

    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private ICSalesContractSupplementInfoService salesContractSupplementInfoService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private ICSalesSupplementSignConfirmationService salesSupplementSignConfirmationService;
    @Autowired
    private ICSalesSupplementSignConfirmationElectronicInfoService salesSupplementSignConfirmationElectronicInfoService;
    @Autowired
    private FileStorageService fileStorageService;


    @Override
    public SalesSupplementSignConfirmationApproval approval(Long id) {

        SalesSupplementSignConfirmationApproval confirmationApproval = new SalesSupplementSignConfirmationApproval();
        CSalesContractSupplementInfo supplementInfo = salesContractSupplementInfoService.lambdaQuery().eq(CSalesContractSupplementInfo::getcSalesContractManagementId, id)
                .orderByDesc(CSalesContractSupplementInfo::getGmtCreate).last("limit 1").one();
        CSalesSupplementSignConfirmation supplementSignConfirmation = salesSupplementSignConfirmationService
                .lambdaQuery().eq(CSalesSupplementSignConfirmation::getcSalesContractSupplementInfoId, supplementInfo.getId())
                .one();
        List<CSalesSupplementSignConfirmationElectronicInfo> list = salesSupplementSignConfirmationElectronicInfoService
                .lambdaQuery().eq(CSalesSupplementSignConfirmationElectronicInfo::getcSalesSupplementSignConfirmationId,
                        supplementSignConfirmation.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
    @Transactional(rollbackFor = Exception.class)
    public void doApproval(SalesSupplementSignConfirmationApproval salesSignConfirmationApproval) {

        CSalesContractSupplementInfo supplementInfo = salesContractSupplementInfoService
                .lambdaQuery().eq(CSalesContractSupplementInfo::getcSalesContractManagementId,salesSignConfirmationApproval.getBusinessKey())
                .orderByDesc(CSalesContractSupplementInfo::getGmtCreate).one();
        CSalesContract contractManagement = salesContractService.getById(supplementInfo.getcSalesContractManagementId());
        salesSignConfirmationApproval.setcSalesContractSupplementInfoId(supplementInfo.getId());
        save(salesSignConfirmationApproval);

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

    }

    @Override
    public SalesSupplementSignConfirmationApproval getView(Long id) {

        SalesSupplementSignConfirmationApproval confirmationApproval = getById(id);
//        CSalesContractSupplementInfo supplementInfo = salesContractSupplementInfoService.lambdaQuery().eq(CSalesContractSupplementInfo::getcSalesContractManagementId, id)
//                .orderByDesc(CSalesContractSupplementInfo::getGmtCreate).last("limit 1").one();
        CSalesSupplementSignConfirmation supplementSignConfirmation = salesSupplementSignConfirmationService
                .lambdaQuery().eq(CSalesSupplementSignConfirmation::getcSalesContractSupplementInfoId, confirmationApproval.getcSalesContractSupplementInfoId())
                .one();
        List<CSalesSupplementSignConfirmationElectronicInfo> list = salesSupplementSignConfirmationElectronicInfoService
                .lambdaQuery().eq(CSalesSupplementSignConfirmationElectronicInfo::getcSalesSupplementSignConfirmationId,
                        supplementSignConfirmation.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, SalesSupplementSignConfirmationApproval approval) {
        //流程处理
        String processKey = ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS;
        String assigneeKey = ConstantUtil.SALES_SIGN_CONFIRMATION_APPROVAL + ConstantUtil._CANDIDATE;

        Map<String, Object> procVariables = new HashMap<>(1);
        procVariables.put(assigneeKey,
                assigneeService.getIdByBusiness(contractManagement.getId(), processKey, ConstantUtil.ASSIGNEE_LEGAL_SPECIALIST));

        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, procVariables,
                null,
                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);
    }

}
