package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.jyzb.Repository.TypeRepository;
import com.junmp.jyzb.api.bean.dto.*;
import com.junmp.jyzb.api.bean.dto.FetchingDataDto.SizeDto;
import com.junmp.jyzb.api.bean.dto.FetchingDataDto.TypeDto;
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.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.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
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.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
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.text.SimpleDateFormat;
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;
    @Autowired
    private TypeRepository typeRepository;
    @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 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;
  }

    @Override
    public Object addEs() {
        QueryEquipmentTypeReq req =new QueryEquipmentTypeReq();
        req.setType(0);
        List<EquipmentType> esDto=this.list();
        typeRepository.deleteAll();
        return typeRepository.saveAll(esDto);
    }

    @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) {

            //先增加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);
            //更新parent_ids字段
            equipmentTypeMapper.setTypeParentIds(type.getId());

            String exchangeName="topicExchange";
            MQDto mqDto = new MQDto();
            mqDto.setApi("InfoChange");
            //更改类别，1为类型
            mqDto.setType(2);
            mqDto.setMessage("Adding typeInfo");
            MQ.sendToExchange(exchangeName,"org",mqDto);
            //往es中添加数据
            typeRepository.save(type);
            return  String.valueOf(newcode);
        } else {
            String msg="以下供应商不存在：" +String.join(",", chekResult);
            throw new JYZBAppException(EquipmentExceptionEnum.SUPPLIER_NOT_EXIST, msg);
        }

    }



    @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());

            String exchangeName="topicExchange";
            MQDto mqDto = new MQDto();
            mqDto.setApi("InfoChange");
            //更改类别，1为类型
            mqDto.setType(2);
            mqDto.setMessage("Updating typeInfo");
            MQ.sendToExchange(exchangeName,"org",mqDto);
            //往es中添加数据
            typeRepository.save(type);
            return this.updateById(type);
        } else {
            String msg="以下供应商不存在：" +String.join(",", chekResult);
            throw new JYZBAppException(EquipmentExceptionEnum.SUPPLIER_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;
    }

//    @Override
//    public ResponseResult setTypeParentIds() {
//        //更新parent_ids字段
//        equipmentTypeMapper.setTypeParentIds();
//        return new ResponseResult(HttpStatus.SUCCESS, ReturnMsg.PASS);
//    }


    public ESTypeDto getTypeTreeByEs(QueryEquipmentTypeReq req) throws IOException {

        ElasticsearchUtil es=new ElasticsearchUtil<>(client);
        // 先从ES中拿到检索数据
        List<EquipmentType> searchResults = es.searchEntities("type_pinyin",req.getNickName(),"name",0, 50,req.getType(), req.getTypeName(), req.getSearchType(), EquipmentType.class);
        LambdaQueryWrapper<EquipmentType> wp = this.createWrapper(req);
        // 获取所有组织机构数据
        List<EquipmentType> allTypes= es.searchAll("type_pinyin",0, 3000, EquipmentType.class);
//        List<EquipmentType> allTypes = this.list(wp);
        List<EquipmentTypeDto> treeResult= buildTypeTree(searchResults,allTypes);
        ESTypeDto resultDto=new ESTypeDto();
        resultDto.setTypeDto(treeResult);
        SetIds(treeResult);
        resultDto.setIds(ids);
        return  resultDto;
    }

    public void SetIds(List<EquipmentTypeDto> treeResult) {
        ids = new ArrayList<>();
        if (treeResult != null) {
            for (EquipmentTypeDto equipmentTypeDto : treeResult) {
                setIdsRecursive(equipmentTypeDto);
            }
        }
    }

    private void setIdsRecursive(EquipmentTypeDto equipmentTypeDto) {
        if (equipmentTypeDto != null) {
            // 添加当前节点的 id
            ids.add(equipmentTypeDto.getId());

            // 递归处理子节点
            if (equipmentTypeDto.getChildren() != null) {
                for (EquipmentTypeDto child : equipmentTypeDto.getChildren()) {
                    setIdsRecursive(child);
                }
            }
        }
    }

    public List<EquipmentTypeDto> buildTypeTree(List<EquipmentType> searchResults, List<EquipmentType> allTypes) {
        Map<String, EquipmentTypeDto> typeDtoMap = new HashMap<>();

        // 将所有设备类型转换为EquipmentTypeDto并放入map中，同时计算子节点数量
        for (EquipmentType type : allTypes) {
            EquipmentTypeDto typeDto = new EquipmentTypeDto();
            BeanPlusUtil.copyProperties(type, typeDto);
            // 其他字段的映射...

            // 计算子节点数量
            int childCount = 0;
            for (EquipmentType childType : allTypes) {
                if (childType.getParentId().equals(type.getId())) {
                    childCount++;
                }
            }
            typeDto.setChildCount(childCount);
            if (childCount<=0)
            {
                typeDto.setIsLeaf(true);
            }
            else
            {
                typeDto.setIsLeaf(false);
            }
            // 将EquipmentTypeDto放入map中，以id为键
            typeDtoMap.put(typeDto.getId(), typeDto);
        }

        List<EquipmentTypeDto> tree = new ArrayList<>();

        // 遍历所有搜索到的设备类型数据，构建树
        for (EquipmentType searchResult : searchResults) {
            EquipmentTypeDto typeDto = typeDtoMap.get(searchResult.getId());

            // 如果找到对应的EquipmentTypeDto
            if (typeDto != null && !tree.contains(typeDto)) {
                // 从当前节点开始，依次向上查找上级节点，直到最顶层
                String parentId = typeDto.getParentId();

                // 将当前节点及其相关节点加入树中
                while (parentId != null) {
                    EquipmentTypeDto parentDto = typeDtoMap.get(parentId);

                    if (parentDto != null) {
                        // 将当前节点添加到上级节点的children中，确保不重复添加
                        if (!parentDto.getChildren().contains(typeDto)) {
                            parentDto.getChildren().add(typeDto);
                        }

                        // 如果上级节点是最顶层，将上级节点添加到树中，确保不重复添加
                        if (parentDto.getParentId().equals("00000000-0000-0000-0000-000000000000")
                                && !parentDto.getId().equals("00000000-0000-0000-0000-000000000000") && !tree.contains(parentDto)) {
                            tree.add(parentDto);
                        }

                        // 将上级节点设为当前节点，继续向上查找
                        typeDto = parentDto;
                        parentId = typeDto.getParentId();
                    } else {
                        parentId = null; // 上级节点不存在，跳出循环
                    }
                }

            }
        }

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

    @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<>();
        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) {
                    dto.setIsLeaf(true);
                } else if (type==1) {
                    children.add(childDto);
                    dto.setIsLeaf(false);
                }
//                dto.setIsLeaf(false);  // 存在子节点，当前节点不是叶子节点
            }
        }

        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.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 (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);


//            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_ALGORITHM);
//            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
//
//            Cipher desCipher = Cipher.getInstance(CBC_PADDING);
//            desCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
//
//            byte[] inputByteArray = jsonString.getBytes(StandardCharsets.UTF_8);
//            int offset = 0;
//
//            StringBuilder encryptedString = new StringBuilder();
//
//            while (offset < inputByteArray.length) {
//                int length = Math.min(CHUNK_SIZE, inputByteArray.length - offset);
//                byte[] chunk = new byte[length];
//                System.arraycopy(inputByteArray, offset, chunk, 0, length);
//
//                byte[] encryptedChunk = desCipher.doFinal(chunk);
//                String base64EncodedChunk = Base64.getEncoder().encodeToString(encryptedChunk);
//                encryptedString.append(base64EncodedChunk);
//
//                offset += CHUNK_SIZE;
//            }
//            return encryptedString.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }



}


