package com.sunxung.factoring.service.salescontractmanagement.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.*;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.salescontractmanagement.*;
import com.sunxung.factoring.entity.salescontractmanagement.vo.SalesContractBasicVo;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import com.sunxung.factoring.mapper.salescontractmanagement.CSalesContractSupplementInfoMapper;
import com.sunxung.factoring.mapper.salescontractmanagement.SalesContractMapper;
import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
import com.sunxung.factoring.service.customerinformation.IElectronicSignaturePersonalService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.salescontractmanagement.*;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationService;
import com.sunxung.factoring.service.sys.*;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售合同-补充信息表 服务实现类
 * </p>
 *
 * @author daxian
 * @since 2022-03-03
 */
@Service("sales_contract_create_changeService")
public class SalesContractSupplementInfoServiceImpl extends ServiceImpl<CSalesContractSupplementInfoMapper, CSalesContractSupplementInfo>
        implements ISalesContractSupplementInfoService {

    @Autowired
    private BusinessBasicInfoService businessBasicInfoService;
    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private DictionaryService dictService;
    @Autowired
    private ISysAttachmentRefService attachmentRefService;
    @Autowired
    private ISalesContractSupplementGoodsInfoService salesContractSupplementGoodsInfoService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private ISalesContractSupplementApprovalService salesContractSupplementApprovalService;
    @Autowired
    private UserService userService;
    @Autowired
    private ISalesContractSupplementHisInfoService salesContractSupplementHisInfoService;
    @Autowired
    private ISalesContractSupplementGoodsInfoHistoryService salesContractSupplementGoodsInfoHistoryService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;
    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;
    @Autowired
    private ISignConfirmationService signConfirmationService;
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;
    @Autowired
    private ISalesContractSupplementApprovalPersonInfoHistoryRefService salesContractSupplementApprovalPersonInfoHistoryRefService;
    @Autowired
    private ICSalesContractSupplementPersonInfoService supplementPersonInfoService;
    @Autowired
    private ISalesContractSupplementPersonInfoHistoryService salesContractSupplementPersonInfoHistoryService;
    @Autowired
    private SalesContractMapper salesContractMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean doChange(CSalesContractSupplementInfo salesContractSupplementInfo) {

        if (salesContractSupplementInfo.getChangeType() == 1) {
            //选择经办人变更时，人员信息必传
            if (CollectionUtil.isEmpty(salesContractSupplementInfo.getSupplementPersonInfos())) {
                throw new BusinessException(CodeUtil.FAIL, "人员信息不能为空！");
            }
        }

        if (salesContractSupplementInfo.getChangeType() == 0) {
            if (CollectionUtil.isEmpty(salesContractSupplementInfo.getFileIds())) {
                throw new BusinessException(CodeUtil.FAIL, "合同模板不能为空！");
            }
        }

        ThreadLocalUtil.setUser(userService.getByLoginName("admin"));

        if (salesContractSupplementInfo.getId() != null) {
            //退回
            updateById(salesContractSupplementInfo);

            //合同模板
            fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, salesContractSupplementInfo.getId())
                    .eq(FileStorageDO::getBusinessType, FileModuleDict.ChildEnum.SALES_SUPPLEMENT_CONTRACT_TEMPLATE_FILE.getCode())
                    .set(FileStorageDO::getBusinessId, null);
        } else {
            //新增
            save(salesContractSupplementInfo);
        }

        //合同文件
        List<Long> fileIds = salesContractSupplementInfo.getFileIds();
        if (CollectionUtil.isNotEmpty(fileIds)) {
            fileIds.forEach(c -> {
                FileStorageDO fileStorageDO = fileService.getById(c);
                fileStorageDO.setBusinessId(salesContractSupplementInfo.getId());
                fileService.updateById(fileStorageDO);
            });
        }

        if (salesContractSupplementInfo.getChangeType() == 1) {

            //删除人员信息
            supplementPersonInfoService.remove(new QueryWrapper<CSalesContractSupplementPersonInfo>()
                    .eq("c_sales_contract_supplement_info_id", salesContractSupplementInfo.getId()));
            //新增人员信息
            salesContractSupplementInfo.getSupplementPersonInfos().forEach(person -> {
                person.setcSalesContractSupplementInfoId(salesContractSupplementInfo.getId());
                supplementPersonInfoService.save(person);
            });

        }

        CSalesContract salesContractManagement = salesContractService.getById(salesContractSupplementInfo.getcSalesContractManagementId());

        //已完成状态才能变更
        if (salesContractManagement.getContractStatus().equals(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode())) {
            salesContractService.change(salesContractManagement.getId());
        }
        BusinessProcessingLog processingLog = businessProcessingLogService
                .getByBusinessTypeBusinessKey(ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS, salesContractManagement.getId());

        salesContractSupplementInfo.setTaskId(processingLog.getHistoricTaskId());

        //流程处理
        handleProcess(salesContractManagement, salesContractSupplementInfo);

        //变更状态为处理中
        salesContractManagement.setContractStatus(ProjectInitiationStatusDict.ChildEnum.PROCESSING.getCode());
        salesContractService.updateById(salesContractManagement);

        return true;
    }

    private Long addhistory(CSalesContractSupplementInfo salesContractSupplementInfo) {
        Long oldId = salesContractSupplementInfo.getId();
        //保存变更信息历史
        SalesContractSupplementHisInfo salesContractSupplementInfoHistory = new SalesContractSupplementHisInfo();
        BeanUtils.copyProperties(salesContractSupplementInfo, salesContractSupplementInfoHistory);
        salesContractSupplementInfoHistory.setId(null);
        salesContractSupplementInfoHistory.setcSalesContractSupplementInfoId(salesContractSupplementInfo.getId());
        salesContractSupplementHisInfoService
                .save(salesContractSupplementInfoHistory);

        //保存人员信息
        if (CollectionUtil.isNotEmpty(salesContractSupplementInfo.getSupplementPersonInfos())) {
            salesContractSupplementInfo.getSupplementPersonInfos().forEach(person -> {
                SalesContractSupplementPersonInfoHistory personInfoHistory = new SalesContractSupplementPersonInfoHistory();
                BeanUtils.copyProperties(person, personInfoHistory);
                personInfoHistory.setcSalesContractSupplementHisInfoId(salesContractSupplementInfoHistory.getId());
                salesContractSupplementPersonInfoHistoryService.save(personInfoHistory);
            });
        }

        //合同模板
        List<FileStorageDO> fileStorages = null;
        if (CollectionUtil.isNotEmpty(salesContractSupplementInfo.getFileIds())) {
            fileStorages = fileService.listByIds(salesContractSupplementInfo.getFileIds());
        }

        if (CollectionUtil.isNotEmpty(fileStorages)) {
            fileStorages.forEach(fileStorageDO -> {
                FileStorageDO fileHis = new FileStorageDO();
                BeanUtils.copyProperties(fileStorageDO, fileHis, "id");
                fileHis.setBusinessId(salesContractSupplementInfoHistory.getId());
                fileHis.setBusinessType(FileModuleDict.ChildEnum.SALES_SUPPLEMENT_CONTRACT_TEMPLATE_HIS_FILE.getCode());
                fileService.save(fileHis);
            });
        }

        return salesContractSupplementInfoHistory.getId();
    }


    @Override
    public SalesContractSupplementHisInfo getView(Long id) {

        SalesContractSupplementHisInfo supplementHisInfo = salesContractSupplementHisInfoService.getById(id);
        SalesContractBasicVo contractBasicVo = salesContractMapper.getBasicInfoById(supplementHisInfo.getcSalesContractManagementId());
        supplementHisInfo.setSalesContractBasicVo(contractBasicVo);

        //人员信息
        List<SalesContractSupplementPersonInfoHistory> personInfoHistories = salesContractSupplementPersonInfoHistoryService
                .list(new QueryWrapper<SalesContractSupplementPersonInfoHistory>()
                        .eq("sales_contract_supplement_his_info_id", id));
        supplementHisInfo.setPersonInfoHistoryList(personInfoHistories);

        //文件
        List<FileStorageDO> list = fileService.lambdaQuery().eq(FileStorageDO::getBusinessId, id)
                .eq(FileStorageDO::getBusinessType, FileModuleDict.ChildEnum.SALES_SUPPLEMENT_CONTRACT_TEMPLATE_HIS_FILE.getCode()).list();
        supplementHisInfo.setFileStorageList(list);

        return supplementHisInfo;
    }


    /**
     * 变更处理流程
     *
     * @param salesContractManagement
     * @param salesContractSupplementInfo
     */
    public void handleProcess(CSalesContract salesContractManagement, CSalesContractSupplementInfo salesContractSupplementInfo) {

        addhistory(salesContractSupplementInfo);

        //走变更流程
        String processKey = ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS;
        String assigneeKey = ConstantUtil.SUPPLEMENT_TEMPLATE_FIRST_APPROVAL + ConstantUtil._CANDIDATE;

        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.OPERATION_SPECIALIST + "角色内无任何用户！");
        }
        String legalIds = legalSpecialists.stream().map(c -> c.toString()).collect(Collectors.joining(","));

        Map<String, Object> procVariables = new HashMap<>(1);
        procVariables.put(assigneeKey,legalIds);
        Map<String, Object> msgVariables = new HashMap<>(2);
        //项目信息
        ProjectInformation projectInformation = projectInformationService
                .getOne(new QueryWrapper<ProjectInformation>()
                        .eq("business_number", salesContractManagement.getBusinessNumber()));
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, projectInformation.getProjectName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为" + salesContractManagement.getBusinessNumber() + "”的项目已inOut“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(processKey) + "—formBusiness”阶段，");

        Long historyId = addhistory(salesContractSupplementInfo);
        Boolean success = flowableService.completeMyTask(salesContractSupplementInfo.getTaskId(), salesContractManagement, procVariables, null, historyId,
                msgVariables, processKey, legalSpecialists);
        if (success == null || !success) {
            throw new ValidatorException(CodeUtil.FAIL, "销售合同变更-创建时出错啦！");
        }

        salesContractManagement.setModify(true);
        salesContractManagement.setContractStatus(ProjectInitiationStatusDict.ChildEnum.PROCESSING.getCode());
        salesContractService.updateById(salesContractManagement);
    }

}
