package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.junmpProcess.dto.ApplyTypeDto;
import com.junmp.junmpProcess.dto.StartProcessInstanceDTO;
import com.junmp.junmpProcess.service.IFlowInstanceService;
//import com.junmp.jyzb.repository.TypeRepository;
import com.junmp.jyzb.api.bean.dto.*;
import com.junmp.jyzb.api.bean.dto.fetchingDataDto.TypeDto;
import com.junmp.jyzb.api.bean.dto.tempDto.TypeSizeDto;
import com.junmp.jyzb.api.bean.query.QueryEquipmentTypeReq;
import com.junmp.jyzb.api.bean.req.UpdateEquipmentTypeReq;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.EquipmentExceptionEnum;
import com.junmp.jyzb.api.exception.enums.SupplierExceptionEnum;
import com.junmp.jyzb.entity.*;
import com.junmp.jyzb.mapper.EquipmentCountSummaryMapper;
import com.junmp.jyzb.mapper.PriceSumSummaryMapper;
import com.junmp.jyzb.service.*;
import com.junmp.jyzb.utils.*;
import com.junmp.v2.auth.api.context.LoginContext;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.junmp.jyzb.mapper.EquipmentTypeMapper;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class EquipmentTypeServiceImpl extends ServiceImpl<EquipmentTypeMapper, EquipmentType> implements EquipmentTypeService {

    @Resource
    private RestHighLevelClient client;
    @Resource
    private EquipmentTypeMapper equipmentTypeMapper;
    @Resource
    private SupplierService supplierService;
    @Resource
    private SupplierTypeService supplierTypeService;
    @Resource
    private InventorySummaryService inventorySummaryService;
    @Resource
    private PriceSumSummaryMapper priceSumSummaryMapper;
    @Resource
    private EquipmentCountSummaryMapper equipmentCountSummaryMapper;

    @Autowired
    private RabbitMQSendMsg MQ;

    @Resource
    private PubOrgService pubOrgService;
    @Resource
    private IFlowInstanceService FlowInstanceService;


    @Resource
    private EquipmentSizeService equipmentSizeService;
    private static final String REDIS_TYPE = "Type_";
    private List<EquipmentTypeDto> typeDto;
    private ArrayList<String> ids;

    private static final String DES_ALGORITHM = "DES";
    private static final String CBC_PADDING = "DES/CBC/PKCS5Padding";
    private static final int CHUNK_SIZE = 8;

    //查询出类别表中数据的所有装备信息（入库时调用）
    public List<EquipmentTypeDto> getEquipmentList(QueryEquipmentTypeReq req) {
        List<EquipmentType> list = list(new LambdaQueryWrapper<EquipmentType>()
                .eq(EquipmentType::getType, req.getType())
                .eq(ObjectUtil.isNotNull(req.getParentId()), EquipmentType::getParentId, req.getParentId())
                .like(ObjectUtil.isNotNull(req.getName()), EquipmentType::getName, req.getName()));
        List<EquipmentTypeDto> collect = list.stream().map(equipmentType -> {
            EquipmentTypeDto org = new EquipmentTypeDto();
            BeanPlusUtil.copyProperties(equipmentType, org);
            return org;
        }).collect(Collectors.toList());
        return collect;
    }

    @Transactional
    @Override
    public String addEquipment(UpdateEquipmentTypeReq req) {

        EquipmentType type = new EquipmentType();
        //判断数据库是否已经存在相同的name，如果有，则提示名称已存在
        List<EquipmentType> list = list(new LambdaQueryWrapper<EquipmentType>()
                .eq(EquipmentType::getName, req.getName()));
        if (list.size() > 0) {
            throw new ServiceException(EquipmentExceptionEnum.EQUIPMENT_NAME_EXIST);
        }

        List<String> chekResult = supplierService.CheckSupplierList(req.getSupplierList());
        if (chekResult.size() == 0) {
            int code = 0;
            if (ObjectUtil.isNotEmpty(req.getProcessDefinitionId())) {
                StartProcessInstanceDTO startProcessInstanceDTO = new StartProcessInstanceDTO();

                //设置参数
                startProcessInstanceDTO = setParams(startProcessInstanceDTO, req);
                String s = FlowInstanceService.startProcessInstanceById(startProcessInstanceDTO);
                return s;
            } else {
                //先增加code码
                BeanPlusUtil.copyProperties(req, type);
                EquipmentType parentType = this.getById(req.getParentId());
                int newcode = parentType.getMaxCode() + 1;
                type.setId(String.valueOf(newcode));
                type.setCode(String.valueOf(newcode));
                parentType.setMaxCode(newcode);
                parentType.setCode(String.valueOf(newcode));
                List<SupplierType> supplierType = new ArrayList<>();
                //判断req.getSupplierList()是否为空，如果为空则不进行循环
                if (CollectionUtil.isNotEmpty(req.getSupplierList())) {
                    req.getSupplierList().forEach(supply -> {
                                SupplierType st = new SupplierType();
                                st.setId(String.valueOf(UUID.randomUUID()));
                                st.setState(0);
                                st.setSupplierId(supply);
                                st.setTypeId(String.valueOf(newcode));
                                supplierType.add(st);
                            }
                    );
                    supplierTypeService.saveBatch(supplierType);
                }
                this.updateById(parentType);
                type.setCreateTime(DateTimeUtil.getCurrentDateTime());
                type.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                this.save(type);
                code=newcode;
            }
            return String.valueOf(code);
        } else {
            String msg = "以下供应商不存在：" + String.join(",", chekResult);
            throw new JYZBAppException(SupplierExceptionEnum.SUPPLIER_IS_NOT_EXIST, msg);
        }


    }

    public StartProcessInstanceDTO setParams (StartProcessInstanceDTO startProcessInstanceDTO, UpdateEquipmentTypeReq req) {
        startProcessInstanceDTO.setProcessDefinitionId(req.getProcessDefinitionId());
        ApplyTypeDto applyTypeDto = new ApplyTypeDto();
        BeanPlusUtil.copyProperties(req,applyTypeDto);
        applyTypeDto.setSupplierList(CollectionUtil.isNotEmpty(req.getSupplierList())?String.join(",",req.getSupplierList()):null);
        startProcessInstanceDTO.setTypeOrder("typeApply");
        startProcessInstanceDTO.setType("typeApply");
        PubOrg pubOrg=equipmentTypeMapper.getOrg(LoginContext.getContext().getLoginUser().getUserId());
        startProcessInstanceDTO.setDName(pubOrg.getDName());
        startProcessInstanceDTO.setInvList(req.getName());
        Object A= JSON.toJSONString(req, SerializerFeature.WriteDateUseDateFormat);
        JSONObject jsonObject = JSON.parseObject(A.toString());
        startProcessInstanceDTO.setApplyTypeDto(applyTypeDto);
        startProcessInstanceDTO.setFormData(jsonObject);
        return startProcessInstanceDTO;
    }
    @Override
    public String GetEquipmentByIds(QueryEquipmentTypeReq req) {
        List<String> typeIds = Arrays.asList(req.getTypeIds().split(","));
        List<EquipmentType> list = list(new LambdaQueryWrapper<EquipmentType>()
                .and(qw -> typeIds.forEach(typeId -> qw.or().eq(EquipmentType::getId, typeId))));
        list.forEach(p -> p.getName());
        String concatenatedNames = list.stream()
                .map(EquipmentType::getName) // 获取每个 EquipmentType 的 name 属性
                .collect(Collectors.joining(",")); // 使用逗号拼接所有的 name
        return concatenatedNames;
    }

    @Override
    public String GetEquipmentBySizeIds(QueryEquipmentTypeReq req) {

        List<String> sizeIds = Arrays.asList(req.getSizeIds().split(","));
        List<TypeSizeDto> sizeList = equipmentTypeMapper.GetNameBySizeIds(sizeIds);
        String concatenatedNames = sizeList.stream()
                .map(dto -> dto.getTypeName() + "-" + dto.getSizeName())  // 获取每个 EquipmentType 的 name 属性
                .collect(Collectors.joining(",")); // 使用逗号拼接所有的 name
        return concatenatedNames;
    }

    @Override
    public Boolean deleteEquipment(UpdateEquipmentTypeReq req) {
        LambdaQueryWrapper<EquipmentType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotEmpty(req.getId()), EquipmentType::getParentId, req.getParentId());
        List<EquipmentType> eqList = list(wrapper);
        if (eqList.size() > 0) {
            throw new ServiceException(EquipmentExceptionEnum.EQUIPMENT_CHILDREN_EXIST);
        } else {
            this.removeById(req.getId());
        }

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateEquipment(UpdateEquipmentTypeReq req) {
        if (req.getEpcType() != null) {
            equipmentSizeService.update(new LambdaUpdateWrapper<EquipmentSize>()
                    .set(EquipmentSize::getEpcType, req.getEpcType())
                    .eq(EquipmentSize::getTypeId, req.getId()));
        }
        EquipmentType type = this.getById(req.getId());
        if (ObjectUtil.isNull(type)) {
            throw new ServiceException(EquipmentExceptionEnum.EQUIPMENT_TYPE_NOT_EXIST);
        }
        req.setCode(type.getCode());//为了以防typeCode不一致的问题
        List<String> chekResult = supplierService.CheckSupplierList(req.getSupplierList());
        if (chekResult.size() == 0) {
            // 先增加code码
            //判断两者的名称是否一致，如果一致，则直接改动summary表中的数据
            if (!type.getName().equals(req.getName())) {
                inventorySummaryService.update(new LambdaUpdateWrapper<InventorySummary>()
                        .set(InventorySummary::getTypeName, req.getName())
                        .eq(InventorySummary::getTypeId, req.getId()));
                priceSumSummaryMapper.setTypeName(req.getId(), req.getName());
                equipmentCountSummaryMapper.setTypeName(req.getId(), req.getName());
            }
            BeanPlusUtil.copyProperties(req, type);

            // 获取当前type对应的所有关联的供应商
            List<SupplierType> currentSupplierList = supplierTypeService.list(new LambdaQueryWrapper<SupplierType>()
                    .eq(SupplierType::getTypeId, type.getId()));

            // 获取当前type对应的所有关联的供应商ID集合
            Set<String> currentSupplierIds = currentSupplierList.stream()
                    .map(SupplierType::getSupplierId)
                    .collect(Collectors.toSet());

            // 获取传入的supplierList中的所有供应商ID集合
            Set<String> newSupplierIds = new HashSet<>();
            if (CollectionUtil.isNotEmpty(req.getSupplierList())) {

                newSupplierIds = new HashSet<>(req.getSupplierList());
            }

            // 需要新增的供应商关联数据
            List<SupplierType> supplierTypeToAdd = new ArrayList<>();
            for (String supplierId : newSupplierIds) {
                if (!currentSupplierIds.contains(supplierId)) {
                    SupplierType st = new SupplierType();
                    st.setId(String.valueOf(UUID.randomUUID()));
                    st.setState(0);
                    st.setSupplierId(supplierId);
                    st.setTypeId(String.valueOf(type.getId()));
                    supplierTypeToAdd.add(st);
                }
            }

            // 需要删除的供应商关联数据
            List<SupplierType> supplierTypeToDelete = new ArrayList<>();
            for (SupplierType currentSupplier : currentSupplierList) {
                if (!newSupplierIds.contains(currentSupplier.getSupplierId())) {
                    supplierTypeToDelete.add(currentSupplier);
                }
            }

            // 保存新增的供应商关联数据
            supplierTypeService.saveBatch(supplierTypeToAdd);

            // 删除需要删除的供应商关联数据
            if (!supplierTypeToDelete.isEmpty()) {
                supplierTypeService.removeByIds(supplierTypeToDelete.stream()
                        .map(SupplierType::getId)
                        .collect(Collectors.toList()));
            }
            // 保存type
            type.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            return this.updateById(type);
        } else {
            String msg = "以下供应商不存在：" + String.join(",", chekResult);
            throw new JYZBAppException(SupplierExceptionEnum.SUPPLIER_IS_NOT_EXIST, msg);
        }
    }


    @Override
    public Boolean changeEquipmentState(UpdateEquipmentTypeReq req) {
        EquipmentType equipment = this.getById(req.getId());
        if (equipment != null) {
            equipment.setState(Integer.valueOf(req.getState()));
            return this.updateById(equipment);
        }
        return true;
    }


    //获取单个物资的信息
    @Override
    public EquipmentTypeDto getEquipment(QueryEquipmentTypeReq req) {
        EquipmentTypeDto equipment = new EquipmentTypeDto();
        BeanPlusUtil.copyProperties(this.getById(req.getId()), equipment);
        //获取该物资的供应商id
        List<SupplierType> list = supplierTypeService.list(new LambdaQueryWrapper<SupplierType>()
                .eq(SupplierType::getTypeId, req.getId()));
        List<String> collect = list.stream().map(SupplierType::getSupplierId).distinct().collect(Collectors.toList());
        equipment.setSupplierList(collect);
        return equipment;
    }

    public List<EquipmentTypeDto> getLowType(QueryEquipmentTypeReq req) {
        if (ObjectUtil.isEmpty(req.getParentId())) {
            req.setParentId(req.getId());
        }
        if (ObjectUtil.isEmpty(req.getParentId())) {
            req.setParentId("00000000-0000-0000-0000-000000000000");
        }
        LambdaQueryWrapper<EquipmentType> wp = this.createWrapper(req);
        List<EquipmentType> list = this.list(wp);
        List<EquipmentTypeDto> orgs = new ArrayList<>();
        Comparator<EquipmentType> orgComparator = (org1, org2) -> {
            String code1 = org1.getCode();
            String code2 = org2.getCode();

            // 将code字段转换为整数类型进行比较
            try {
                long intValue1 = Long.parseLong(code1);
                long intValue2 = Long.parseLong(code2);
                return Long.compare(intValue1, intValue2);
            } catch (NumberFormatException e) {
                // 如果有不是数字的情况，直接返回字符串比较结果
                return code1.compareTo(code2);
            }
        };
        Collections.sort(list, orgComparator);

        list.forEach(p -> {
            EquipmentTypeDto org = new EquipmentTypeDto();
            BeanPlusUtil.copyProperties(p, org);
            //判断是否有下级，如果没有设置为true；
            // 判断是否有子节点
            boolean hasChildren = hasChildren(p.getId());
            org.setIsLeaf(!hasChildren);
            orgs.add(org);
        });
        return orgs;
    }

    // 判断是否有子节点的方法
    private boolean hasChildren(String parentId) {
        LambdaQueryWrapper<EquipmentType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentType::getParentId, parentId);
        Long count = this.count(wrapper);
        return count > 0;
    }


    //获取整棵type树
    public List<EquipmentTreeDto> GetTypeTree(QueryEquipmentTypeReq req) {
        //默认type为1（也就是需要将整棵数进行返回，如果只需要返回上面的装备类型，那么前端传递的type是0，否则就是1）
        Integer type = 1;
        String typeName= req.getTypeName();
        if (ObjectUtil.isNotNull(req.getType()) && req.getType() == 0) {
            type = 0;
        }
        List<EquipmentTreeDto> dtoList = new ArrayList<>();
        List<EquipmentTreeDto> dtoTypeNameList = new ArrayList<>();
        //获取所有的装备，不包括超级根
        List<EquipmentType> list = list(new LambdaQueryWrapper<EquipmentType>()
                .ne(EquipmentType::getId, "00000000-0000-0000-0000-000000000000"));
        // 构建根节点列表
        List<EquipmentType> rootEntities = new ArrayList<>();

        for (EquipmentType entity : list) {
            if (entity.getParentId().equals("00000000-0000-0000-0000-000000000000")) {
                rootEntities.add(entity);
            }
        }

        if (ObjectUtil.isEmpty(typeName)){
            // 递归转换为输出类节点
            for (EquipmentType rootEntity : rootEntities) {
                EquipmentTreeDto dto = convertNode(rootEntity, list, type);
                dtoList.add(dto);
            }

        }else {
            for (EquipmentType rootEntity : rootEntities) {
                EquipmentTreeDto dto = convertNodeWithTypeName(rootEntity, list, type,typeName);
                dtoTypeNameList.add(dto);
            }
            for (int i=0;i<dtoTypeNameList.size();i++) {
                if (CollectionUtil.isEmpty(dtoTypeNameList.get(i).getChildren())){
                    dtoTypeNameList.remove(dtoTypeNameList.get(i));
                    i--;
                }
            }
            EquipmentTreeDto treeDto = new EquipmentTreeDto();
            treeDto.setChildren(dtoTypeNameList);
            //设置ids
            SetTypeIds(dtoTypeNameList);
            treeDto.setIds(ids);
            dtoList.add(treeDto);
            //再将id传入
        }
        return dtoList;

    }

    public void SetTypeIds(List<EquipmentTreeDto> treeResult) {
        ids = new ArrayList<>();
        if (treeResult != null) {
            for (EquipmentTreeDto equipmentTreeDto : treeResult) {
                setTypeIdsRecursive(equipmentTreeDto);
            }
        }
    }

    private void setTypeIdsRecursive(EquipmentTreeDto equipmentTreeDto) {
        if (equipmentTreeDto != null) {
            // 添加当前节点的 id
            ids.add(equipmentTreeDto.getId());

            // 递归处理子节点
            if (equipmentTreeDto.getChildren() != null) {
                for (EquipmentTreeDto child : equipmentTreeDto.getChildren()) {
                    setTypeIdsRecursive(child);
                }
            }
        }
    }

    @Override
    public List<TypeDto> alignTypeInfo(UpdateEquipmentTypeReq req) {
        String date = DateTimeUtil.TimeLongToString(req.getUpdateTime());
        return equipmentTypeMapper.alignTypeInfo(date);
    }


    private EquipmentTreeDto convertNode(EquipmentType entity, List<EquipmentType> entityList, Integer type) {
        EquipmentTreeDto dto = new EquipmentTreeDto();
        BeanPlusUtil.copyProperties(entity, dto);
        dto.setIsLeaf(true); // 默认为叶子节点
        List<EquipmentTreeDto> children = new ArrayList<>();
        List<EquipmentTreeDto> childrens = new ArrayList<>();
        for (EquipmentType childEntity : entityList) {
            if (childEntity.getParentId().equals(entity.getId()) ) {
                EquipmentTreeDto childDto = convertNode(childEntity, entityList, type);

                if (childEntity.getType() != 1 && type == 0) {
                    children.add(childDto);
                    dto.setIsLeaf(false);
                } else if (childEntity.getType() == 1 && type == 0) {
                    childrens.add(childDto);
                    dto.setIsLeaf(true);
                } else if (type == 1) {
                    children.add(childDto);
                    dto.setIsLeaf(false);
                }
//                dto.setIsLeaf(false);  // 存在子节点，当前节点不是叶子节点
            }
        }
        if (CollectionUtil.isNotEmpty(childrens)){
            dto.setChildrens(childrens);
        }
        dto.setChildren(children);

        return dto;
    }


    private EquipmentTreeDto convertNodeWithTypeName(EquipmentType entity, List<EquipmentType> entityList, Integer type,String typeName) {
        EquipmentTreeDto dto = new EquipmentTreeDto();
        BeanPlusUtil.copyProperties(entity, dto);
        dto.setIsLeaf(true); // 默认为叶子节点
        dto.setIsContainsName(false);
        List<EquipmentTreeDto> children = new ArrayList<>();
        List<EquipmentTreeDto> childrens = new ArrayList<>();
        for (EquipmentType childEntity : entityList) {
            if (entity.getName().contains(typeName)){
                dto.setIsContainsName(true);
                entity.setIsContainsName(true);
            }
            if (childEntity.getParentId().equals(entity.getId()) ) {
                childEntity.setIsContainsName(entity.getIsContainsName());
                EquipmentTreeDto childDto = convertNodeWithTypeName(childEntity, entityList, type,typeName);
                //其他层
                if (childDto.getIsContainsName() || (ObjectUtil.isNotNull(childEntity.getIsContainsName()) && childEntity.getIsContainsName())){
                    if ( childEntity.getType() != 1 && type == 0 ) {
                        children.add(childDto);
                        dto.setIsLeaf(false);
                        dto.setIsContainsName(true);
                    } else if ( childEntity.getType() == 1 && type == 0) {
                        childrens.add(childDto);
                        dto.setIsLeaf(true);
                        dto.setIsContainsName(true);
                    } else if (type == 1 ) {
                        children.add(childDto);
                        dto.setIsLeaf(false);
                        dto.setIsContainsName(true);
                    }
                }else {//最下层
                    if (childEntity.getType() != 1 && type == 0 && (childDto.getName().contains(typeName) || (ObjectUtil.isNotNull(childEntity.getIsContainsName()) && childEntity.getIsContainsName()))) {//下一层为装备类别
                        children.add(childDto);
                        dto.setIsLeaf(false);
                        dto.setIsContainsName(true);

                    } else if (childEntity.getType() == 1 && type == 0 ) {//下一层为装备名称
                        childrens.add(childDto);
                        dto.setIsLeaf(true);
                    } else if (type == 1 ) {//只查询装备名称
                        children.add(childDto);
                        dto.setIsLeaf(false);
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(childrens)){
            dto.setChildrens(childrens);
        }
        dto.setChildren(children);

        return dto;
    }
    private LambdaQueryWrapper<EquipmentType> createWrapper(QueryEquipmentTypeReq req) {
        LambdaQueryWrapper<EquipmentType> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isEmpty(req)) {
            return wrapper;
        }
        wrapper.eq(ObjectUtil.isNotEmpty(req.getParentId()), EquipmentType::getParentId, req.getParentId());
        // 添加id字段不等于"00000000-0000-0000-0000-000000000000"的判断
        wrapper.ne(EquipmentType::getId, "00000000-0000-0000-0000-000000000000");
        wrapper.eq(ObjectUtil.isNotEmpty(req.getType()), EquipmentType::getType, req.getType());
        wrapper.like(ObjectUtil.isNotEmpty(req.getName()), EquipmentType::getName, req.getName());
        wrapper.eq(ObjectUtil.isNotEmpty(req.getTypeId()), EquipmentType::getId, req.getTypeId());
        wrapper.orderByDesc(EquipmentType::getCreateTime);
        return wrapper;

    }

    @Override
    public String exportSizeAndType(QueryEquipmentTypeReq req) {
        List<EquipmentType> typeList = list(new LambdaQueryWrapper<EquipmentType>().ge(EquipmentType::getUpdateTime, req.getUpdateTime()));
        SizeAndType sizeAndType = new SizeAndType();
        sizeAndType.setTypeList(CollectionUtil.isNotEmpty(typeList) ? typeList : new ArrayList<>());
        List<EquipmentSize> sizeList = equipmentSizeService.list(new LambdaQueryWrapper<EquipmentSize>().ge(EquipmentSize::getUpdateTime, req.getUpdateTime()));
        sizeAndType.setSizeList(CollectionUtil.isNotEmpty(sizeList) ? sizeList : new ArrayList<>());

        if (ObjectUtil.isNotEmpty(req.getFlag()) && req.getFlag()) {
            List<PubOrg> pubList = pubOrgService.list(new LambdaQueryWrapper<PubOrg>().ge(PubOrg::getUpdateTime, req.getUpdateTime())
                    .eq(PubOrg::getDelFlag, 1));
            sizeAndType.setOrgList(CollectionUtil.isNotEmpty(pubList) ? pubList : new ArrayList<>());
        }

        String jsonString = JSONObject.toJSONString(sizeAndType);

        try {
            // 设置密钥和初始化向量
            byte[] byKey = Arrays.copyOf("junmp888".getBytes(StandardCharsets.UTF_8), 8);
            byte[] iv = {(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};

            SecretKeySpec secretKeySpec = new SecretKeySpec(byKey, "DES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

            // 创建加密器并进行初始化
            Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
            desCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

            // 对输入数据进行填充
            byte[] inputByteArray = jsonString.getBytes(StandardCharsets.UTF_8);
            int paddingLength = 8 - (inputByteArray.length % 8);
            byte[] paddedByteArray = new byte[inputByteArray.length + paddingLength];
            System.arraycopy(inputByteArray, 0, paddedByteArray, 0, inputByteArray.length);

            // 执行加密操作
            byte[] encryptedBytes = desCipher.doFinal(paddedByteArray);

            // 对加密结果进行Base64编码并返回
            return Base64.getEncoder().encodeToString(encryptedBytes);

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    @Override
    public PageResult<EquipmentTreeDto> getTypePage(QueryEquipmentTypeReq req) {
        Page<EquipmentTreeDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());

        page=equipmentTypeMapper.getTypePage(page,req,req.getTypeCodesList());
        return PageResultFactory.createPageResult(page);
    }


}


