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

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.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.dict.impl.PurchContractStatusDict;
import com.sunxung.factoring.entity.businessmanagement.BusinessBasicInfo;
import com.sunxung.factoring.entity.purchcontractmanagement.*;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.mapper.purchcontractmanagement.PurchContractSupplementSignApprovalMapper;
import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
import com.sunxung.factoring.service.purchcontractmanagement.*;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
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 daxian
 * @since 2022-03-15
 */
@Service("purch_contract_change_final_approvalService")
public class PurchContractSupplementSignApprovalServiceImpl extends ServiceImpl<PurchContractSupplementSignApprovalMapper, PurchContractSupplementSignApproval> implements IPurchContractSupplementSignApprovalService {

    @Autowired
    PurchContractService purchContractService;

    @Autowired
    IPurchContractSupplementInfoService supplementInfoService;

    @Autowired
    IPurchContractSupplementSignApprovalService supplementSignApprovalService;

    @Autowired
    BusinessBasicInfoService businessBasicInfoService;

    @Autowired
    FlowableService flowableService;

    @Autowired
    DictionaryService dictService;

    @Autowired
    ISysAttachmentRefService attachmentRefService;

    @Autowired
    private IPurchContractSupplementApprovalService purchContractSupplementApprovalService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Override
    @Transactional
    public void audit(PurchContractSupplementSignApproval signApproval) {
        if (signApproval == null || signApproval.getBusinessKey() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "变更签署审核信息或者业务id不能为空");
        }

        PurchContractManagement purchContractManagement = purchContractService.getById(signApproval.getBusinessKey());
        if (purchContractManagement == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同管理信息");
        }

        PurchContractSupplementInfo supplementInfo = supplementInfoService
                .lambdaQuery().eq(PurchContractSupplementInfo::getPurchContractManagementId,signApproval.getBusinessKey())
                .orderByDesc(PurchContractSupplementInfo::getGmtCreate).last("limit 1").one();

        if (supplementInfo == null) {
            throw new BusinessException(CodeUtil.FAIL, "未查到该变更信息");
        }

        //保存变更审批       approval
        signApproval.setPurchContractSupplementInfoId(supplementInfo.getId());
        supplementSignApprovalService.save(signApproval);

        //流程处理
        String processKey = ConstantUtil.PURCH_CONTRACT_CHANGE_PROCESS;

        String result;

        //如果审核结论为通过、修改合同状态为 已审核
        if (signApproval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
            purchContractManagement.setContractStatus(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());
            result = ConstantConversionUtil.APPROVAL_RESULT_PASS_DISPLAY;
        } else if (signApproval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
            result = ConstantConversionUtil.APPROVAL_RESULT_BACK_DISPLAY;
        } else {
            throw new ValidatorException(CodeUtil.FAIL, "结论不正确！");
        }

        purchContractService.updateById(purchContractManagement);

        Map<String, Object> procVariables = new HashMap<>();
        procVariables.put("result", result);

        Map<String, Object> msgVariables = new HashMap<>(2);
        PurchContractBasicInfo basicInfo = purchContractBasicInfoService
                .lambdaQuery().eq(PurchContractBasicInfo::getPurchContractManagementId, signApproval.getBusinessKey()).one();
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, basicInfo.getProjectName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为" + purchContractManagement.getBusinessNumber() + "”的项目已inOut“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(processKey) + "—formBusiness”阶段，");
        Boolean success = flowableService.completeMyTask(signApproval.getTaskId(), purchContractManagement, procVariables,
                null,
                signApproval.getId(), msgVariables, processKey);
        if (success == null || !success) {
            throw new ValidatorException(CodeUtil.FAIL, "采购合同签署审批出错啦！");
        }

    }

    @Override
    public PurchContractSupplementSignApproval getView(Long id) {
        PurchContractSupplementSignApproval signApproval = supplementSignApprovalService.getById(id);

        PurchContractSupplementInfo purch = supplementInfoService.getById(signApproval.getPurchContractSupplementInfoId());
        if (purch != null && purch.getId() != null) {
            List<FileStorage> fileStorageList = new ArrayList<>();
            fileStorageList.addAll(attachmentRefService.getFiles(AttachmentDto.builder()
                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_SIGN_FILE).setEntityId(purch.getId()).build()));
            signApproval.setFileStorageList(fileStorageList);
        }

        return signApproval;
    }

}
