package com.jwipc.supplier.logic.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jwipc.aggregation.ModelAggregationService;
import com.jwipc.constant.DelFlag;
import com.jwipc.constant.EnableStatus;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.prop.SysProp;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.constant.*;
import com.jwipc.supplier.convert.*;
import com.jwipc.supplier.dto.*;
import com.jwipc.supplier.entity.*;
import com.jwipc.supplier.logic.SupplierChangeLogic;
import com.jwipc.supplier.logic.SupplierToOaLogic;
import com.jwipc.supplier.model.po.FieldDictPO;
import com.jwipc.supplier.model.po.SupplierBankVersionComparePO;
import com.jwipc.supplier.model.po.SupplierContactsVersionComparePO;
import com.jwipc.supplier.model.po.SupplierPurchaseCategoryVersionComparePO;
import com.jwipc.supplier.model.query.SupplierChangeQuery;
import com.jwipc.supplier.service.*;
import com.jwipc.sys.client.AreaClient;
import com.jwipc.sys.client.EmailSendClient;
import com.jwipc.sys.client.FileClient;
import com.jwipc.sys.client.UserClient;
import com.jwipc.sys.client.dto.EmailTmpSendDTO;
import com.jwipc.sys.client.dto.FileResposeCDTO;
import com.jwipc.sys.client.dto.UserDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SupplierChangeLogicImpl implements SupplierChangeLogic {
    private final ISupplierChangeVersionService supplierChangeVersionService;
    private final SupplierChangeVersionConvert supplierChangeVersionConvert;
    private final SupplierPurchaseCategoryVersionConvert supplierPurchaseCategoryVersionConvert;
    private final SupplierBankVersionConvert supplierBankVersionConvert;
    private final ISupplierService supplierService;
    private final ISupplierFieldService supplierFieldService;
    private final ISupplierExtensionService supplierExtensionService;
    private final ISupplierBankService supplierBankService;
    private final ISupplierBankVersionService supplierBankVersionService;
    private final ISupplierContactsService supplierContactsService;
    private final ISupplierContactsVersionService supplierContactsVersionService;
    private final SupplierContactsVersionConvert supplierContactsVersionConvert;
    private final ISupplierPurchaseCategoryService supplierPurchaseCategoryService;
    private final ISupplierPurchaseCategoryVersionService supplierPurchaseCategoryVersionService;
    private final SupplierChangeAttachmentConvert supplierChangeAttachmentConvert;
    private final ISupplierChangeAttachmentService supplierChangeAttachmentService;
    private final AreaClient areaClient;
    private final ISupplierTemplateFieldRelationService supplierTemplateFieldRelationService;
    private final ISupplierVersionService supplierVersionService;
    private final SupplierVersionConvert supplierVersionConvert;
    private final FileClient fileClient;
    private final ISupplierQualificationService supplierQualificationService;
    private final ISupplierQualificationChangeItemService supplierQualificationChangeItemService;
    private final SupplierQualificationChangeItemConvert qualificationChangeItemConvert;
    private final ModelAggregationService modelAggregationService;
    private final SupplierQualificationConvert supplierQualificationConvert;
    private final SupplierToOaLogic supplierToOaLogic;
    private final UserClient userClient;
    private final EmailSendClient emailSendClient;
    private final ISupplierInvitaionService supplierInvitaionService;
    private final ISupplierExtensionVersionService supplierExtensionVersionService;
    private final ISupplierBankVersionWholeService supplierBankVersionWholeService;
    private final ISupplierChangeAttachmentWholeService supplierChangeAttachmentWholeService;
    private final ISupplierContactsVersionWholeService supplierContactsVersionWholeService;
    private final ISupplierPurchaseCategoryVersionWholeService supplierPurchaseCategoryVersionWholeService;
    private final ISupplierQualificationChangeItemWholeService supplierQualificationChangeItemWholeService;
    private final SupplierBankVersionWholeConvert supplierBankVersionWholeConvert;
    private final SupplierPurchaseCategoryVersionWholeConvert supplierPurchaseCategoryVersionWholeConvert;
    private final SupplierChangeAttachmentWholeConvert supplierChangeAttachmentWholeConvert;
    private final SupplierContactsVersionWholeConvert supplierContactsVersionWholeConvert;
    private final SupplierQualificationChangeItemWholeConvert supplierQualificationChangeItemWholeConvert;
    private final SysProp sysProp;
    @Override
    public PageView getList(SupplierChangeQuery query) {
        final Page<SupplierChangeVersion> page = PageUtil.toPage(query);
        //更换成mapper.xml查询
        if (LoginUtil.isSupplier()) {
            query.setSupplierId(LoginUtil.getSupplierId());
            query.setOptType(1);
        } else {
//            final Set<String> userPurchaseGroupCode = userPurchaseGroupClient.getUserPurchaseGroupCode(
//                    LoginUtil.getUserId());
//            query.setUserPurchaseGroupCodes(userPurchaseGroupCode);
            query.setUserId(LoginUtil.getUserId());
        }
        final List<SupplierChangeVersion> list = supplierChangeVersionService.findList(page, query);
        List<SupplierChangeVersionBaseDTO> dtos = supplierChangeVersionConvert.entities2Dtos(list);
        return PageUtil.getPV(dtos, page.getTotal());
    }

    @Override
    public PageView getListAll(SupplierChangeQuery query) {
        final Page<SupplierChangeVersion> page = PageUtil.toPage(query);
        final List<SupplierChangeVersion> list = supplierChangeVersionService.findListAll(page, query);
        List<SupplierChangeVersionBaseDTO> dtos = supplierChangeVersionConvert.entities2Dtos(list);
        return PageUtil.getPV(dtos, page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(SupplierChangeSaveDTO supplierChangeSaveDTO) {
        //当前提交的供应商数据
        final Map<String, Object> tmpMap = supplierChangeSaveDTO.getSupplier();
        Map<String, String> supplierMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : tmpMap.entrySet()) {
            String key = entry.getKey();
            String value = convertToString(entry.getValue());
            supplierMap.put(StrUtil.toCamelCase(key), value);
        }
        final Long supplierId = Long.valueOf(supplierMap.get("id"));
        validate(supplierId);
        final Integer currentVersion = getCurrentVersion(supplierId);


        /**
         *
         * 判断当前变更版本如果是1表示是第一次，增加一条版本为0 的供应商信息备份
         */
        if (currentVersion == 1) {
            firstChangeVersionSaveBack(supplierId);
        }
        final Supplier dbSupplier = supplierService.getById(supplierId);
        final Long changeVersionId;


        //==============
        List<SupplierQualificationChangeDTO> changeDTOS = null;
        Set<Long> editIds = null;
        boolean changeFlag = false;
        //==============
        //查询当前变更已生成的OA编号
        String bpmCode = "";
        if (Objects.nonNull(supplierChangeSaveDTO.getChangeVersionId()) &&
                supplierChangeSaveDTO.getChangeVersionId() > 0) {
            SupplierChangeVersion changeVersionServiceById = supplierChangeVersionService.getById(
                    supplierChangeSaveDTO.getChangeVersionId());
            bpmCode = changeVersionServiceById.getBpmCode();
            changeVersionId = supplierChangeSaveDTO.getChangeVersionId();
            //变更驳回后重新提交，对供应商主数据变更和银行，联系人，资质文件，品类,附件，等version表进行先删除后新增
            //在原有变更单上重新发起的所有变更记录不走新建走修改
            //查询变更前供应商正式主表信息，用于对不本次修改了哪些主表信息
            //1.修改 SupplierChangeVersion 表
            final SupplierChangeVersion changeVersionUpdate = new SupplierChangeVersion();
            changeVersionUpdate.setId(supplierChangeSaveDTO.getChangeVersionId());
            changeVersionUpdate.setSupplierId(supplierId);
            changeVersionUpdate.setSupplierName(dbSupplier.getSupplierName());
            changeVersionUpdate.setSupplierCode(dbSupplier.getSupplierCode());
            changeVersionUpdate.setRemark(supplierChangeSaveDTO.getRemark());
            changeVersionUpdate.setOaType(supplierChangeSaveDTO.getOaType());
            changeVersionUpdate.setOpenFlag(supplierChangeSaveDTO.getOpenFlag());
            changeVersionUpdate.setExecutionTime(supplierChangeSaveDTO.getExecutionTime());
            changeVersionUpdate.setPaymentTerms(supplierChangeSaveDTO.getPaymentTerms());
            changeVersionUpdate.setBpmCode(bpmCode);
            if (LoginUtil.isSupplier()) {
                changeVersionUpdate.setOptType(ChangeOptType.SUPPLIER.getType());
                changeVersionUpdate.setExamineState(SupplierChangeExamineState.APPROVALING.getVal());
            } else {
                changeVersionUpdate.setOptType(ChangeOptType.PROCUREMENT.getType());
                changeVersionUpdate.setEliminateFlag(supplierChangeSaveDTO.getEliminateFlag());
                changeVersionUpdate.setExecutionTime(supplierChangeSaveDTO.getExecutionTime());
                changeVersionUpdate.setPaymentTerms(supplierChangeSaveDTO.getPaymentTerms());
            }
            supplierChangeVersionService.updateById(changeVersionUpdate);
            extracted(changeVersionId);
            //===============
            //需要处理资质变更数据
            final List<SupplierQualificationChangeDTO> supplierQualificationsList =
                    supplierChangeSaveDTO.getSupplierQualificationsList();
            //需要把新增和编辑的数据处理下
            changeDTOS = supplierQualificationsList.stream()
                    .filter(a -> a.getType() == VersionChangeType.CREATE.getType() ||
                            a.getType() == VersionChangeType.EDIT.getType()).toList();
            //变更重新发起时判断 qualificationId的值
            editIds = changeDTOS.stream().filter(a -> Objects.nonNull(a.getQualificationId()))
                    .map(SupplierQualificationChangeDTO::getQualificationId).collect(Collectors.toSet());
            //原始新增
            changeFlag = true;

            //===============

        } else {
            //新增变更申请主表
            final SupplierChangeVersion changeVersionCreate = new SupplierChangeVersion();
            changeVersionCreate.setSupplierId(supplierId);
            changeVersionCreate.setSupplierName(dbSupplier.getSupplierName());
            changeVersionCreate.setSupplierCode(dbSupplier.getSupplierCode());
            changeVersionCreate.setCreator(LoginUtil.getUserId());
            changeVersionCreate.setCreateTime(LocalDateTime.now());
            changeVersionCreate.setVersion(currentVersion);
            changeVersionCreate.setRemark(supplierChangeSaveDTO.getRemark());
            changeVersionCreate.setOaType(supplierChangeSaveDTO.getOaType());
            changeVersionCreate.setOpenFlag(supplierChangeSaveDTO.getOpenFlag());
            changeVersionCreate.setBpmCode(bpmCode);
            if (LoginUtil.isSupplier()) {
                changeVersionCreate.setOptType(ChangeOptType.SUPPLIER.getType());
            } else {
                changeVersionCreate.setOptType(ChangeOptType.PROCUREMENT.getType());
                changeVersionCreate.setEliminateFlag(supplierChangeSaveDTO.getEliminateFlag());
                changeVersionCreate.setExecutionTime(supplierChangeSaveDTO.getExecutionTime());
                changeVersionCreate.setPaymentTerms(supplierChangeSaveDTO.getPaymentTerms());
            }
            supplierChangeVersionService.save(changeVersionCreate);
            changeVersionId = changeVersionCreate.getId();

            //需要处理资质变更数据 ===========
            final List<SupplierQualificationChangeDTO> supplierQualificationsList =
                    supplierChangeSaveDTO.getSupplierQualificationsList();
            //需要把新增和编辑的数据处理下
            changeDTOS = supplierQualificationsList.stream()
                    .filter(a -> a.getType() == VersionChangeType.CREATE.getType() ||
                            a.getType() == VersionChangeType.EDIT.getType()).toList();
            //原始新增
            editIds = changeDTOS.stream().filter(a -> Objects.nonNull(a.getId()))
                    .map(SupplierQualificationChangeDTO::getId).collect(Collectors.toSet());

            //===============
        }
        //处理资质文件
        //需要取供应商原来的资质数据
        final Map<Long, SupplierQualification> qualificationCache = Maps.newHashMap();
        if (CollUtil.isNotEmpty(editIds)) {
            final List<SupplierQualification> supplierQualifications = supplierQualificationService.listByIds(editIds);
            qualificationCache.putAll(
                    supplierQualifications.stream().collect(Collectors.toMap(SupplierQualification::getId, a -> a)));
        }
        //需要处理数据
        List<SupplierQualificationChangeItem> supplierQualificationChanges = Lists.newArrayList();
        for (SupplierQualificationChangeDTO changeDTO : changeDTOS) {
            SupplierQualificationChangeItem qualificationChangeItem = new SupplierQualificationChangeItem();
            qualificationChangeItem.setVersionChangeId(changeVersionId);
            Long id;
            if (changeFlag) {
                id = changeDTO.getQualificationId();
            } else {
                id = changeDTO.getId();
            }

            if (Objects.nonNull(id)) {
                final SupplierQualification supplierQualification = qualificationCache.get(id);
                if (Objects.nonNull(supplierQualification)) {
                    qualificationChangeItem.setQualificationId(supplierQualification.getId());
                    qualificationChangeItem.setQualificationNumber(supplierQualification.getQualificationNumber());
                    qualificationChangeItem.setAvailableStartDate(supplierQualification.getAvailableStartDate());
                    qualificationChangeItem.setAvailableEndDate(supplierQualification.getAvailableEndDate());
                    qualificationChangeItem.setFileId(supplierQualification.getFileId());
                }
            }
            qualificationChangeItem.setQualificationCode(changeDTO.getQualificationCode());
            qualificationChangeItem.setQualificationName(changeDTO.getQualificationName());
            qualificationChangeItem.setNewQualificationNumber(changeDTO.getQualificationNumber());
            qualificationChangeItem.setNewFileId(changeDTO.getFileId());
            qualificationChangeItem.setNewAvailableEndDate(changeDTO.getAvailableEndDate());
            qualificationChangeItem.setNewAvailableStartDate(changeDTO.getAvailableStartDate());
            supplierQualificationChanges.add(qualificationChangeItem);
        }
        if (CollUtil.isNotEmpty(supplierQualificationChanges)) {
            supplierQualificationChangeItemService.saveBatch(supplierQualificationChanges);
        }

        //保存附件信息
        final List<SupplierChangeAttachmentBaseDTO> files = supplierChangeSaveDTO.getFiles();
        List<SupplierChangeAttachment> supplierChangeAttachments = supplierChangeAttachmentConvert.dtos2Entities(files);
        for (SupplierChangeAttachment supplierChangeAttachment : supplierChangeAttachments) {
            supplierChangeAttachment.setChangeVersionId(changeVersionId);
            supplierChangeAttachment.setSupplierId(supplierId);
        }
        final List<SupplierChangeAttachment> attachentsInsertLists = supplierChangeAttachments.stream()
                .filter(a -> Objects.nonNull(a.getFileId())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(attachentsInsertLists)) {
            supplierChangeAttachmentService.saveBatch(attachentsInsertLists);
        }
        Map<String, String> fieldNamTitleMap = new HashMap<>();
        final List<SupplierField> supplierFields = supplierFieldService.list(
                new LambdaQueryWrapper<SupplierField>().eq(SupplierField::getSupplierId, supplierId));
        final Map<String, String> dbSupplierData = getDbSupplierData(supplierId);
        List<SupplierVersion> modifyRecordList = Lists.newArrayList();
        supplierFields.forEach(e -> {
            final String field = StrUtil.toCamelCase(e.getFieldCode());
            final String original = StrUtil.isEmpty(dbSupplierData.get(field)) ? StrUtil.EMPTY : dbSupplierData.get(
                    field);
            final String value = StrUtil.isEmpty(supplierMap.get(field)) ? StrUtil.EMPTY : supplierMap.get(field);
            fieldNamTitleMap.put(field, e.getFieldAlias());
            //判断之前的值和现在的值是不是一样的，不一样的把变更存在记录表中
            if (!original.equals(value)) {
                //追加限制。1.供应商名称不能为空且不能重复 2.供应商简称同样 3.税号
                if (field.equals("supplierName")) {
                    if (StringUtils.isEmpty(value)) {
                        throw new DaoException("供应商名称不可为空");
                    }
                    List<Supplier>   supplierList=supplierService.list(
                            new LambdaQueryWrapper<Supplier>().eq(Supplier::getSupplierName, value));
                    if (CollectionUtils.isNotEmpty(supplierList) && supplierList.size()>0) {
                        Supplier ss=supplierList.get(0);
                        if(ss.getSupplierName().equals(value)){
                            throw new DaoException("供应商名称重复!");
                        }
                    }
                }
                if (field.equals("shortName")) {
                    if (StringUtils.isEmpty(value)) {
                        throw new DaoException("供应商简称不可为空");
                    }
                    final long count = supplierService.count(
                            new LambdaQueryWrapper<Supplier>().eq(Supplier::getShortName, value));
                    if (count > 0) {
                        throw new DaoException("供应商简称重复!");
                    }
                }
                if ("taxNo".equals(field)) {
                    if (StringUtils.isEmpty(value)) {
                        throw new DaoException("税号不能为空");
                    }
                    final long count = supplierService.count(
                            new LambdaQueryWrapper<Supplier>().eq(Supplier::getTaxNo, value));
                    if (count > 0) {
                        throw new DaoException("供应商税号重复!");
                    }
                }
                if ("creditNo".equals(field)) {
                    if (StringUtils.isEmpty(value)) {
                        throw new DaoException("信用代码不能为空");
                    }

                    final long count = supplierService.count(
                            new LambdaQueryWrapper<Supplier>().eq(Supplier::getCreditNo, value));
                    if (count > 0) {
                        throw new DaoException("供应商信用代码重复!");
                    }
                }

                final SupplierVersion modifyRecord = new SupplierVersion();
                modifyRecord.setChangeVersionId(changeVersionId);
                modifyRecord.setSupplierId(supplierId);
                modifyRecord.setField(field);
                modifyRecord.setFieldText(e.getFieldAlias());
                modifyRecord.setOriginal(original);
                modifyRecord.setValue(value);
                // TODO: 2024/2/28  jiez 这个类型默认给2
                modifyRecord.setType(2);


                /**
                 * 判断类型是字典类型的，需要保存字典值
                 * 如果变更的字典是 country，那么不能使用公共的字典方法查询，要去查另一张表的数据
                 */
                if (e.getFormControl() == TemplateFiledType.DICT.getType() ||
                        e.getFormControl() == TemplateFiledType.AREA.getType()) {
                    if (field.equals("country") || field.equals("province") || field.equals("city")) {
                        if (StringUtils.isNotEmpty(value)) {
                            final String areaName = areaClient.getAreaName(value);
                            modifyRecord.setValueText(areaName);
                        }

                        if (StringUtils.isNotEmpty(original)) {
                            final String areaName = areaClient.getAreaName(original);
                            modifyRecord.setValueText(areaName);
                        }
                    } else {


                        if (StringUtils.isNotEmpty(value)) {
                            final String sqlSentence = e.getSqlSentence();
                            final List<FieldDictPO> maps = supplierTemplateFieldRelationService.selectDataBySql(
                                    sqlSentence);
                            final Map<String, String> dictMap = maps.stream()
                                    .collect(Collectors.toMap(a -> a.getCODE(), b -> b.getNAME()));
                            modifyRecord.setValueText(dictMap.get(value));
                        }

                        if (StringUtils.isNotEmpty(original)) {
                            final String sqlSentence = e.getSqlSentence();
                            final List<FieldDictPO> maps = supplierTemplateFieldRelationService.selectDataBySql(
                                    sqlSentence);
                            final Map<String, String> dictMap = maps.stream()
                                    .collect(Collectors.toMap(a -> a.getCODE(), b -> b.getNAME()));
                            modifyRecord.setOriginalText(dictMap.get(original));
                        }
                    }

                }
                modifyRecordList.add(modifyRecord);
            }
        });
        if (CollUtil.isNotEmpty(modifyRecordList)) {
            supplierVersionService.saveBatch(modifyRecordList);
        }
        saveAllInfo(supplierChangeSaveDTO, tmpMap, fieldNamTitleMap, supplierId, changeVersionId, changeFlag);
        //供应商联系人,这个地方需要注意，把如果有id放到masterId里面，
        final List<SupplierContactsDTO> contactsList = supplierChangeSaveDTO.getContactsList();
        //这个地方需要注意，把如果有id放到masterId里面
        List<SupplierContactsVersion> contactsVersionList1 = supplierChangeVersionConvert.dtos2Entities(contactsList);
        final List<SupplierContactsVersion> contactsVersionList = contactsVersionList1.stream()
                .filter(a -> Objects.nonNull(a.getType())).toList();
        for (SupplierContactsVersion supplierContactsVersion : contactsVersionList) {

            final Long masterId;
            if (Objects.nonNull(supplierContactsVersion.getMasterId())) {
                masterId = supplierContactsVersion.getMasterId();
            } else {
                masterId = supplierContactsVersion.getId();
            }
            supplierContactsVersion.setMasterId(masterId);
            supplierContactsVersion.setSupplierId(supplierId);
            supplierContactsVersion.setChangeVersionId(changeVersionId);
            supplierContactsVersion.setId(IdWorker.getId());
        }
        if (CollUtil.isNotEmpty(contactsVersionList)) {
            supplierContactsVersionService.saveBatch(contactsVersionList);
        }

        //供应商银行
        final List<SupplierBankDTO> bankList1 = supplierChangeSaveDTO.getBankList();
        //这个地方需要注意，把如果有id放到masterId里面
        List<SupplierBankVersion> tmp = supplierBankVersionConvert.dtos2Entities(bankList1);
        final List<SupplierBankVersion> bankList = tmp.stream().filter(a -> Objects.nonNull(a.getType())).toList();
        for (SupplierBankVersion supplierBankVersion : bankList) {

            final Long masterId;
            if (Objects.nonNull(supplierBankVersion.getMasterId())) {
                masterId = supplierBankVersion.getMasterId();
            } else {
                masterId = supplierBankVersion.getId();
            }
            supplierBankVersion.setMasterId(masterId);
            supplierBankVersion.setSupplierId(supplierId);
            supplierBankVersion.setChangeVersionId(changeVersionId);
            supplierBankVersion.setId(IdWorker.getId());
        }
        if (CollUtil.isNotEmpty(bankList)) {
            supplierBankVersionService.saveBatch(bankList);
        }

        //供应商品类
        final List<SupplierPurchaseCategoryBaseDTO> categoryList =
                supplierChangeSaveDTO.getSupplierPurchaseCategoryList();
        if (CollUtil.isNotEmpty(categoryList)) {
            //这个地方需要注意，把如果有id放到masterId里面
            final List<SupplierPurchaseCategoryVersion> purchaseCategoryVersions =
                    supplierPurchaseCategoryVersionConvert.dtos2Entities(
                            categoryList);
            //需要根据品类、税率、币种、付款条件、公司、组织、付款方式判断啊采购品类的唯一性
            final Map<String, String> stringStringMap = purchaseCategoryVersions.stream().collect(
                    Collectors.toMap(
                            category -> {
                                final String format = StrUtil.format("{}-{}-{}-{}-{}-{}-{}",
                                        category.getPurchaseCategoryCode(),
                                        category.getTaxCode(),
                                        category.getCurrencyCode(),
                                        category.getPaymentTerms(),
                                        category.getCompanyCode(),
                                        category.getPurchaseOrgCode(),
                                        category.getPaymentMethod()
                                );
                                return format;
                            },
                            SupplierPurchaseCategoryVersion::getPurchaseCategoryName,
                            (existing, replacement) -> existing));
            //校验
            Map<String, Long> codeCountMap = purchaseCategoryVersions.stream()
                    .collect(Collectors.groupingBy(
                            category -> {
                                final String format = StrUtil.format("{}-{}-{}-{}-{}-{}-{}",
                                        category.getPurchaseCategoryCode(),
                                        category.getTaxCode(),
                                        category.getCurrencyCode(),
                                        category.getPaymentTerms(),
                                        category.getCompanyCode(),
                                        category.getPurchaseOrgCode(),
                                        category.getPaymentMethod()
                                );
                                return format;
                            },
                            Collectors.counting()
                    ));

            boolean hasDuplicates = codeCountMap.values().stream().anyMatch(a -> a > 1);
            if (hasDuplicates) {
                Set<String> tipMsg = Sets.newHashSet();
                codeCountMap.entrySet().stream()
                        .filter(entry -> entry.getValue() > 1)
                        .forEach(entry -> tipMsg.add(stringStringMap.get(entry.getKey())));
                throw new DaoException(String.join(",", tipMsg) + "出现重复");
            }
            //需要把type是null过滤掉
            List<SupplierPurchaseCategoryVersion> supplierProductTypeVersionList = purchaseCategoryVersions.stream()
                    .filter(a -> Objects.nonNull(a.getType())).toList();
            for (SupplierPurchaseCategoryVersion categoryVersion : supplierProductTypeVersionList) {
                final Long masterId;
                if (Objects.nonNull(categoryVersion.getMasterId())) {
                    masterId = categoryVersion.getMasterId();
                } else {
                    masterId = categoryVersion.getId();
                }
                categoryVersion.setMasterId(masterId);
                categoryVersion.setSupplierId(supplierId);
                categoryVersion.setChangeVersionId(changeVersionId);
                categoryVersion.setId(IdWorker.getId());
            }
            if (CollUtil.isNotEmpty(supplierProductTypeVersionList)) {
                supplierPurchaseCategoryVersionService.saveBatch(supplierProductTypeVersionList);
            }
        }

        //如果是采购提交，直接提交OA
        if (!LoginUtil.isSupplier()) {
            ChangeExamineParamDTO changeExamineParamDTO = new ChangeExamineParamDTO();
            changeExamineParamDTO.setRemark("");
            changeExamineParamDTO.setOaType(supplierChangeSaveDTO.getOaType());
            changeExamineParamDTO.setState(SupplierChangeExamineState.PASS.getVal());
            changeExamineParamDTO.setId(changeVersionId);
            changeExamineParamDTO.setIsFreeze(supplierChangeSaveDTO.getIsFreeze());
            changeExamineParamDTO.setEliminateFlag(supplierChangeSaveDTO.getEliminateFlag());
            changeExamineParamDTO.setExecutionTime(supplierChangeSaveDTO.getExecutionTime());
            changeExamineParamDTO.setPaymentTerms(supplierChangeSaveDTO.getPaymentTerms());
            examine(changeExamineParamDTO);
        } else {
            //供应商提交的需要通知供应商的邀请人
            //需要发送邮件
            final EmailTmpSendDTO emailTxtSingleSendDTO = new EmailTmpSendDTO();
            emailTxtSingleSendDTO.setTemplateCode("JW_POST_135");
            Map<String, Object> params = Maps.newHashMap();
            params.put("code", dbSupplier.getSupplierCode());
            params.put("name", dbSupplier.getSupplierName());
            emailTxtSingleSendDTO.setParams(params);
            final SupplierInvitaion one = supplierInvitaionService.getOne(
                    new LambdaQueryWrapper<>(SupplierInvitaion.class).eq(SupplierInvitaion::getSupplierId,
                            dbSupplier.getId()), false);
            final String recommender = one.getRecommender();
            final UserDTO byAccount = userClient.getByAccount(recommender);
            final String email = byAccount.getEmail();
            List<String> receiver = Lists.newArrayList(email);
            emailTxtSingleSendDTO.setReceiver(receiver);
            emailTxtSingleSendDTO.setSender(LoginUtil.getUserId());
            emailSendClient.async(emailTxtSingleSendDTO);
        }
    }

    private void extracted(Long changeVersionId) {
        //删除附件
        supplierChangeAttachmentService.remove(
                new LambdaQueryWrapper<SupplierChangeAttachment>().eq(SupplierChangeAttachment::getChangeVersionId,
                        changeVersionId));
        //供应商版本表
        supplierVersionService.remove(
                new LambdaQueryWrapper<SupplierVersion>().eq(SupplierVersion::getChangeVersionId, changeVersionId));
        //删除银行
        supplierBankVersionService.remove(
                new LambdaQueryWrapper<SupplierBankVersion>().eq(SupplierBankVersion::getChangeVersionId,
                        changeVersionId));
        //删除联系人
        supplierContactsVersionService.remove(
                new LambdaQueryWrapper<SupplierContactsVersion>().eq(SupplierContactsVersion::getChangeVersionId,
                        changeVersionId));
        //删除资质
        supplierPurchaseCategoryVersionService.remove(new LambdaQueryWrapper<SupplierPurchaseCategoryVersion>().eq(
                SupplierPurchaseCategoryVersion::getChangeVersionId, changeVersionId));
        //删除供应商品类
        supplierQualificationChangeItemService.remove(new LambdaQueryWrapper<SupplierQualificationChangeItem>().eq(
                SupplierQualificationChangeItem::getVersionChangeId, changeVersionId));
    }

    //将变更信息及初始供应商信息全部保存
    public void saveAllInfo(SupplierChangeSaveDTO supplierChangeSaveDTO, Map<String, Object> tmpMap,
                            Map<String, String> fieldNamTitleMap, Long supplierId, Long changeVersionId,
                            boolean changeFlag)
    {
        Long changeVersionOldId = supplierChangeSaveDTO.getChangeVersionId();

        //保存供应商全部数据
        List<SupplierExtensionVersion> supplierExtensions = new ArrayList<>();
        if (CollUtil.isNotEmpty(tmpMap)) {
            for (String key : tmpMap.keySet()) {
                //这个地方的字段是供应商主表中
                SupplierExtensionVersion supplierExtension = new SupplierExtensionVersion();
                supplierExtension.setExtensionKey(key);
                final String label = fieldNamTitleMap.get(key);
                supplierExtension.setChangeVersionId(changeVersionId);
                supplierExtension.setExtensionLabel(label);
                supplierExtension.setExtensionValue(tmpMap.get(key).toString());
                supplierExtension.setSupplierId(supplierId);
                supplierExtensions.add(supplierExtension);
            }
        }
        if (CollUtil.isNotEmpty(supplierExtensions)) {
            supplierExtensionVersionService.remove(
                    new LambdaQueryWrapper<SupplierExtensionVersion>().eq(SupplierExtensionVersion::getSupplierId,
                            supplierId));
            supplierExtensionVersionService.saveBatch(supplierExtensions);
        }
        //供应商联系人数据保存全量
        List<SupplierContactsDTO> contactsList = supplierChangeSaveDTO.getContactsList();
        List<SupplierContactsVersionWhole> versionWholes = supplierChangeVersionConvert.dtos2WholeEntities(
                contactsList);
        for (SupplierContactsVersionWhole supplierContactsWhole : versionWholes) {
            final Long masterId;
            if (Objects.nonNull(supplierContactsWhole.getMasterId())) {
                masterId = supplierContactsWhole.getMasterId();
            } else {
                masterId = supplierContactsWhole.getId();
            }
            supplierContactsWhole.setMasterId(masterId);
            supplierContactsWhole.setSupplierId(supplierId);
            supplierContactsWhole.setChangeVersionId(changeVersionId);
            supplierContactsWhole.setId(IdWorker.getId());
        }
        if (CollUtil.isNotEmpty(versionWholes)) {
            supplierContactsVersionWholeService.remove(new LambdaQueryWrapper<SupplierContactsVersionWhole>().eq(
                    SupplierContactsVersionWhole::getSupplierId, supplierId));
            supplierContactsVersionWholeService.saveBatch(versionWholes);
        }

        //============================================
        //供应商银行数据保存全量
        //这个地方需要注意，把如果有id放到masterId里面
        List<SupplierBankDTO> bankList = supplierChangeSaveDTO.getBankList();
        List<SupplierBankVersionWhole> bankVersionWholeList = supplierBankVersionWholeConvert.dtos2Entities(bankList);
        for (SupplierBankVersionWhole bankVersionWhole : bankVersionWholeList) {
            final Long masterId;
            if (Objects.nonNull(bankVersionWhole.getMasterId())) {
                masterId = bankVersionWhole.getMasterId();
            } else {
                masterId = bankVersionWhole.getId();
            }
            bankVersionWhole.setMasterId(masterId);
            bankVersionWhole.setSupplierId(supplierId);
            bankVersionWhole.setChangeVersionId(changeVersionId);
            bankVersionWhole.setId(IdWorker.getId());
        }
        if (CollUtil.isNotEmpty(bankVersionWholeList)) {
            supplierBankVersionWholeService.remove(
                    new LambdaQueryWrapper<SupplierBankVersionWhole>().eq(SupplierBankVersionWhole::getSupplierId,
                            supplierId));
            supplierBankVersionWholeService.saveBatch(bankVersionWholeList);
        }

        //===========================================
        //供应商品类全量保存表
        //供应商品类
        final List<SupplierPurchaseCategoryBaseDTO> categoryList =
                supplierChangeSaveDTO.getSupplierPurchaseCategoryList();
        if (CollUtil.isNotEmpty(categoryList)) {
            //这个地方需要注意，把如果有id放到masterId里面
            final List<SupplierPurchaseCategoryVersionWhole> purchaseCategoryVersions =
                    supplierPurchaseCategoryVersionWholeConvert.dtos2Entities(
                            categoryList);
            //需要根据品类、税率、币种、付款条件、公司、组织、付款方式判断啊采购品类的唯一性
            final Map<String, String> stringStringMap = purchaseCategoryVersions.stream().collect(
                    Collectors.toMap(
                            category -> {
                                final String format = StrUtil.format("{}-{}-{}-{}-{}-{}-{}",
                                        category.getPurchaseCategoryCode(),
                                        category.getTaxCode(),
                                        category.getCurrencyCode(),
                                        category.getPaymentTerms(),
                                        category.getCompanyCode(),
                                        category.getPurchaseOrgCode(),
                                        category.getPaymentMethod()
                                );
                                return format;
                            },
                            SupplierPurchaseCategoryVersionWhole::getPurchaseCategoryName,
                            (existing, replacement) -> existing));
            //校验
            Map<String, Long> codeCountMap = purchaseCategoryVersions.stream()
                    .collect(Collectors.groupingBy(
                            category -> {
                                final String format = StrUtil.format("{}-{}-{}-{}-{}-{}-{}",
                                        category.getPurchaseCategoryCode(),
                                        category.getTaxCode(),
                                        category.getCurrencyCode(),
                                        category.getPaymentTerms(),
                                        category.getCompanyCode(),
                                        category.getPurchaseOrgCode(),
                                        category.getPaymentMethod()
                                );
                                return format;
                            },
                            Collectors.counting()
                    ));

            boolean hasDuplicates = codeCountMap.values().stream().anyMatch(a -> a > 1);
            if (hasDuplicates) {
                Set<String> tipMsg = Sets.newHashSet();
                codeCountMap.entrySet().stream()
                        .filter(entry -> entry.getValue() > 1)
                        .forEach(entry -> tipMsg.add(stringStringMap.get(entry.getKey())));
                throw new DaoException(String.join(",", tipMsg) + "出现重复");
            }
            //需要把type是null过滤掉
            for (SupplierPurchaseCategoryVersionWhole categoryVersion : purchaseCategoryVersions) {
                final Long masterId;
                if (Objects.nonNull(categoryVersion.getMasterId())) {
                    masterId = categoryVersion.getMasterId();
                } else {
                    masterId = categoryVersion.getId();
                }
                categoryVersion.setMasterId(masterId);
                categoryVersion.setSupplierId(supplierId);
                categoryVersion.setChangeVersionId(changeVersionId);
                categoryVersion.setId(IdWorker.getId());
            }
            if (CollUtil.isNotEmpty(purchaseCategoryVersions)) {
                supplierPurchaseCategoryVersionWholeService.remove(
                        new LambdaQueryWrapper<SupplierPurchaseCategoryVersionWhole>().eq(
                                SupplierPurchaseCategoryVersionWhole::getSupplierId, supplierId));
                supplierPurchaseCategoryVersionWholeService.saveBatch(purchaseCategoryVersions);
            }
        }
        //=================================================
        //资质文件全量保存
        //需要处理资质变更数据
        final List<SupplierQualificationChangeDTO> supplierQualificationsList =
                supplierChangeSaveDTO.getSupplierQualificationsList();
        //需要处理数据
        List<SupplierQualificationChangeItemWhole> supplierQualificationChanges = Lists.newArrayList();
        for (SupplierQualificationChangeDTO changeDTO : supplierQualificationsList) {
            SupplierQualificationChangeItemWhole qualificationChangeItem = new SupplierQualificationChangeItemWhole();
            qualificationChangeItem.setVersionChangeId(changeVersionId);
            Long id;
            if (changeFlag) {
                id = changeDTO.getQualificationId();
            } else {
                id = changeDTO.getId();
            }
            qualificationChangeItem.setQualificationId(id);
            qualificationChangeItem.setQualificationNumber(changeDTO.getQualificationNumber());
            qualificationChangeItem.setAvailableStartDate(changeDTO.getAvailableStartDate());
            qualificationChangeItem.setAvailableEndDate(changeDTO.getAvailableEndDate());
            qualificationChangeItem.setFileId(changeDTO.getFileId());
            qualificationChangeItem.setQualificationCode(changeDTO.getQualificationCode());
            qualificationChangeItem.setQualificationName(changeDTO.getQualificationName());
            qualificationChangeItem.setNewQualificationNumber(changeDTO.getQualificationNumber());
            qualificationChangeItem.setQualificationNumber(changeDTO.getQualificationNumber());
            qualificationChangeItem.setNewFileId(changeDTO.getFileId());
            qualificationChangeItem.setNewAvailableEndDate(changeDTO.getAvailableEndDate());
            qualificationChangeItem.setNewAvailableStartDate(changeDTO.getAvailableStartDate());
            qualificationChangeItem.setSupplierId(supplierId);
            qualificationChangeItem.setChangeId(changeVersionId);
            supplierQualificationChanges.add(qualificationChangeItem);
        }
        if (CollUtil.isNotEmpty(supplierQualificationChanges)) {
            supplierQualificationChangeItemWholeService.remove(
                    new LambdaQueryWrapper<SupplierQualificationChangeItemWhole>().eq(
                            SupplierQualificationChangeItemWhole::getSupplierId, supplierId));
            supplierQualificationChangeItemWholeService.saveBatch(supplierQualificationChanges);
        }
        //附件全部保存
        //保存附件信息
        final List<SupplierChangeAttachmentBaseDTO> files = supplierChangeSaveDTO.getFiles();
        List<SupplierChangeAttachmentWhole> supplierChangeAttachments =
                supplierChangeAttachmentWholeConvert.dtos2Entities(
                        files);
        for (SupplierChangeAttachmentWhole supplierChangeAttachment : supplierChangeAttachments) {
            supplierChangeAttachment.setChangeVersionId(changeVersionId);
            supplierChangeAttachment.setSupplierId(supplierId);
        }
        if (CollUtil.isNotEmpty(supplierChangeAttachments)) {
            supplierChangeAttachmentWholeService.remove(new LambdaQueryWrapper<SupplierChangeAttachmentWhole>().eq(
                    SupplierChangeAttachmentWhole::getSupplierId, supplierId));
            supplierChangeAttachmentWholeService.saveBatch(supplierChangeAttachments);
        }
    }


    @Override
    public SupplierChangeVersionBaseDTO getDetail(Long id) {
        final SupplierChangeVersion changeVersion = supplierChangeVersionService.getById(id);
        if (Objects.nonNull(changeVersion)) {
            return supplierChangeVersionConvert.entity2Dtos(changeVersion);
        }
        return new SupplierChangeVersionBaseDTO();
    }

    @Override
    public PageView getSupplierVersionList(SupplierChangeQuery query) {
        final LambdaQueryWrapper<SupplierVersion> queryWrapper = new LambdaQueryWrapper<SupplierVersion>().eq(
                SupplierVersion::getChangeVersionId, query.getChangeVersionId());
        final List<SupplierVersion> list = supplierVersionService.list(queryWrapper);
        List<SupplierVersionBaseDTO> baseDTOList = supplierVersionConvert.entities2Dtos(list);
        return PageUtil.getPV(baseDTOList, baseDTOList.size());
    }

    @Override
    public PageView getSupplierBankVersionList(SupplierChangeQuery query) {
        List<SupplierBankVersionComparePO> supplierBankVersionComparePOS = supplierBankVersionService.findForCompare(
                query);
        List<SupplierBankVersionCompareDTO> supplierBankVersionCompareDTOS = supplierBankVersionConvert.pos2Dtos(
                supplierBankVersionComparePOS);
        return PageUtil.getPV(supplierBankVersionCompareDTOS, supplierBankVersionCompareDTOS.size());
    }

    @Override
    public PageView getSupplierBankVersionWholeList(SupplierChangeQuery query) {
        List<SupplierBankVersionComparePO> supplierBankVersionComparePOS =
                supplierBankVersionWholeService.findForCompare(
                        query);
        List<SupplierBankVersionCompareDTO> supplierBankVersionCompareDTOS = supplierBankVersionWholeConvert.pos2Dtos(
                supplierBankVersionComparePOS);
        return PageUtil.getPV(supplierBankVersionCompareDTOS, supplierBankVersionCompareDTOS.size());
    }

    @Override
    public PageView getSupplierContactsVersionList(SupplierChangeQuery query) {
        List<SupplierContactsVersionComparePO> supplierContactsVersionComparePOS =
                supplierContactsVersionService.findForCompare(query);
        List<SupplierContactsVersionCompareDTO> versionCompareDTOS = supplierContactsVersionConvert.pos2Dtos(
                supplierContactsVersionComparePOS);
        return PageUtil.getPV(versionCompareDTOS, versionCompareDTOS.size());
    }

    @Override
    public PageView getSupplierContactsVersionWholeList(SupplierChangeQuery query) {
        List<SupplierContactsVersionComparePO> supplierContactsVersionComparePOS =
                supplierContactsVersionWholeService.findForCompare(query);
        List<SupplierContactsVersionCompareDTO> versionCompareDTOS = supplierContactsVersionWholeConvert.pos2Dtos(
                supplierContactsVersionComparePOS);
        return PageUtil.getPV(versionCompareDTOS, versionCompareDTOS.size());
    }

    @Override
    public PageView getSupplierPurchaseCategoryVersionList(SupplierChangeQuery query) {
        List<SupplierPurchaseCategoryVersionComparePO> categoryVersionComparePOS =
                supplierPurchaseCategoryVersionService.findForCompare(query);
        List<SupplierPurchaseCategoryVersionCompareDTO> categoryVersionCompareDTOS =
                supplierPurchaseCategoryVersionConvert.pos2Dtos(
                        categoryVersionComparePOS);
        return PageUtil.getPV(categoryVersionCompareDTOS, categoryVersionCompareDTOS.size());
    }

    @Override
    public PageView getSupplierPurchaseCategoryVersionWholeList(SupplierChangeQuery query) {
        List<SupplierPurchaseCategoryVersionComparePO> categoryVersionComparePOS =
                supplierPurchaseCategoryVersionWholeService.findForCompare(query);
        List<SupplierPurchaseCategoryVersionCompareDTO> categoryVersionCompareDTOS =
                supplierPurchaseCategoryVersionWholeConvert.pos2Dtos(
                        categoryVersionComparePOS);
        return PageUtil.getPV(categoryVersionCompareDTOS, categoryVersionCompareDTOS.size());
    }

    @Override
    public PageView getAttachmentList(SupplierChangeQuery query) {
        Page<SupplierChangeAttachment> page = PageUtil.toPage(query);
        final List<SupplierChangeAttachment> list = supplierChangeAttachmentService.list(page,
                new LambdaQueryWrapper<SupplierChangeAttachment>().eq(SupplierChangeAttachment::getChangeVersionId,
                        query.getChangeVersionId()));
        List<SupplierChangeAttachmentBaseDTO> dtos = supplierChangeAttachmentConvert.entities2Dtos(list);
        final List<Long> fileIds = dtos.stream().filter(a -> Objects.nonNull(a.getFileId()))
                .map(SupplierChangeAttachmentBaseDTO::getFileId).collect(Collectors.toList());
        Map<Long, String> fileMaps = Maps.newHashMap();
        if (CollUtil.isNotEmpty(fileIds)) {
            final List<FileResposeCDTO> fileInfos = fileClient.getFileInfos(fileIds);
            fileMaps = fileInfos.stream().collect(Collectors.toMap(a -> a.getId(), a -> a.getFileName()));
        }

        for (SupplierChangeAttachmentBaseDTO dto : dtos) {
            if (Objects.nonNull(dto.getFileId())) {
                dto.setFileName(fileMaps.get(dto.getFileId()));
            }
        }
        return PageUtil.getPV(dtos, page.getTotal());
    }

    @Override
    public PageView getAttachmentWholeList(SupplierChangeQuery query) {
        Page<SupplierChangeAttachmentWhole> page = PageUtil.toPage(query);
        final List<SupplierChangeAttachmentWhole> list = supplierChangeAttachmentWholeService.list(page,
                new LambdaQueryWrapper<SupplierChangeAttachmentWhole>().eq(
                        SupplierChangeAttachmentWhole::getChangeVersionId,
                        query.getChangeVersionId()));
        List<SupplierChangeAttachmentBaseDTO> dtos = supplierChangeAttachmentWholeConvert.entities2Dtos(list);
        final List<Long> fileIds = dtos.stream().filter(a -> Objects.nonNull(a.getFileId()))
                .map(SupplierChangeAttachmentBaseDTO::getFileId).collect(Collectors.toList());
        Map<Long, String> fileMaps = Maps.newHashMap();
        if (CollUtil.isNotEmpty(fileIds)) {
            final List<FileResposeCDTO> fileInfos = fileClient.getFileInfos(fileIds);
            fileMaps = fileInfos.stream().collect(Collectors.toMap(a -> a.getId(), a -> a.getFileName()));
        }

        for (SupplierChangeAttachmentBaseDTO dto : dtos) {
            if (Objects.nonNull(dto.getFileId())) {
                dto.setFileName(fileMaps.get(dto.getFileId()));
            }
        }
        return PageUtil.getPV(dtos, page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examine(ChangeExamineParamDTO paramDTO) {
        final SupplierChangeVersion changeVersion = supplierChangeVersionService.getById(paramDTO.getId());
        changeVersion.setExamineState(paramDTO.getState());
        changeVersion.setExamineRemark(paramDTO.getRemark());
        changeVersion.setIsFreeze(paramDTO.getIsFreeze());
        changeVersion.setExamineUser(LoginUtil.getUserId());
        changeVersion.setEliminateFlag(paramDTO.getEliminateFlag());
        changeVersion.setExecutionTime(paramDTO.getExecutionTime());
        changeVersion.setPaymentTerms(paramDTO.getPaymentTerms());
        if (changeVersion.getExamineState() == SupplierChangeExamineState.PASS.getVal()) {
            changeVersion.setOaType(paramDTO.getOaType());
            //需要增加判断，如果供应商存在erp编码就需要推送oa
            final Long supplierId = changeVersion.getSupplierId();
            final Supplier supplier = supplierService.getById(supplierId);
            if (StrUtil.isNotEmpty(supplier.getSupplierErpCode())) {
                supplierToOaLogic.supplierChangeToOa(changeVersion);
            } else {
                oaExamine(changeVersion.getId(), SupplierChangeBpmState.PASS.getVal());
            }

        } else {
            changeVersion.setBpmState(SupplierChangeBpmState.TO_BE_SUBMITTED.getVal());
            supplierChangeVersionService.updateById(changeVersion);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void oaExamine(Long id, Integer state) {
        final SupplierChangeVersion changeVersion = supplierChangeVersionService.getById(id);
        changeVersion.setBpmState(state);
        supplierChangeVersionService.updateById(changeVersion);
        changeToMain(changeVersion, state);
    }

    @Override
    public PageView getSupplierQualificationVersionList(SupplierChangeQuery query) {
        final Long changeVersionId = query.getChangeVersionId();
        final List<SupplierQualificationChangeItem> changeItems = supplierQualificationChangeItemService.list(
                new LambdaQueryWrapper<SupplierQualificationChangeItem>().eq(
                        SupplierQualificationChangeItem::getVersionChangeId, changeVersionId));
        final List<SupplierQualificationChangeItemBaseDTO> supplierQualificationChangeItemBaseDTOS =
                qualificationChangeItemConvert.entities2BaseDtos(
                        changeItems);
        modelAggregationService.processRelationAggregation(supplierQualificationChangeItemBaseDTOS);
        return PageUtil.getPV(supplierQualificationChangeItemBaseDTOS, supplierQualificationChangeItemBaseDTOS.size());
    }

    @Override
    public PageView getSupplierQualificationVersionWholeList(SupplierChangeQuery query) {
        final Long changeVersionId = query.getChangeVersionId();
        final List<SupplierQualificationChangeItemWhole> changeItems = supplierQualificationChangeItemWholeService.list(
                new LambdaQueryWrapper<SupplierQualificationChangeItemWhole>().eq(
                        SupplierQualificationChangeItemWhole::getVersionChangeId, changeVersionId));
        final List<SupplierQualificationChangeItemBaseDTO> supplierQualificationChangeItemBaseDTOS =
                supplierQualificationChangeItemWholeConvert.entities2BaseDtos(
                        changeItems);
        for (SupplierQualificationChangeItemBaseDTO supplierQualificationChangeItemBaseDTO :
                supplierQualificationChangeItemBaseDTOS) {
            supplierQualificationChangeItemBaseDTO.setQualificationNumber(
                    supplierQualificationChangeItemBaseDTO.getNewQualificationNumber());
            supplierQualificationChangeItemBaseDTO.setFileId(supplierQualificationChangeItemBaseDTO.getNewFileId());
            supplierQualificationChangeItemBaseDTO.setAvailableEndDate(
                    supplierQualificationChangeItemBaseDTO.getNewAvailableEndDate());
            supplierQualificationChangeItemBaseDTO.setAvailableStartDate(
                    supplierQualificationChangeItemBaseDTO.getNewAvailableStartDate());
            supplierQualificationChangeItemBaseDTO.setFileName(supplierQualificationChangeItemBaseDTO.getNewFileName());
        }
        modelAggregationService.processRelationAggregation(supplierQualificationChangeItemBaseDTOS);
        return PageUtil.getPV(supplierQualificationChangeItemBaseDTOS, supplierQualificationChangeItemBaseDTOS.size());
    }

    @Override
    public List<SupplierChangeVersion> findExportListAll(SupplierChangeQuery supplierChangeQuery) {


        //需要单独查询分页总数
        supplierChangeQuery.setRows(1);
        supplierChangeQuery.setPage(1);
        Page<SupplierChangeVersion> page = PageUtil.toPage(supplierChangeQuery);
        final List<SupplierChangeVersion> list = supplierChangeVersionService.findList(page, supplierChangeQuery);

        if (page.getTotal() > sysProp.getExportMaxCount()) {
            throw new DaoException(StrUtil.format("导出数据超过{}条", sysProp.getExportMaxCount()));
        }
        List<SupplierChangeVersion> changeVersions = supplierChangeVersionService.findExportListAll(supplierChangeQuery);
        return changeVersions;
    }

    @Override
    public void remove(Long id) {
        supplierChangeVersionService.remove(
                new LambdaQueryWrapper<SupplierChangeVersion>().eq(SupplierChangeVersion::getId,
                        id));
        extracted(id);
    }

    private void changeToMain(SupplierChangeVersion changeVersion, Integer state) {
        final Long id = changeVersion.getId();
        final Long supplierId = changeVersion.getSupplierId();
        final Supplier supplier = supplierService.getById(supplierId);
        final String supplierCode = supplier.getSupplierCode();
        final SupplierChangeBpmState supplierChangeBpmState = SupplierChangeBpmState.valueOf(state);
        switch (supplierChangeBpmState) {
            case PASS:
                final Integer isFreeze = changeVersion.getIsFreeze();
                if (Objects.nonNull(isFreeze)) {
                    LambdaUpdateWrapper<Supplier> supplierLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    supplierLambdaUpdateWrapper.eq(Supplier::getId, supplierId).set(Supplier::getIsFreeze, isFreeze);
                    if(changeVersion.getEliminateFlag() != null){
                        //20241011增加待淘汰更新标识
                        supplierLambdaUpdateWrapper.set(Supplier::getEliminateFlag,changeVersion.getEliminateFlag());
                    }
                    //需要更新冻结标识
                    supplierService.update(supplierLambdaUpdateWrapper);
                    //禁用该供应商下的主、副账号
                    if(isFreeze.equals(1)){
                        userClient.updateStatusBySupplier(supplierId, 1);
                    }
                }
                //联系人
                final List<SupplierContactsVersion> contactsVersionList = supplierContactsVersionService.list(
                        new LambdaQueryWrapper<SupplierContactsVersion>().eq(
                                SupplierContactsVersion::getChangeVersionId, id));
                if (CollUtil.isNotEmpty(contactsVersionList)) {
                    final List<SupplierContacts> contactListUpdate = Lists.newArrayList();
                    final List<Long> idDelete = Lists.newArrayList();
                    contactsVersionList.forEach(e -> {
                        if (Objects.nonNull(e.getType())) {
                            final VersionChangeType versionChangeType = VersionChangeType.forEach(e.getType());
                            switch (versionChangeType) {
                                case CREATE:
                                    final SupplierContacts contactsInsert = new SupplierContacts();
                                    contactsInsert.setSupplierId(supplierId);
                                    contactsInsert.setSupplierCode(supplierCode);
                                    contactsInsert.setContactsType(e.getContactsType());
                                    contactsInsert.setContactsName(e.getContactsName());
                                    contactsInsert.setContactsType(e.getContactsType());
                                    contactsInsert.setContactsMobile(e.getContactsMobile());
                                    contactsInsert.setContactsTel(e.getContactsTel());
                                    contactsInsert.setTax(e.getTax());
                                    contactsInsert.setEmail(e.getEmail());
                                    contactsInsert.setIdCard(e.getIdCard());
                                    supplierContactsService.save(contactsInsert);
                                    final SupplierContactsVersion contactsVersionUpdate = new SupplierContactsVersion();
                                    contactsVersionUpdate.setId(e.getId());
                                    contactsVersionUpdate.setMasterId(contactsInsert.getId().longValue());
                                    supplierContactsVersionService.updateById(contactsVersionUpdate);
                                    break;
                                case EDIT:
                                    final SupplierContacts contacts = new SupplierContacts();
                                    contacts.setId(e.getMasterId().intValue());
                                    contacts.setSupplierId(supplierId);
                                    contacts.setSupplierCode(supplierCode);
                                    contacts.setContactsType(e.getContactsType());
                                    contacts.setContactsName(e.getContactsName());
                                    contacts.setContactsType(e.getContactsType());
                                    contacts.setContactsMobile(e.getContactsMobile());
                                    contacts.setContactsTel(e.getContactsTel());
                                    contacts.setTax(e.getTax());
                                    contacts.setEmail(e.getEmail());
                                    contacts.setIdCard(e.getIdCard());
                                    contactListUpdate.add(contacts);
                                    break;
                                case DEL:
                                    idDelete.add(e.getMasterId());
                                    break;
                            }
                        }
                    });
                    if (CollUtil.isNotEmpty(idDelete)) {
                        supplierContactsService.removeBatchByIds(idDelete);
                    }
                    if (CollUtil.isNotEmpty(contactListUpdate)) {
                        supplierContactsService.saveOrUpdateBatch(contactListUpdate);
                    }

                }


                /**
                 * 银行信息
                 */
                final List<SupplierBankVersion> supplierBankVersionList = supplierBankVersionService.list(
                        new LambdaQueryWrapper<SupplierBankVersion>().eq(SupplierBankVersion::getChangeVersionId, id));
                if (CollUtil.isNotEmpty(supplierBankVersionList)) {
                    supplierBankVersionList.forEach(e -> {
                        if (Objects.nonNull(e.getType())) {
                            final VersionChangeType versionChangeType = VersionChangeType.forEach(e.getType());
                            switch (versionChangeType) {
                                case CREATE:
                                    final SupplierBank insert = new SupplierBank();
                                    insert.setSupplierId(supplierId);
                                    insert.setOpeningBankName(e.getOpeningBankName());
                                    insert.setCardholderName(e.getCardholderName());
                                    insert.setBankAccount(e.getBankAccount());
                                    insert.setBankCode(e.getBankCode());
                                    insert.setBankAddress(e.getBankAddress());
                                    insert.setCompanyCode(e.getCompanyCode());
                                    insert.setCompanyName(e.getCompanyName());
                                    insert.setBankInterCode(e.getBankInterCode());
                                    supplierBankService.save(insert);
                                    e.setMasterId(insert.getId());
                                    supplierBankVersionService.updateById(e);
                                    break;

                                case EDIT:
                                    final SupplierBank update = new SupplierBank();
                                    update.setId(e.getMasterId());
                                    update.setSupplierId(supplierId);
                                    update.setOpeningBankName(e.getOpeningBankName());
                                    update.setCardholderName(e.getCardholderName());
                                    update.setBankAccount(e.getBankAccount());
                                    update.setBankCode(e.getBankCode());
                                    update.setBankAddress(e.getBankAddress());
                                    update.setBankInterCode(e.getBankInterCode());
                                    update.setCompanyCode(e.getCompanyCode());
                                    update.setCompanyName(e.getCompanyName());
                                    supplierBankService.updateById(update);
                                    break;
                                case DEL:
                                    supplierBankService.removeById(e.getMasterId());
                                    break;
                            }
                        }
                    });
                }
                /**
                 * 供应商品类信息
                 */
                final List<SupplierPurchaseCategoryVersion> supplierProductTypeVersionList =
                        supplierPurchaseCategoryVersionService.list(
                                new LambdaQueryWrapper<SupplierPurchaseCategoryVersion>().eq(
                                        SupplierPurchaseCategoryVersion::getChangeVersionId, id));
                if (CollUtil.isNotEmpty(supplierProductTypeVersionList)) {
                    supplierProductTypeVersionList.stream().forEach(e -> {
                        if (Objects.nonNull(e.getType())) {
                            final VersionChangeType versionChangeType = VersionChangeType.forEach(e.getType());
                            switch (versionChangeType) {
                                case CREATE:
                                    final SupplierPurchaseCategory insert = new SupplierPurchaseCategory();
                                    insert.setSupplierId(supplierId);
                                    insert.setPurchaseCategoryCode(e.getPurchaseCategoryCode());
                                    insert.setPurchaseCategoryName(e.getPurchaseCategoryName());
                                    insert.setTaxCode(e.getTaxCode());
                                    insert.setCompanyCode(e.getCompanyCode());
                                    insert.setPaymentTerms(e.getPaymentTerms());
                                    insert.setPaymentMethod(e.getPaymentMethod());
                                    insert.setCurrencyCode(e.getCurrencyCode());
                                    insert.setCreateTime(LocalDateTime.now());
                                    insert.setControlSubject(e.getControlSubject());
                                    insert.setPurchaseOrgCode(e.getPurchaseOrgCode());
                                    insert.setIsFreeze(e.getIsFreeze());
                                    //这个地方需要获取当前供应商这个品类的现在状态，
                                    final SupplierPurchaseCategory exitsPG = supplierPurchaseCategoryService.getOne(
                                            new LambdaQueryWrapper<SupplierPurchaseCategory>().eq(
                                                            SupplierPurchaseCategory::getSupplierId, supplierId)
                                                    .eq(SupplierPurchaseCategory::getPurchaseCategoryCode,
                                                            e.getPurchaseCategoryCode()),false);
                                    if (Objects.nonNull(exitsPG)) {
                                        insert.setState(exitsPG.getState());
                                    } else {
                                        insert.setState(AuthenticationState.SMALL_BATCH.getState());
                                    }
                                    insert.setAcceptanceMethod(e.getAcceptanceMethod());
                                    if (Objects.nonNull(e.getEffectiveTime())) {
                                        insert.setEffectiveTime(e.getEffectiveTime());
                                    }
                                    supplierPurchaseCategoryService.save(insert);
                                    e.setMasterId(insert.getId());
                                    supplierPurchaseCategoryVersionService.updateById(e);
                                    break;
                                case EDIT:
                                    final SupplierPurchaseCategory update = new SupplierPurchaseCategory();
                                    update.setId(e.getMasterId());
                                    update.setTaxCode(e.getTaxCode());
                                    update.setCompanyCode(e.getCompanyCode());
                                    update.setPaymentTerms(e.getPaymentTerms());
                                    update.setPaymentMethod(e.getPaymentMethod());
                                    update.setCurrencyCode(e.getCurrencyCode());
                                    update.setControlSubject(e.getControlSubject());
                                    update.setIsFreeze(e.getIsFreeze());
                                    update.setPurchaseOrgCode(e.getPurchaseOrgCode());
                                    update.setAcceptanceMethod(e.getAcceptanceMethod());
                                    if (Objects.nonNull(e.getEffectiveTime())) {
                                        update.setEffectiveTime(e.getEffectiveTime());
                                    }
                                    supplierPurchaseCategoryService.updateById(update);
                                    break;
                            }
                        }
                    });
                }
                changeVersion.setBpmState(SupplierChangeBpmState.PASS.getVal()); // 审批通过
                //需要把供应商的主表字段更新
                final List<SupplierVersion> list = supplierVersionService.list(
                        new LambdaQueryWrapper<SupplierVersion>().eq(SupplierVersion::getChangeVersionId, id));
                //供应商资质
                final List<SupplierQualificationChangeItem> changeItems = supplierQualificationChangeItemService.list(
                        new LambdaQueryWrapper<SupplierQualificationChangeItem>().eq(
                                SupplierQualificationChangeItem::getVersionChangeId, changeVersion.getId()));
                List<SupplierQualification> qualifications = Lists.newArrayList();
                for (SupplierQualificationChangeItem changeItem : changeItems) {
                    final Long qualificationId = changeItem.getQualificationId();
                    SupplierQualification tmp = new SupplierQualification();
                    if (Objects.nonNull(qualificationId)) {
                        tmp.setId(qualificationId);
                        tmp.setUpdateTime(LocalDateTime.now());
                    } else {
                        tmp.setSupplierId(supplierId);
                        tmp.setCreateTime(LocalDateTime.now());
                        tmp.setQualificationName(changeItem.getQualificationName());
                        tmp.setQualificationCode(changeItem.getQualificationCode());
                    }
                    if (StrUtil.isNotEmpty(changeItem.getNewQualificationNumber())) {
                        tmp.setQualificationNumber(changeItem.getNewQualificationNumber());
                    }
                    if (StrUtil.isNotEmpty(changeItem.getNewAvailableStartDate())) {
                        tmp.setAvailableStartDate(changeItem.getNewAvailableStartDate());
                    }
                    if (StrUtil.isNotEmpty(changeItem.getNewAvailableEndDate())) {
                        tmp.setAvailableEndDate(changeItem.getNewAvailableEndDate());
                    }
                    if (Objects.nonNull(changeItem.getNewFileId())) {
                        tmp.setFileId(changeItem.getNewFileId());
                    }
                    qualifications.add(tmp);
                }
                if (CollUtil.isNotEmpty(qualifications)) {
                    supplierQualificationService.saveOrUpdateBatch(qualifications);
                }
                Map<String, String> supplierMap = Maps.newHashMap();
                Map<String, String> supplierExtensionMap = Maps.newHashMap();
                List<String> fieldCodes = Lists.newArrayList();
                //需要去取t_supplier的字段信息
                String supplierName = "";
                List<String> tableColumns = supplierService.getTableStruct();
                for (SupplierVersion e : list) {
                    //需要把数据转成Supplier对象
                    if (tableColumns.contains(StrUtil.toUnderlineCase(e.getField()))) {
                        supplierMap.put(e.getField(), e.getValue());
                    } else {
                        fieldCodes.add(e.getField());
                        supplierExtensionMap.put(e.getField(), e.getValue());
                    }
                    /**
                     * 变更的时候要检查供应商名称、简称、税号 不能更新成空，且不能重复
                     */
                    if (e.getField().equals("shortName")) {
                        if (StringUtils.isEmpty(e.getValue())) {
                            throw new DaoException("供应商简称不可以为空");
                        } else {
                            final long count = supplierService.count(
                                    new LambdaQueryWrapper<Supplier>().ne(Supplier::getId, supplierId)
                                            .eq(Supplier::getShortName, e.getValue()));
                            if (count > 0) {
                                throw new DaoException("供应商简称重复!");
                            }
                        }
                    }
                    if ("taxNo".equals(e.getField())) {
                        if (StringUtils.isEmpty(e.getValue())) {
                            throw new DaoException("供应商税号不可以为空");
                        } else {
                            final long count = supplierService.count(
                                    new LambdaQueryWrapper<Supplier>().ne(Supplier::getId, supplierId)
                                            .eq(Supplier::getTaxNo, e.getValue()));
                            if (count > 0) {
                                throw new DaoException("供应商税号重复!");
                            }
                        }
                    }

                    if (e.getField().equals("supplierName")) {
                        if (StringUtils.isEmpty(e.getValue())) {
                            throw new DaoException("供应商名称不能为空");
                        } else {
                            supplierName = e.getValue();
                            final long count = supplierService.count(
                                    new LambdaQueryWrapper<Supplier>().ne(Supplier::getId, supplierId)
                                            .eq(Supplier::getSupplierName, e.getValue()));
                            if (count > 0) {
                                throw new DaoException("供应商名称重复!");
                            }
                        }
                    }
                    if ("creditNo".equals(e.getField())) {
                        if (StringUtils.isEmpty(e.getValue())) {
                            throw new DaoException("信用代码不能为空");
                        }
                        final long count = supplierService.count(
                                new LambdaQueryWrapper<Supplier>().ne(Supplier::getId, supplierId)
                                        .eq(Supplier::getCreditNo, e.getValue()));
                        if (count > 0) {
                            throw new DaoException("供应商信用代码重复!");
                        }
                    }
                }
                //需要把供应商扩展表中的字段更新
                if (CollUtil.isNotEmpty(fieldCodes)) {
                    final List<SupplierExtension> supplierExtensions = supplierExtensionService.list(
                            new LambdaQueryWrapper<SupplierExtension>().eq(SupplierExtension::getSupplierId, supplierId)
                                    .in(SupplierExtension::getExtensionKey, fieldCodes));
                    for (SupplierExtension supplierExtension : supplierExtensions) {
                        final String newVal = supplierExtensionMap.get(supplierExtension.getExtensionKey());
                        supplierExtension.setExtensionValue(newVal);
                    }
                    supplierExtensionService.updateBatchById(supplierExtensions);
                }
                if (CollUtil.isNotEmpty(supplierMap)) {
                    final UpdateWrapper<Supplier> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", supplierId);
                    for (String s : supplierMap.keySet()) {
                        //需要把驼峰转成数据字段
                        updateWrapper.set(StrUtil.toUnderlineCase(s), supplierMap.get(s));
                    }
                    supplierService.update(updateWrapper);
                }
                supplierChangeVersionService.update(
                        new LambdaUpdateWrapper<SupplierChangeVersion>().set(SupplierChangeVersion::getStatus,
                                        EnableStatus.ENABLE.getStatus())
                                .eq(SupplierChangeVersion::getId, changeVersion.getId()));
                //需要更新供应商的用户昵称
                if (StrUtil.isNotEmpty(supplierName)) {
                    userClient.updateSupplierName(supplierName, supplierId);
                }
                //更新变更审批主表
                changeVersion.setBpmRemark("审批通过");
                break;
            case REJECT:
                //驳回
                changeVersion.setBpmState(SupplierChangeBpmState.REJECT.getVal()); // 审批拒绝
                //更新变更审批主表
                changeVersion.setBpmRemark("审批不通过");
                if (changeVersion.getOptType() == 1) {//供应商发起
                    changeVersion.setExamineState(SupplierChangeExamineState.REJECT.getVal());
                }

                break;
            default:
                throw new DaoException("参数错误!");
        }

        supplierChangeVersionService.updateById(changeVersion);
    }

    private Map<String, String> getDbSupplierData(Long supplierId) {
        //需要查询供应商的
        //需要查询供应商的字段信息
        final Supplier supplier = supplierService.getById(supplierId);
        final Map<String, Object> stringObjectMap = BeanUtil.beanToMap(supplier, false, true);
        final List<SupplierExtension> supplierExtensions = supplierExtensionService.list(
                new LambdaQueryWrapper<SupplierExtension>().eq(SupplierExtension::getSupplierId, supplierId));
        for (SupplierExtension supplierExtension : supplierExtensions) {
            stringObjectMap.put(supplierExtension.getExtensionKey(), supplierExtension.getExtensionValue());
        }
        Map<String, String> stringMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
            String key = entry.getKey();
            String value = convertToString(entry.getValue());
            stringMap.put(key, value);
        }
        return stringMap;
    }

    public static String convertToString(Object value) {
        if (value instanceof String) {
            return (String) value;
        } else if (value instanceof Integer) {
            return String.valueOf((Integer) value);
        } else if (value instanceof Long) {
            return String.valueOf((Long) value);
        } else {
            // 可以根据需要处理其他类型的值转换，这里只处理了String、Integer和Long
            return null; // 或者抛出异常等
        }
    }

    private void firstChangeVersionSaveBack(Long supplierId) {
        final Supplier supplier = supplierService.getById(supplierId);
        //供应商第一次变更，给初始数据做一次拍照,版本设置 0
        final SupplierChangeVersion firstChangeVersion = new SupplierChangeVersion();
        firstChangeVersion.setSupplierId(supplierId);
        firstChangeVersion.setSupplierName(supplier.getSupplierName());
        firstChangeVersion.setSupplierCode(supplier.getSupplierCode());
        firstChangeVersion.setVersion(0);
        //设置状态完结
        firstChangeVersion.setExamineState(SupplierChangeExamineState.PASS.getVal());
        firstChangeVersion.setStatus(EnableStatus.ENABLE.getStatus());
        firstChangeVersion.setBpmState(SupplierChangeBpmState.PASS.getVal());
        supplierChangeVersionService.save(firstChangeVersion);
        final Long changeVersionId = firstChangeVersion.getId();
        final Map<String, String> stringObjectMap = getDbSupplierData(supplierId);
        final List<SupplierField> supplierFields = supplierFieldService.list(
                new LambdaQueryWrapper<SupplierField>().eq(SupplierField::getSupplierId, supplierId));
        List<SupplierVersion> insertLists = Lists.newArrayList();
        for (SupplierField supplierField : supplierFields) {
            final String fieldCode = StrUtil.toCamelCase(supplierField.getFieldCode());
            if (Objects.nonNull(stringObjectMap.get(fieldCode))) {
                String val = stringObjectMap.get(fieldCode);//需要进行
                SupplierVersion supplierVersion = new SupplierVersion();
                supplierVersion.setChangeVersionId(changeVersionId);
                supplierVersion.setSupplierId(supplierId);
                supplierVersion.setField(supplierField.getFieldCode());
                supplierVersion.setFieldText(supplierField.getFieldAlias());
                supplierVersion.setOriginal(val);
                insertLists.add(supplierVersion);
            }
        }
        if (CollUtil.isNotEmpty(insertLists)) {
            supplierVersionService.saveBatch(insertLists);
        }
        //供应商银行
        final List<SupplierBank> bankList = supplierBankService.list(
                new LambdaQueryWrapper<SupplierBank>().eq(SupplierBank::getSupplierId, supplierId));
        if (CollUtil.isNotEmpty(bankList)) {
            final List<SupplierBankVersion> bankVersionListUpdate = Lists.newArrayList();
            bankList.forEach(e -> {
                final SupplierBankVersion bankVersion = new SupplierBankVersion();
                bankVersion.setMasterId(e.getId());
                bankVersion.setChangeVersionId(changeVersionId);
                bankVersion.setSupplierId(supplierId);
                bankVersion.setBankCode(e.getBankCode());
                bankVersion.setOpeningBankName(e.getOpeningBankName());
                bankVersion.setBankAccount(e.getBankAccount());
                bankVersion.setCompanyName(e.getCompanyName());
                bankVersion.setBankAddress(e.getBankAddress());
                bankVersion.setBankCountryCode(e.getBankCountryCode());
                bankVersion.setRemark(e.getRemark());
                bankVersion.setType(VersionChangeType.INIT.getType());
                bankVersion.setBankAccountNumber(e.getBankAccountNumber());
                bankVersion.setCardholderName(e.getCardholderName());
                bankVersionListUpdate.add(bankVersion);
            });
            supplierBankVersionService.saveBatch(bankVersionListUpdate);
        }
        //供应商联系人
        final List<SupplierContacts> contactsList = supplierContactsService.list(
                new LambdaQueryWrapper<SupplierContacts>().eq(SupplierContacts::getSupplierId, supplierId));
        if (CollUtil.isNotEmpty(contactsList)) {
            final List<SupplierContactsVersion> contactsVersionList = contactsList.stream().map(e -> {
                final SupplierContactsVersion contactsVersion = new SupplierContactsVersion();
                contactsVersion.setMasterId(e.getId().longValue());
                contactsVersion.setChangeVersionId(changeVersionId);
                contactsVersion.setSupplierId(supplierId);
                contactsVersion.setContactsType(e.getContactsType());
                contactsVersion.setContactsName(e.getContactsName());
                contactsVersion.setContactsTel(e.getContactsTel());
                contactsVersion.setContactsMobile(e.getContactsMobile());
                contactsVersion.setEmail(e.getEmail());
                contactsVersion.setType(VersionChangeType.INIT.getType());
                contactsVersion.setIdCard(e.getIdCard());
                return contactsVersion;
            }).collect(Collectors.toList());
            supplierContactsVersionService.saveBatch(contactsVersionList);
        }
        //供应商品类
        final List<SupplierPurchaseCategory> supplierPurchaseCategories = supplierPurchaseCategoryService.list(
                new LambdaQueryWrapper<SupplierPurchaseCategory>().eq(SupplierPurchaseCategory::getSupplierId,
                        supplierId));
        if (CollUtil.isNotEmpty(supplierPurchaseCategories)) {
            List<SupplierPurchaseCategoryVersion> categoryVersionServiceVersion =
                    supplierPurchaseCategoryVersionConvert.toVersion(
                            supplierPurchaseCategories);
            for (SupplierPurchaseCategoryVersion supplierPurchaseCategoryVersion : categoryVersionServiceVersion) {
                supplierPurchaseCategoryVersion.setChangeVersionId(changeVersionId);
                final Long masterId = supplierPurchaseCategoryVersion.getId();
                supplierPurchaseCategoryVersion.setMasterId(masterId);
                supplierPurchaseCategoryVersion.setId(null);
                supplierPurchaseCategoryVersion.setType(VersionChangeType.INIT.getType());
                supplierPurchaseCategoryVersion.setSupplierId(supplierId);
            }
            supplierPurchaseCategoryVersionService.saveBatch(categoryVersionServiceVersion);
        }
        //需要把资质也要保存一份
        final List<SupplierQualification> list = supplierQualificationService.list(
                new LambdaQueryWrapper<SupplierQualification>()
                        .eq(SupplierQualification::getSupplierId, supplierId));
        List<SupplierQualificationChangeItem> supplierQualificationChangeItems =
                supplierQualificationConvert.toChangeEntities(
                        list);
        for (SupplierQualificationChangeItem supplierQualificationChangeItem : supplierQualificationChangeItems) {
            final Long masterId = supplierQualificationChangeItem.getId();
            supplierQualificationChangeItem.setQualificationId(masterId);
            supplierQualificationChangeItem.setId(null);
            supplierQualificationChangeItem.setVersionChangeId(changeVersionId);
        }
        if (CollUtil.isNotEmpty(supplierQualificationChangeItems)) {
            supplierQualificationChangeItemService.saveBatch(supplierQualificationChangeItems);
        }
    }

    private Integer getCurrentVersion(Long supplierId) {
        //查找版本号,查找最近的一条，在其基础上版本号 +1
        Integer version = 1;
        final SupplierChangeVersion maxVersion = supplierChangeVersionService.getOne(
                new LambdaQueryWrapper<SupplierChangeVersion>().eq(SupplierChangeVersion::getSupplierId, supplierId)
                        .orderBy(true, false, SupplierChangeVersion::getVersion), false);
        if (Objects.nonNull(maxVersion)) {
            version = maxVersion.getVersion() + 1;
        }
        return version;
    }

    private void validate(Long supplierId) {
        //需要验证是否存在正在审批中的变更记录

        final LambdaQueryWrapper<SupplierChangeVersion> queryWrapper =
                new LambdaQueryWrapper<SupplierChangeVersion>().eq(
                                SupplierChangeVersion::getSupplierId, supplierId)
                        .and(wr -> wr.eq(SupplierChangeVersion::getExamineState,
                                        SupplierChangeExamineState.APPROVALING.getVal()).or()
                                .eq(SupplierChangeVersion::getBpmState, SupplierChangeBpmState.APPROVALING.getVal()));
        final long count = supplierChangeVersionService.count(queryWrapper);
        if (count > 0) {
            throw new DaoException("已发起信息变更无法重复发起!");
        }
    }

}