package com.jwipc.supplier.logic.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.enums.SqlLike;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jwipc.aggregation.ModelAggregationService;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.SapResposeBody;
import com.jwipc.constant.DelFlag;
import com.jwipc.constant.DictCode;
import com.jwipc.constant.EnableStatus;
import com.jwipc.constant.FlagConst;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
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.SupplierQualificationLogic;
import com.jwipc.supplier.model.po.SupplierQualificationChangePO;
import com.jwipc.supplier.model.po.SupplierQualificationPO;
import com.jwipc.supplier.model.query.SupplierQualificationChangeQuery;
import com.jwipc.supplier.model.query.SupplierQualificationQuery;
import com.jwipc.supplier.model.query.SupplierQualificationSupplemntQuery;
import com.jwipc.supplier.service.*;
import com.jwipc.sys.client.EmailSendClient;
import com.jwipc.sys.client.SequenceClient;
import com.jwipc.sys.client.dto.EmailTmpSendDTO;
import com.jwipc.util.DateUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static com.jwipc.supplier.constant.SequenceConst.QUALIFICATIONS_CHANGE_NO;
import static com.jwipc.supplier.constant.SequenceConst.SUPPLIER_QUALIFICATION_SUPPLEMENT_CODE;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class SupplierQualificationLogicImpl implements SupplierQualificationLogic {
    private final IQualificationService qualificationService;
    private final SupplierQualificationConvert supplierQualificationConvert;
    private final ISupplierQualificationApplyService supplierQualificationApplyService;
    private final SupplierQualificationApplyConvert supplierQualificationApplyConvert;
    private final SequenceClient sequenceClient;
    private final ISupplierService supplierService;
    private final ISupplierQualificationApplySupplierService supplierQualificationApplySupplierService;
    private final SupplierQualificationApplySupplierConvert supplierQualificationApplySupplierConvert;
    private final ISupplierQualificationApplyDetailService supplierQualificationApplyDetailService;
    private final SupplierQualificationApplyDetailConvert supplierQualificationApplyDetailConvert;
    private final ISupplierQualificationService supplierQualificationService;
    private final ISupplierQualificationChangeService supplierQualificationChangeService;
    private final ISupplierQualificationChangeItemService supplierQualificationChangeItemService;
    private final SupplierQualificationChangeConvert supplierQualificationChangeConvert;
    private final SupplierQualificationChangeItemConvert supplierQualificationChangeItemConvert;
    private final ISupplierInvitaionService supplierInvitaionService;
    private final ISupplierTemplateService supplierTemplateService;
    private final IQualificationTemplateService qualificationTemplateService;
    private final IQualificationTemplateItemService qualificationTemplateItemService;
    private final ModelAggregationService modelAggregationService;
    private final ISupplierPurchaseCategoryService supplierPurchaseCategoryService;
    private final EmailSendClient emailSendClient;
    private final ISupplierContactsService supplierContactsService;
    private final ISupplierSqeScoreService supplierSqeScoreService;

    private final SupplierSapClient sapClient;


    @Override
    public PageView getApplyList(SupplierQualificationSupplemntQuery query) {
        //将这里的wrapper查询修改成mapper.xml的方式进行查询
        final Page<SupplierQualificationApply> page = PageUtil.toPage(query);
        if (!LoginUtil.getAccount().equals("admin")) {
            query.setUserId(LoginUtil.getUserId());
        }
        List<SupplierQualificationApply> supplierQualificationApplies = supplierQualificationApplyService.findList(page,
                query);

        List<SupplierQualificationApplyBaseDTO> supplierQualificationApplyBaseDTOS =
                supplierQualificationApplyConvert.entities2Dtos(
                        supplierQualificationApplies);
        modelAggregationService.processRelationAggregation(supplierQualificationApplyBaseDTOS);
        return PageUtil.getPV(supplierQualificationApplyBaseDTOS, page.getTotal());
    }

    @Override
    public SupplierQualificationApplyBaseDTO getApplyDetail(Long id) {
        final SupplierQualificationApply supplierQualificationApply = supplierQualificationApplyService.getById(id);
        if (Objects.isNull(supplierQualificationApply)) {
            return new SupplierQualificationApplyBaseDTO();
        }
        return supplierQualificationApplyConvert.entity2Dto(supplierQualificationApply);
    }

    @Override
    public List<SupplierQualificationApplySupplierBaseDTO> getApplySupplierList(Long applyId) {
        final List<SupplierQualificationApplySupplier> applySuppliers = supplierQualificationApplySupplierService.list(
                new LambdaQueryWrapper<SupplierQualificationApplySupplier>().eq(
                        SupplierQualificationApplySupplier::getApplyId, applyId));
        final List<Long> supplierIds = applySuppliers.stream().map(SupplierQualificationApplySupplier::getSupplierId)
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(supplierIds)) {
            return Collections.emptyList();
        }
        List<SupplierQualificationApplySupplierBaseDTO> supplierBaseDTOS =
                supplierQualificationApplySupplierConvert.entities2BaseDtos(
                        applySuppliers);
        final List<Supplier> suppliers = supplierService.listByIds(supplierIds);
        final Map<Long, Supplier> supplierMap = suppliers.stream().collect(Collectors.toMap(Supplier::getId, a -> a));
        //需要做数据转换
        for (SupplierQualificationApplySupplierBaseDTO supplierBaseDTO : supplierBaseDTOS) {
            final Supplier supplier = supplierMap.get(supplierBaseDTO.getSupplierId());
            supplierBaseDTO.setSupplierCode(supplier.getSupplierCode());
            supplierBaseDTO.setSupplierName(supplier.getSupplierName());
        }
        return supplierBaseDTOS;
    }

    @Override
    public List<SupplierQualificationApplyDetailBaseDTO> getApplyQualificationList(Long applyId) {
        final List<SupplierQualificationApplyDetail> qualificationApplyDetails =
                supplierQualificationApplyDetailService.list(
                        new LambdaQueryWrapper<SupplierQualificationApplyDetail>().eq(
                                SupplierQualificationApplyDetail::getApplyId, applyId));
        return supplierQualificationApplyDetailConvert.entities2BaseDtos(qualificationApplyDetails);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applySaveOrUpdate(SupplierQualificationApplySaveDTO applySaveDTO) {
        final List<SupplierQualificationApplySupplierBaseDTO> supplierList = applySaveDTO.getSupplierList();
        final List<SupplierQualificationApplyDetailBaseDTO> detailList = applySaveDTO.getDetailList();
        SupplierQualificationApply apply = supplierQualificationApplyConvert.saveDto2Entity(applySaveDTO);
        if (Objects.nonNull(apply.getId())) {
            /**
             * 修改，需要删除之前的数据重新插入
             */
            final SupplierQualificationApply dbApply = supplierQualificationApplyService.getById(apply.getId());
            if (dbApply.getStatus() != 1) {
                throw new DaoException("仅新增的数据可以修改!");
            }
            apply.setUpdateId(LoginUtil.getUserId());
            apply.setUpdateTime(LocalDateTime.now());

            supplierQualificationApplyDetailService.remove(
                    new LambdaQueryWrapper<SupplierQualificationApplyDetail>().eq(
                            SupplierQualificationApplyDetail::getApplyId, apply.getId()));
            supplierQualificationApplySupplierService.remove(
                    new LambdaQueryWrapper<SupplierQualificationApplySupplier>().eq(
                            SupplierQualificationApplySupplier::getApplyId, apply.getId()));
        } else {
            //新增
            final String sequenceNo = sequenceClient.createSequenceNo(SUPPLIER_QUALIFICATION_SUPPLEMENT_CODE.getCode());
            apply.setApplyNo(sequenceNo);
            apply.setCreatorId(LoginUtil.getUserId());
            apply.setCreateTime(LocalDateTime.now());
        }
        if (CollUtil.isEmpty(supplierList.stream().filter(e -> e.getType() == DelFlag.NORMAL.getStatus())
                .collect(Collectors.toList()))) {
            throw new DaoException("供应商未添加!");
        }
        if (CollUtil.isEmpty(detailList.stream().filter(e -> e.getType() == DelFlag.NORMAL.getStatus())
                .collect(Collectors.toList()))) {
            throw new DaoException("资质明细未添加!");
        }
        //需要判断所选的供应商是否全部都没有对应的资质信息,
        // t_supplier_qualification查询这张表，然后通过资质的code来判断是是否已经有资质了，如果有就抛异常
        final List<Long> supplierIds = supplierList.stream().filter(e -> e.getType() == DelFlag.NORMAL.getStatus())
                .map(e -> e.getSupplierId()).collect(Collectors.toList());
        final Map<Long, String> supplierIdCodeCache = supplierList.stream()
                .filter(e -> e.getType() == DelFlag.NORMAL.getStatus()).collect(
                        Collectors.toMap(SupplierQualificationApplySupplierBaseDTO::getSupplierId,
                                a -> a.getSupplierCode()));
        final List<SupplierQualification> list1 = supplierQualificationService.list(
                new LambdaQueryWrapper<SupplierQualification>().in(SupplierQualification::getSupplierId, supplierIds).eq(SupplierQualification::getState, 1));
//        final Map<Long, List<String>> qualificationCodeCache = list1.stream().collect(
//                Collectors.groupingBy(SupplierQualification::getSupplierId,
//                        Collectors.mapping(SupplierQualification::getQualificationCode, Collectors.toList())));

        final Map<Long, List<SupplierQualification>> qualificationCodeCache = list1.stream().collect(
                Collectors.groupingBy(SupplierQualification::getSupplierId, Collectors.toList()));

        final List<String> qualificationCodes = detailList.stream()
                .filter(e -> e.getType() == DelFlag.NORMAL.getStatus()).map(a -> a.getCode())
                .collect(Collectors.toList());
        final List<Qualification> qualifications = qualificationService.list(
                new LambdaQueryWrapper<Qualification>().in(Qualification::getCode, qualificationCodes));
        for (Long supplierId : qualificationCodeCache.keySet()) {
            final List<SupplierQualification> supplierQualifications = qualificationCodeCache.get(supplierId);

            //比较资质的版本是否一致，如果比原来的版本低则抛异常 2024-11-25 邓京术
            List<String> matchingElements = new ArrayList<>();
            Iterator ite = qualifications.iterator();
            while (ite.hasNext()) {
                Qualification qualification = (Qualification)ite.next();
                for (SupplierQualification supplierQualification: supplierQualifications) {
                    if (qualification.getCode().equals(supplierQualification.getQualificationCode())) {
                        float vf = Float.parseFloat(qualification.getVersion());
                        if (Float.parseFloat(supplierQualification.getVersion()) >= vf) {
                            matchingElements.add(qualification.getCode());
                        }
                    }
                }
            }
//            List<String> matchingElements = codes.stream().filter(qualificationCodes::contains)
//                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(matchingElements)) {
                throw new DaoException(StrUtil.format("供应商:{},资质编码:{}已经存在对应资质,请发起变更!",
                        supplierIdCodeCache.get(supplierId),
                        matchingElements.stream().collect(Collectors.joining(","))));
            }
        }
        supplierQualificationApplyService.saveOrUpdate(apply);
        if (CollUtil.isNotEmpty(supplierList)) {
            List<SupplierQualificationApplySupplier> list = supplierQualificationApplySupplierConvert.dtos2Entities(
                    supplierList);
            for (SupplierQualificationApplySupplier supplierQualificationApplySupplier : list) {
                supplierQualificationApplySupplier.setApplyId(apply.getId());
            }
            //如果是转合格和转小批量不允许多个供应商
            if (applySaveDTO.getType().equals(QualificationApplyType.BATCHED.getCode())
                    || applySaveDTO.getType().equals(QualificationApplyType.QUALIFIED.getCode())) {
                if (list.size() > 1) {
                    throw new DaoException("转合格和转小批量的资质补录不允许多个供应商同时操作!");
                }
            }
            supplierQualificationApplySupplierService.saveBatch(list);
        }
        if (CollUtil.isNotEmpty(detailList)) {
            List<SupplierQualificationApplyDetail> list = supplierQualificationApplyDetailConvert.dtos2Entities(
                    detailList);
            for (SupplierQualificationApplyDetail supplierQualificationApplyDetail : list) {
                supplierQualificationApplyDetail.setApplyId(apply.getId());
            }
            supplierQualificationApplyDetailService.saveBatch(list);
        }
        if (Objects.equals(applySaveDTO.getSubmitFlag(), FlagConst.Y.getCode())) {
            applySubmit(apply.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applySubmit(Long id) {
        final SupplierQualificationApply supplierQualificationApply = supplierQualificationApplyService.getById(id);
        if (supplierQualificationApply.getStatus() == QualificationApplyStatus.SUBMITTED.getVal()) {
            throw new DaoException("已提交,无需重复提交!");
        }
        final List<SupplierQualificationApplySupplier> applySuppliers = supplierQualificationApplySupplierService.list(
                new LambdaQueryWrapper<SupplierQualificationApplySupplier>().eq(
                                SupplierQualificationApplySupplier::getApplyId, id)
                        .eq(SupplierQualificationApplySupplier::getType, DelFlag.NORMAL.getStatus()));
        final List<SupplierQualificationApplyDetail> qualificationApplyDetails =
                supplierQualificationApplyDetailService.list(
                        new LambdaQueryWrapper<SupplierQualificationApplyDetail>().eq(
                                        SupplierQualificationApplyDetail::getApplyId, id)
                                .eq(SupplierQualificationApplyDetail::getType, DelFlag.NORMAL.getStatus()));
        if (CollUtil.isEmpty(applySuppliers) || CollUtil.isEmpty(qualificationApplyDetails)) {
            throw new DaoException("数据错误!补录申请单子表为空!");
        }
        List<SupplierQualificationChangeItem> insertLists = Lists.newArrayList();
        List<SupplierQualificationChange> insertLists1 = Lists.newArrayList();
        Set<Long> supplierIds = Sets.newHashSet();
        for (SupplierQualificationApplySupplier applySupplier : applySuppliers) {
            SupplierQualificationChange supplierQualificationChange = new SupplierQualificationChange();
            Long supplierQualificationChangeId = IdWorker.getId();
            supplierQualificationChange.setId(supplierQualificationChangeId);
            supplierQualificationChange.setSupplierId(applySupplier.getSupplierId());
            supplierIds.add(applySupplier.getSupplierId());
            supplierQualificationChange.setSupplementCode(supplierQualificationApply.getApplyNo());
            supplierQualificationChange.setCode(sequenceClient.createSequenceNo(QUALIFICATIONS_CHANGE_NO.getCode()));
            supplierQualificationChange.setCreateId(LoginUtil.getUserId());
            supplierQualificationChange.setCreateTime(LocalDateTime.now());
            insertLists1.add(supplierQualificationChange);
            for (SupplierQualificationApplyDetail qualificationApplyDetail : qualificationApplyDetails) {
                SupplierQualificationChangeItem supplierQualificationChangeItem = new SupplierQualificationChangeItem();
                supplierQualificationChangeItem.setChangeId(supplierQualificationChangeId);
                supplierQualificationChangeItem.setQualificationId(qualificationApplyDetail.getQualificationId());
                supplierQualificationChangeItem.setQualificationName(qualificationApplyDetail.getName());
                supplierQualificationChangeItem.setQualificationCode(qualificationApplyDetail.getCode());
                insertLists.add(supplierQualificationChangeItem);
            }
        }
        if (CollUtil.isNotEmpty(insertLists1)) {
            supplierQualificationChangeService.saveBatch(insertLists1);
        }
        if (CollUtil.isNotEmpty(insertLists)) {
            supplierQualificationChangeItemService.saveBatch(insertLists);
        }
        supplierQualificationApply.setStatus(QualificationApplyStatus.SUBMITTED.getVal());
        supplierQualificationApply.setUpdateTime(LocalDateTime.now());
        supplierQualificationApply.setUpdateId(LoginUtil.getUserId());
        supplierQualificationApplyService.updateById(supplierQualificationApply);
        //发送邮件
        if (CollUtil.isNotEmpty(supplierIds)) {
            final List<SupplierContacts> list = supplierContactsService.list(new LambdaQueryWrapper<SupplierContacts>()
                    .in(SupplierContacts::getSupplierId, supplierIds)
                    .eq(SupplierContacts::getContactsType, DictCode.ContactType.BUSINESS.getType()));
            final Map<Long, List<SupplierContacts>> supplierContactCache = list.stream()
                    .collect(Collectors.groupingBy(SupplierContacts::getSupplierId));
            final List<Supplier> suppliers = supplierService.listByIds(supplierIds);
            for (Supplier supplierById : suppliers) {
                final List<SupplierContacts> supplierContacts = supplierContactCache.get(supplierById.getId());
                if (CollUtil.isNotEmpty(supplierContacts)) {
                    EmailTmpSendDTO emailTmpSendDTO = new EmailTmpSendDTO();
                    final Set<String> emails = supplierContacts.stream().map(SupplierContacts::getEmail)
                            .collect(Collectors.toSet());
                    emailTmpSendDTO.setReceiver(emails);
                    emailTmpSendDTO.setParams(BeanUtil.beanToMap(supplierById));
                    emailTmpSendDTO.setTemplateCode("JW_POST_125");
                    emailTmpSendDTO.setSender(LoginUtil.getUserId());
                    emailSendClient.async(emailTmpSendDTO);
                }
            }
        }
    }

    @Override
    public void updateRemoveStatus(Long id) {
        final SupplierQualificationApply dbApply = supplierQualificationApplyService.getById(id);
        supplierQualificationApplyService.removeById(dbApply.getId());
        supplierQualificationApplyDetailService.remove(
                new LambdaQueryWrapper<SupplierQualificationApplyDetail>().eq(
                        SupplierQualificationApplyDetail::getApplyId, id));
        supplierQualificationApplySupplierService.remove(
                new LambdaQueryWrapper<SupplierQualificationApplySupplier>().eq(
                        SupplierQualificationApplySupplier::getApplyId, id));
    }

    @Override
    public PageView getChangeList(SupplierQualificationChangeQuery query) {
        final Page<SupplierQualificationChangePO> page = PageUtil.toPage(query);
        if (LoginUtil.isSupplier()) {
            query.setSupplierId(LoginUtil.getSupplierId());
        } else {
            //则获取用户id,查出该用户下的所有采购组关联的供应商
            query.setUserId(LoginUtil.getUserId());
        }
        List<SupplierQualificationChangePO> qualificationChangePOS = supplierQualificationChangeService.findList(page,
                query);
        List<SupplierQualificationChangeBaseDTO> changeBaseDTOS = supplierQualificationChangeConvert.pos2BaseDtos(
                qualificationChangePOS);
        modelAggregationService.processRelationAggregation(changeBaseDTOS);
        return PageUtil.getPV(changeBaseDTOS, page.getTotal());
    }

    @Override
    public SupplierQualificationChangeBaseDTO getChangeDetail(Long id) {
        final SupplierQualificationChange supplierQualificationChange = supplierQualificationChangeService.getById(id);
        if (Objects.isNull(supplierQualificationChange)) {
            //如果是新建需要根据登录用来判断是否为供应商登录，如果是供应商登录需要把供应商信息取出填充进去
            final SupplierQualificationChangeBaseDTO dto = new SupplierQualificationChangeBaseDTO();
            if (LoginUtil.isSupplier()) {
                final Supplier supplier = supplierService.getById(LoginUtil.getSupplierId());
                dto.setSupplierName(supplier.getSupplierName());
                dto.setSupplierId(supplier.getId());
            }
            return dto;
        }
        final Supplier supplier = supplierService.getById(supplierQualificationChange.getSupplierId());
        final SupplierQualificationChangeBaseDTO supplierQualificationChangeBaseDTO =
                supplierQualificationChangeConvert.entity2BaseDTO(
                        supplierQualificationChange);
        supplierQualificationChangeBaseDTO.setSupplierId(supplier.getId());
        supplierQualificationChangeBaseDTO.setSupplierName(supplier.getSupplierName());
        final SupplierQualificationApply qualificationApply = supplierQualificationApplyService.getOne(
                new LambdaQueryWrapper<>(SupplierQualificationApply.class).eq(SupplierQualificationApply::getApplyNo,
                        supplierQualificationChange.getSupplementCode()));
        //如果补录申请存在需要取品类数据
        if (Objects.nonNull(qualificationApply)) {
            supplierQualificationChangeBaseDTO.setPurchaseCategoryCodes(qualificationApply.getPurchaseCategoryCodes());
        }
        return supplierQualificationChangeBaseDTO;
    }

    @Override
    public List<SupplierQualificationChangeItemBaseDTO> getChangeItemList(Long changeId) {
        //需要查询版本号
        final List<SupplierQualificationChangeItem> changeItems = supplierQualificationChangeItemService.list(
                new LambdaQueryWrapper<SupplierQualificationChangeItem>().eq(
                        SupplierQualificationChangeItem::getChangeId, changeId));
        final List<SupplierQualificationChangeItemBaseDTO> supplierQualificationChangeItemBaseDTOS =
                supplierQualificationChangeItemConvert.entities2BaseDtos(
                        changeItems);

        //
        final Set<String> codes = changeItems.stream().map(SupplierQualificationChangeItem::getQualificationCode)
                .collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(codes)) {
            final List<Qualification> qualifications = qualificationService.findByCodes(codes);
            final Map<String, Long> fileMap = qualifications.stream().filter(a -> Objects.nonNull(a.getFileId()))
                    .collect(Collectors.toMap(Qualification::getCode, Qualification::getFileId));
            if (CollUtil.isNotEmpty(fileMap)) {
                for (SupplierQualificationChangeItemBaseDTO supplierQualificationChangeItemBaseDTO :
                        supplierQualificationChangeItemBaseDTOS) {
                    final String qualificationCode = supplierQualificationChangeItemBaseDTO.getQualificationCode();
                    final Long fileId = fileMap.get(qualificationCode);
                    if (Objects.nonNull(fileId)) {
                        supplierQualificationChangeItemBaseDTO.setQualificationFileId(fileId);
                    }
                }
            }
        }
        modelAggregationService.processRelationAggregation(supplierQualificationChangeItemBaseDTOS);
        return supplierQualificationChangeItemBaseDTOS;
    }

    @Override
    public PageView getList(SupplierQualificationQuery query) {
        final Page<SupplierQualification> page = PageUtil.toPage(query);
        final LambdaQueryWrapper<SupplierQualification> wrapper = new LambdaQueryWrapper<SupplierQualification>().eq(
                        SupplierQualification::getSupplierId, query.getSupplierId())
                .like(StrUtil.isNotEmpty(query.getCode()), SupplierQualification::getQualificationCode,
                        SqlUtils.concatLike(query.getCode(), SqlLike.DEFAULT))
                .like(StrUtil.isNotEmpty(query.getName()), SupplierQualification::getQualificationName,
                        SqlUtils.concatLike(query.getName(), SqlLike.DEFAULT));
        final List<SupplierQualification> list = supplierQualificationService.list(page, wrapper);
        List<SupplierQualificationBaseDTO> supplierQualificationBaseDTOS =
                supplierQualificationConvert.entities2BaseDtos(
                        list);
        modelAggregationService.processRelationAggregation(supplierQualificationBaseDTOS);
        return PageUtil.getPV(supplierQualificationBaseDTOS, page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeSaveOrUpdate(SupplierQualificationChangeSaveDTO supplierQualificationChangeSaveDTO) {
        SupplierQualificationChange supplierQualificationChange = supplierQualificationChangeConvert.saveDto2Entity(
                supplierQualificationChangeSaveDTO);
        /**
         * 校验当前供应商资质配置信息，匹配该供应商资质模板信息，若匹配到则查看是否填写有效期，是则校验必填，否则不校验
         */
        final SupplierInvitaion invitaionServiceOne = supplierInvitaionService.getOne(
                new LambdaQueryWrapper<SupplierInvitaion>().eq(SupplierInvitaion::getSupplierId,
                        supplierQualificationChangeSaveDTO.getSupplierId()), false);
        final Long templateId = invitaionServiceOne.getTemplateId();
        final SupplierTemplate supplierTemplate = supplierTemplateService.getById(templateId);
        final String qualificationTemplateCode = supplierTemplate.getQualificationTemplateCode();
        final String templateQualificationVersion = supplierTemplate.getQualificationVersion();
        final QualificationTemplate qualificationTemplate = qualificationTemplateService.getOne(
                new LambdaQueryWrapper<QualificationTemplate>().eq(QualificationTemplate::getCode,
                        qualificationTemplateCode).eq(QualificationTemplate::getVersion, templateQualificationVersion),
                false);
        final List<QualificationTemplateItem> qualificationTemplateItems = qualificationTemplateItemService.list(
                new LambdaQueryWrapper<QualificationTemplateItem>().eq(QualificationTemplateItem::getTemplateId,
                        qualificationTemplate.getId()));
        final List<String> requriedCodes = qualificationTemplateItems.stream()
                .filter(a -> a.getRequery() == EnableStatus.ENABLE.getStatus()).map(QualificationTemplateItem::getCode)
                .collect(Collectors.toList());
        final List<SupplierQualificationChangeItemBaseDTO> item = supplierQualificationChangeSaveDTO.getItem();
        for (SupplierQualificationChangeItemBaseDTO supplierQualificationChangeItemBaseDTO : item) {
            if (requriedCodes.contains(supplierQualificationChangeItemBaseDTO.getQualificationCode())) {
                if (StrUtil.isEmpty(supplierQualificationChangeItemBaseDTO.getNewAvailableStartDate())) {
                    throw new DaoException(StrUtil.format("资质编码:{},生效日期必填",
                            supplierQualificationChangeItemBaseDTO.getQualificationCode()));
                } else if (StrUtil.isEmpty(supplierQualificationChangeItemBaseDTO.getNewAvailableEndDate())) {
                    throw new DaoException(StrUtil.format("资质编码:{},失效日期必填",
                            supplierQualificationChangeItemBaseDTO.getQualificationCode()));
                }
                //还需要判断生效日期要在失效日期后面
                final DateTime startDate = DateUtil.parse(
                        supplierQualificationChangeItemBaseDTO.getNewAvailableStartDate(), DateUtils.yyyyMMddDash);
                final DateTime endDate = DateUtil.parse(supplierQualificationChangeItemBaseDTO.getNewAvailableEndDate(),
                        DateUtils.yyyyMMddDash);
                if (endDate.isBeforeOrEquals(startDate)) {
                    throw new DaoException(StrUtil.format("资质编码:{},生效日期必须要在失效日期之前",
                            supplierQualificationChangeItemBaseDTO.getQualificationCode()));
                }
            }
        }
        Long id = supplierQualificationChange.getId();
        final SupplierQualificationChange change = supplierQualificationChangeService.getById(id);
        if (Objects.nonNull(change)) {
            //如果是修改，需要把之前的明细数据删除
            supplierQualificationChangeItemService.remove(new LambdaQueryWrapper<SupplierQualificationChangeItem>().eq(
                    SupplierQualificationChangeItem::getChangeId, id));
            supplierQualificationChange.setUpdateId(LoginUtil.getUserId());
            supplierQualificationChange.setUpdateTime(LocalDateTime.now());
        } else {
            //需要生成编号
            supplierQualificationChange.setCode(sequenceClient.createSequenceNo(QUALIFICATIONS_CHANGE_NO.getCode()));
            supplierQualificationChange.setCreateId(LoginUtil.getUserId());
            supplierQualificationChange.setCreateTime(LocalDateTime.now());
        }
        supplierQualificationChange.setState(QualificationChangeStatus.BUSINESS_APPROVALING.getVal());
        supplierQualificationChangeService.saveOrUpdate(supplierQualificationChange);
        id = supplierQualificationChange.getId();
        List<SupplierQualificationChangeItem> changeItems = supplierQualificationChangeItemConvert.dtos2Entities(item);
        for (SupplierQualificationChangeItem changeItem : changeItems) {
            changeItem.setChangeId(id);
        }
        if (CollUtil.isNotEmpty(changeItems)) {
            supplierQualificationChangeItemService.saveBatch(changeItems);
        }
        // TODO: 2024/2/28  jiez 需要增加如果供应商没有生成正式编号，需要直接生效
    }

    @Override
    public void changeBusinessReject(Long id, String remark) {
        final SupplierQualificationChange change = supplierQualificationChangeService.getById(id);
        change.setApproverId(LoginUtil.getUserId());
        change.setState(QualificationChangeStatus.REJECT.getVal());
        change.setRemark(remark);
        supplierQualificationChangeService.updateById(change);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeBusinessPass(Long id, String remark, String rows) {
        final List<SupplierQualificationChangeItem> changeItems = JSON.parseArray(rows,
                SupplierQualificationChangeItem.class);
        supplierQualificationChangeItemService.updateBatchById(changeItems);
        final SupplierQualificationChange change = supplierQualificationChangeService.getById(id);
        change.setApproverId(LoginUtil.getUserId());
        change.setState(QualificationChangeStatus.SQE_APPROVALING.getVal());
        change.setRemark(remark);
        supplierQualificationChangeService.updateById(change);
        hanlderChangeDataToMain(change);
    }

    @Override
    public PageView warnPage(SupplierQualificationQuery query) {
        final Page<SupplierQualificationPO> page = PageUtil.toPage(query);
        final List<SupplierQualificationPO> list = supplierQualificationService.selectWarnList(page, query);
        List<SupplierQualificationBaseDTO> supplierQualificationBaseDTOS = supplierQualificationConvert.pos2BaseDtos(
                list);
        modelAggregationService.processRelationAggregation(supplierQualificationBaseDTOS);
        return PageUtil.getPV(supplierQualificationBaseDTOS, page.getTotal());
    }

    @Override
    public void changeSqeReject(Long id, String remark) {
        final SupplierQualificationChange change = supplierQualificationChangeService.getById(id);
        change.setApproverId(LoginUtil.getUserId());
        change.setState(QualificationChangeStatus.BUSINESS_APPROVALING.getVal());
        change.setSqeRemark(remark);
        supplierQualificationChangeService.updateById(change);
    }

    @Override
    public void changeSqePass(Long id, String remark) {
        final SupplierQualificationChange change = supplierQualificationChangeService.getById(id);
        change.setSqeApproverId(LoginUtil.getUserId());
        change.setState(QualificationChangeStatus.PASS.getVal());
        change.setSqeRemark(remark);
        supplierQualificationChangeService.updateById(change);
        final List<SupplierQualification> tmp = hanlderChangeDataToMain(change);
        final List<SupplierQualification> supplierQualifications = tmp.stream()
                .filter(a -> Objects.equals(a.getScene(), QualificationType.BAOGAO.getCode())).toList();
        //如果是走的资质补录申请，就需要转合格了
        final String supplementCode = change.getSupplementCode();
        if (StrUtil.isNotEmpty(supplementCode)) {
            final SupplierQualificationApply qualificationApply = supplierQualificationApplyService.getOne(
                    new LambdaQueryWrapper<SupplierQualificationApply>().eq(SupplierQualificationApply::getApplyNo,
                            supplementCode));
            if (qualificationApply.getType() == QualificationApplyType.BATCHED.getCode()) {
                final String purchaseCategoryCodes = qualificationApply.getPurchaseCategoryCodes();
                if (StrUtil.isNotEmpty(purchaseCategoryCodes)) {
                    final List<String> pgcs = StrUtil.split(purchaseCategoryCodes, StrUtil.COMMA);
                    final Long id1 = qualificationApply.getId();
                    final List<SupplierQualificationApplySupplier> applySuppliers =
                            supplierQualificationApplySupplierService.list(
                                    new LambdaQueryWrapper<SupplierQualificationApplySupplier>().eq(
                                            SupplierQualificationApplySupplier::getApplyId, id1));
                    //如果是转合格和转小批量这个供应商只允许是单个
                    final Set<Long> supplierIds = applySuppliers.stream()
                            .map(SupplierQualificationApplySupplier::getSupplierId).collect(Collectors.toSet());
                    final LambdaQueryWrapper<SupplierPurchaseCategory> queryWrapper1 =
                            new LambdaQueryWrapper<SupplierPurchaseCategory>().in(
                                            SupplierPurchaseCategory::getSupplierId,
                                            supplierIds).in(SupplierPurchaseCategory::getPurchaseCategoryCode, pgcs)
                                    .eq(SupplierPurchaseCategory::getState, AuthenticationState.POTENTIAL.getState());
                    final List<SupplierPurchaseCategory> list1 = supplierPurchaseCategoryService.list(queryWrapper1);
                    if (CollUtil.isNotEmpty(list1)) {
                        //潜在的需要去更新资质附件已上传
//                        supplierPurchaseCategoryService.update(
//                                new LambdaUpdateWrapper<SupplierPurchaseCategory>().in(
//                                                SupplierPurchaseCategory::getSupplierId,
//                                                supplierIds).in(SupplierPurchaseCategory::getPurchaseCategoryCode,
//                                                pgcs)
//                                        .set(SupplierPurchaseCategory::getReportFlag, FlagConst.Y.getCode())
//                                        .eq(SupplierPurchaseCategory::getState,
//                                                AuthenticationState.POTENTIAL.getState()));
                        //需要把本次的资质都变更到当前的品类中,如果是多个需要把当前的更新到新品类，然后还需要生成旧品类
                        //需要判断品类是否单个，如果单个则直接设置品类编码，如果是多个需要把资质设置多份
                        List<SupplierQualification> updateLists = Lists.newArrayList();
                        List<SupplierQualification> inertLists = Lists.newArrayList();
                        final SupplierPurchaseCategory supplierPurchaseCategory1 = list1.get(0);
                        for (SupplierQualification supplierQualification : supplierQualifications) {
                            supplierQualification.setPurchaseCategoryCode(
                                    supplierPurchaseCategory1.getPurchaseCategoryCode());
                            updateLists.add(supplierQualification);
                        }
                        if (list1.size() > 1) {
                            for (int i = 1; i < list1.size(); i++) {
                                final SupplierPurchaseCategory supplierPurchaseCategory = list1.get(i);
                                for (SupplierQualification supplierQualification : supplierQualifications) {
                                    SupplierQualification su = supplierQualificationConvert.copy1(
                                            supplierQualification);
                                    su.setId(null);
                                    su.setPurchaseCategoryCode(supplierPurchaseCategory.getPurchaseCategoryCode());
                                    inertLists.add(su);
                                }
                            }
                        }

                        //创建后传输小批量状态到SAP，如果该供应商其他品类有合格状态， 则传合格
                        final LambdaQueryWrapper<SupplierPurchaseCategory> queryWrapper2 =
                                new LambdaQueryWrapper<SupplierPurchaseCategory>().in(
                                                SupplierPurchaseCategory::getSupplierId,
                                                supplierIds).in(SupplierPurchaseCategory::getPurchaseCategoryCode, pgcs)
                                        .eq(SupplierPurchaseCategory::getState, AuthenticationState.QUALIFIED.getState());
                        final List<SupplierPurchaseCategory> list2 = supplierPurchaseCategoryService.list(queryWrapper2);
                        if (CollUtil.isNotEmpty(list1)) {
                            SupplierPurchaseCategory supplierPurchaseCategory = list1.get(0);
                            Supplier s = supplierService.getById(supplierPurchaseCategory.getSupplierId());
                            List<SupplierStateToSapDTO.Item>  items=new ArrayList<>();
                            SupplierStateToSapDTO.IT_ITEM it_item= new SupplierStateToSapDTO.IT_ITEM();
                            SupplierStateToSapDTO.Item item = new SupplierStateToSapDTO.Item();
                            item.setLIFNR(s.getSupplierCode());
                            if(CollUtil.isNotEmpty(list2)){
                                item.setZZJDZT("H");
                            }else{
                                item.setZZJDZT("X");
                            }
                            items.add(item);
                            it_item.setItem(items);
                            SupplierStateToSapDTO supplierStateToSapDTO = new SupplierStateToSapDTO();
                            supplierStateToSapDTO.setIT_ITEM(it_item);
                            final SapResposeBody sapResposeBody = sapClient.updateSupplierState(supplierStateToSapDTO);
                            if (!sapResposeBody.getES_RET().getCODE().equals(RestCode.SAP_SUCCESS.getCode())) {
                                throw new DaoException(StrUtil.format("推送SAP错误:{}", sapResposeBody.getES_RET().getMSG()));
                            }
                        }
                        if (CollUtil.isNotEmpty(inertLists)) {
                            supplierQualificationService.saveBatch(inertLists);
                        }
                        if (CollUtil.isNotEmpty(updateLists)) {
                            supplierQualificationService.updateBatchById(updateLists);
                        }
                    }
                }
            } else if (qualificationApply.getType() == QualificationApplyType.QUALIFIED.getCode()) {
                final String purchaseCategoryCodes = qualificationApply.getPurchaseCategoryCodes();
                if (StrUtil.isNotEmpty(purchaseCategoryCodes)) {
                    final List<String> pgcs = StrUtil.split(purchaseCategoryCodes, StrUtil.COMMA);
                    final Long id1 = qualificationApply.getId();
                    final List<SupplierQualificationApplySupplier> applySuppliers =
                            supplierQualificationApplySupplierService.list(
                                    new LambdaQueryWrapper<SupplierQualificationApplySupplier>().eq(
                                            SupplierQualificationApplySupplier::getApplyId, id1));
                    //如果是转合格和转小批量这个供应商只允许是单个
                    final Set<Long> supplierIds = applySuppliers.stream()
                            .map(SupplierQualificationApplySupplier::getSupplierId).collect(Collectors.toSet());
                    //获取品类信息，如果是走资质补录，然后状态都是小批量的就走转合格
                    final LambdaQueryWrapper<SupplierPurchaseCategory> queryWrapper =
                            new LambdaQueryWrapper<SupplierPurchaseCategory>().in(
                                            SupplierPurchaseCategory::getSupplierId,
                                            supplierIds).in(SupplierPurchaseCategory::getPurchaseCategoryCode, pgcs)
                                    .eq(SupplierPurchaseCategory::getState, AuthenticationState.SMALL_BATCH.getState());
                    final List<SupplierPurchaseCategory> list = supplierPurchaseCategoryService.list(queryWrapper);
                    if (CollUtil.isNotEmpty(list)) {
                        //小批量的才需要转合格
                        supplierPurchaseCategoryService.update(
                                new LambdaUpdateWrapper<SupplierPurchaseCategory>().in(
                                                SupplierPurchaseCategory::getSupplierId,
                                                supplierIds).in(SupplierPurchaseCategory::getPurchaseCategoryCode, pgcs)
                                        .eq(SupplierPurchaseCategory::getState,
                                                AuthenticationState.SMALL_BATCH.getState())
                                        .set(SupplierPurchaseCategory::getState,
                                                AuthenticationState.QUALIFIED.getState()));

                        //创建后传输合格状态到SAP
                        SupplierPurchaseCategory supplierPurchaseCategory = list.get(0);
                        Supplier s = supplierService.getById(supplierPurchaseCategory.getSupplierId());
                        List<SupplierStateToSapDTO.Item> items = new ArrayList<>();
                        SupplierStateToSapDTO.IT_ITEM it_item = new SupplierStateToSapDTO.IT_ITEM();
                        SupplierStateToSapDTO.Item item = new SupplierStateToSapDTO.Item();
                        item.setLIFNR(s.getSupplierCode());
                        item.setZZJDZT("H");
                        items.add(item);
                        it_item.setItem(items);
                        SupplierStateToSapDTO supplierStateToSapDTO = new SupplierStateToSapDTO();
                        supplierStateToSapDTO.setIT_ITEM(it_item);
                        final SapResposeBody sapResposeBody = sapClient.updateSupplierState(supplierStateToSapDTO);
                        if (!sapResposeBody.getES_RET().getCODE().equals(RestCode.SAP_SUCCESS.getCode())) {
                            throw new DaoException(StrUtil.format("推送SAP错误:{}", sapResposeBody.getES_RET().getMSG()));
                        }
                    }
                }
            }

        }
    }

    @Override
    public PageView getReportList(Long id, String purchaseCategoryCode) {
        List<SupplierQualification> list = supplierQualificationService.list(
                new LambdaQueryWrapper<>(SupplierQualification.class)
                        .eq(SupplierQualification::getSupplierId, id)
                        .eq(SupplierQualification::getPurchaseCategoryCode, purchaseCategoryCode)
                        .eq(SupplierQualification::getScene, QualificationType.BAOGAO.getCode()));
        //如果是这个是空的，就需要把供应商的全取出来
        if (CollUtil.isEmpty(list)) {
            list = supplierQualificationService.list(
                    new LambdaQueryWrapper<>(SupplierQualification.class)
                            .eq(SupplierQualification::getSupplierId, id)
                            .eq(SupplierQualification::getScene, QualificationType.BAOGAO.getCode()));
            //需要把id都置空
            list.forEach(a -> {
                a.setId(null);
                a.setPurchaseCategoryCode(purchaseCategoryCode);
            });
            if (CollUtil.isNotEmpty(list)) {
                //需要把的报告插入进去 SRM_ZZ_066 SRM_ZZ_065
                final SupplierQualification supplierQualification = list.get(0);
                final SupplierQualification supplierQualification1 = new SupplierQualification();
                BeanUtil.copyProperties(supplierQualification, supplierQualification1);
                supplierQualification1.setQualificationCode(DictCode.SupplierQualification.SRM_ZZ_066.name());
                supplierQualification1.setQualificationName(DictCode.SupplierQualification.SRM_ZZ_066.getTitle());
                supplierQualification1.setFileId(null);
                list.add(supplierQualification1);
                final SupplierQualification supplierQualification2 = new SupplierQualification();
                BeanUtil.copyProperties(supplierQualification, supplierQualification2);
                supplierQualification2.setQualificationCode(DictCode.SupplierQualification.SRM_ZZ_065.name());
                supplierQualification2.setQualificationName(DictCode.SupplierQualification.SRM_ZZ_065.getTitle());
                supplierQualification2.setFileId(null);
                list.add(supplierQualification2);
            }
        }
        final List<SupplierQualificationBaseDTO> supplierQualificationBaseDTOS =
                supplierQualificationConvert.entities2BaseDtos(
                        list);
        modelAggregationService.processRelationAggregation(supplierQualificationBaseDTOS);
        return PageUtil.getPV(supplierQualificationBaseDTOS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reportSave(List<SupplierQualificationBaseDTO> supplierQualificationBaseDTOS) {
        final List<SupplierQualification> supplierQualifications = supplierQualificationConvert.dtos2Entities(
                supplierQualificationBaseDTOS);
        supplierQualificationService.saveOrUpdateBatch(supplierQualifications);
        //只会处理一个品类的
        if (CollUtil.isNotEmpty(supplierQualifications)) {
            final Long supplierId = supplierQualifications.get(0).getSupplierId();
            final String purchaseCategoryCode = supplierQualifications.get(0).getPurchaseCategoryCode();
            //更新认证报告的上传标记
            //需要增加逻辑如果有评分这个地方才会变成1,如果没有评分这个地方变成2
            final SupplierSqeScore one = supplierSqeScoreService.getOne(
                    new LambdaQueryWrapper<>(SupplierSqeScore.class).eq(SupplierSqeScore::getSupplierId, supplierId));
            Integer reportStatus;
            if (Objects.nonNull(one)) {
                reportStatus = SupplierPurchaseCategoryReportStatus.OK.getCode();
            } else {
                reportStatus = SupplierPurchaseCategoryReportStatus.UPLOAD.getCode();
            }
            supplierPurchaseCategoryService.update(
                    new LambdaUpdateWrapper<SupplierPurchaseCategory>()
                            .eq(SupplierPurchaseCategory::getState, AuthenticationState.POTENTIAL.getState())
                            .eq(SupplierPurchaseCategory::getSupplierId, supplierId)
                            .set(SupplierPurchaseCategory::getReportFlag, reportStatus)
                            .eq(SupplierPurchaseCategory::getPurchaseCategoryCode, purchaseCategoryCode));

        }
    }

    @Override
    public void update(List<SupplierQualificationBaseDTO> supplierQualificationBaseDTOS) {
        if (CollUtil.isNotEmpty(supplierQualificationBaseDTOS)) {
            List<SupplierQualification> updateLists = Lists.newArrayList();
            for (SupplierQualificationBaseDTO supplierQualificationBaseDTO : supplierQualificationBaseDTOS) {
                SupplierQualification supplierQualification = new SupplierQualification();
                supplierQualification.setId(supplierQualificationBaseDTO.getId());
                supplierQualification.setFileId(supplierQualificationBaseDTO.getFileId());
                updateLists.add(supplierQualification);
            }
            supplierQualificationService.updateBatchById(updateLists);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeById(Long id) {
        final SupplierQualificationChange byId = supplierQualificationChangeService.getById(id);
        //判断是否存在，不存在抛异常
        if (Objects.isNull(byId)) {
            throw new DaoException("资质补录信息不存在!");
        }
        supplierQualificationChangeService.removeById(id);
        supplierQualificationChangeItemService.remove(new LambdaQueryWrapper<SupplierQualificationChangeItem>().eq(
                SupplierQualificationChangeItem::getChangeId, id));

    }

    /**
     * 把资质变更信息同步到供应商资质表
     *
     * @param change 资质变更记录
     */
    @Transactional(rollbackFor = Exception.class)
    public List<SupplierQualification> hanlderChangeDataToMain(SupplierQualificationChange change) {
        //需要把供应商的资质文件更新到t_supplier_qualification表
        final List<SupplierQualificationChangeItem> changeItems = supplierQualificationChangeItemService.list(
                new LambdaQueryWrapper<SupplierQualificationChangeItem>().eq(
                        SupplierQualificationChangeItem::getChangeId, change.getId()));
        final Map<String, SupplierQualificationChangeItem> changeItemMap = changeItems.stream()
                .collect(Collectors.toMap(SupplierQualificationChangeItem::getQualificationCode, a -> a));
        //需要通过资质编号查询资质配置的数据
        final Set<String> strings = changeItemMap.keySet();
        final List<Qualification> qualifications = qualificationService.list(
                new LambdaQueryWrapper<>(Qualification.class).in(Qualification::getCode, strings));
        final Map<String, Qualification> qualificationMap = qualifications.stream()
                .collect(Collectors.toMap(Qualification::getCode, a -> a));
        final Long supplierId = change.getSupplierId();
        final List<SupplierQualification> list = supplierQualificationService.list(
                new LambdaQueryWrapper<SupplierQualification>().eq(SupplierQualification::getSupplierId, supplierId));
        //如果是变更,需要把新字段变更到已有数据中
        Set<String> updateCodes = Sets.newConcurrentHashSet();
        final Long userId = LoginUtil.getUserId();
        List<SupplierQualification> updateLists = Lists.newArrayList();
        for (SupplierQualification supplierQualification : list) {
            final String qualificationCode = supplierQualification.getQualificationCode();
            final SupplierQualificationChangeItem supplierQualificationChangeItem = changeItemMap.get(
                    qualificationCode);
            if (Objects.nonNull(supplierQualificationChangeItem)) {
                final Qualification qualification = qualificationMap.get(qualificationCode);
                supplierQualification.setFileId(supplierQualificationChangeItem.getNewFileId());
                supplierQualification.setVersion(qualification.getVersion());
                supplierQualification.setScene(qualification.getScene());
                supplierQualification.setAvailableStartDate(supplierQualificationChangeItem.getNewAvailableStartDate());
                supplierQualification.setAvailableEndDate(supplierQualificationChangeItem.getNewAvailableEndDate());
                supplierQualification.setUpdateTime(LocalDateTime.now());
                supplierQualification.setUpdateUserid(userId);
                updateLists.add(supplierQualification);
                updateCodes.add(qualificationCode);
            }
        }
        //新增的资质
        List<SupplierQualification> insertLists = Lists.newArrayList();
        for (SupplierQualificationChangeItem changeItem : changeItems) {
            final String qualificationCode = changeItem.getQualificationCode();
            if (!updateCodes.contains(qualificationCode)) {
                final Qualification qualification = qualificationMap.get(qualificationCode);
                SupplierQualification supplierQualification = new SupplierQualification();
                supplierQualification.setSupplierId(supplierId);
                supplierQualification.setVersion(qualification.getVersion());
                supplierQualification.setScene(qualification.getScene());
                supplierQualification.setQualificationCode(qualificationCode);
                supplierQualification.setQualificationName(changeItem.getQualificationName());
                supplierQualification.setFileId(changeItem.getNewFileId());
                supplierQualification.setFileId(changeItem.getNewFileId());
                supplierQualification.setAvailableStartDate(changeItem.getNewAvailableStartDate());
                supplierQualification.setAvailableEndDate(changeItem.getNewAvailableEndDate());
                supplierQualification.setCreateTime(LocalDateTime.now());
                supplierQualification.setCreateUserid(userId);
                insertLists.add(supplierQualification);
            }
        }
        if (CollUtil.isNotEmpty(updateLists)) {
            supplierQualificationService.updateBatchById(updateLists);
        }
        if (CollUtil.isNotEmpty(insertLists)) {
            supplierQualificationService.saveBatch(insertLists);
        }
        insertLists.addAll(updateLists);
        return insertLists;
    }
}