package org.dromara.zhishu.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.file.request.PddGoodsImgUploadRequest;
import com.pdd.pop.sdk.http.api.file.response.PddGoodsImgUploadResponse;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.dromara.common.core.enums.FormatsType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysConfigService;
import org.dromara.zhishu.domain.*;
import org.dromara.zhishu.domain.bo.*;
import org.dromara.zhishu.domain.dto.BatchProcessingContext;
import org.dromara.zhishu.domain.dto.RunningTaskShopGoodsDto;
import org.dromara.zhishu.domain.dto.request.BatchGoodsRequest;
import org.dromara.zhishu.domain.dto.request.GoodsComparisonRequest;
import org.dromara.zhishu.domain.dto.request.UpdateArtNoRequest;
import org.dromara.zhishu.domain.dto.request.ZhishuShopGoodsRequest;
import org.dromara.zhishu.domain.vo.*;
import org.dromara.zhishu.domain.vo.ProductSubmitResultVo;
import org.dromara.zhishu.enums.*;
import org.dromara.zhishu.mapper.*;
import org.dromara.zhishu.service.*;
import org.dromara.zhishu.service.client.KfzClient;
import org.dromara.zhishu.service.client.PddClient;
import org.dromara.zhishu.service.factory.InventorySynchronizedStrategyFactory;
import org.dromara.zhishu.service.strategy.InventorySynchronizedStrategy;
import org.dromara.zhishu.threads.KfzAutoAddRunnable;
import org.dromara.zhishu.threads.ShopGoodsTaskRunnable;
import org.dromara.zhishu.util.*;
import org.hibernate.validator.internal.util.stereotypes.Lazy;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.repository.query.Param;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.dromara.zhishu.util.UrlUtil.getImgResultUrl;
import static org.dromara.zhishu.util.UrlUtil.getUploadImgUrl;

/**
 * 商品信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-03-07
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ZhishuShopGoodsServiceImpl implements IZhishuShopGoodsService {

    private static final String UPLOAD_DIR = "D:\\images";

    private final WaveDetailMapper waveDetailMapper;


    /**
     * 锁对象
     */
    private final Map<String, Object> lockMap = new HashMap<>();
    private final Map<String, Boolean> runMap = new HashMap<>();

    private final ApplicationContext applicationContext;
    private final IZhishuShopGoodsDetailService zhishuShopGoodsDetailService;

    private final ZhishuShopGoodsMapper baseMapper;

    private final IRunningTaskService runningTaskService;


    private final TBookAuditMapper tBookAuditMapper;

    private final IShopGoodsPublishedService shopGoodsPublishedService;

    private final IZhishuShopImagesService zhishuShopImagesService;

    private final IRunningTaskByShopService runningTaskByShopService;

    private final ScheduledExecutorService scheduledExecutorService;

    private final ITaskService taskService;

    private final ISysConfigService configService;

    private final IShopDetailService shopDetailService;

    private final ITDepotService depotService;


    private final ITLogisticsService logisticsService;
    // 每隔多少秒续期一次 Redis 锁（比如 30 秒）
    private static final int INITIAL_DELAY_AND_PERIOD = 30;

    @Resource
    private TDepotMapper tDepotMapper;

    @Resource
    private TShelvesMapper tShelvesMapper;

    @Autowired
    private IShopService shopService;

    @Autowired
    private TaskServiceImpl taskServiceImpl;

    @Autowired
    private CnumberUtils cnumberUtils;

    @Autowired
    private TDepotMapper TDepotMapper;

    @Autowired
    private TShelvesMapper TShelvesMapper;

    @Autowired
    private TFreightMapper TFreightMapper;

    @Autowired
    private TLogisticsMapper tLogisticsMapper;

    @Autowired
    private ZhishuShopImagesMapper zhishuShopImagesMapper;

    @Lazy
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Lazy
    @Autowired
    private KongfzServiceImpl kongfzService;

    @Autowired
    private ShopGoodIsbnMapper shopGoodIsbnMapper;

    @Autowired
    private ArtNoMoveMapper  artNoMoveMapper;

    // 品相对应的数值
    private static final double[] CONDITION_CODES = {1, 2, 3, 4, 5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10};
    // 品相对应的字母标识
    private static final String[] CONDITION_CODE = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"};

    // 品相对应的中文标识
    private static final String[] CHINESE_CODE = {"一品", "二品", "三品", "四品", "五品", "六品", "六五品", "七品", "七五品", "八品", "八五品", "九品", "九五品", "全新"};
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private KfzClient kfzClient;

    @Autowired
    private UploadUtil uploadUtil;

    @Autowired
    private ZhishuShopGoodsAopService zhishuShopGoodsAopService;

    @Autowired
    private StockChangeLogMapper stockChangeLogMapper;
    @Autowired
    private PddClient pddClient;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private PlatformTransactionManager transactionManager;



    /**
     * 批量查询商品根据id
     * @param ids
     * @return
     */
    @Override
    public List<ZhishuShopGoodsVo> selectByIds(List<String> ids){
        return baseMapper.selectByIds(ids);
    }

    /**
     * 查询商品信息
     *
     * @param id 主键
     * @return 商品信息
     */
    @Override
    public ZhishuShopGoodsVo queryById(String id) {
        // 查询商品信息
        Long userId = LoginHelper.getUserId();
        ZhishuShopGoodsVo result = baseMapper.selectByIdVo(id);
        // 判断result不为空并且result.getPrice不为空
        if (result != null) {
            // 查询仓库编码
            String depotCode = result.getArtNo().substring(0, 2);
            TDepotVo vo = baseMapper.selectDepotName(userId, depotCode);
            if (vo != null) {
                result.setDepotName(vo.getName() + vo.getUnit());
                result.setDepotId(vo.getId());
            }
            result.setConditionCode(CHINESE_TO_CODE_MAP2.get(result.getConditionCode()));
        }
        return result;
    }


    /**
     * 查询商品信息
     *
     * @param isbn 主键
     * @return 商品信息
     */
    @Override
    public List<ProductVo> getProductByBarcode(String isbn) {
        List<ProductVo> results = baseMapper.selectShopGoodsByIsbn(isbn);
        if (results.isEmpty()) {

        }
        return results;
    }

    /**
     * 查询商品信息
     *
     * @param isbn 主键
     * @return 商品信息
     */
    private static final int MAX_RETRIES = 1;
    private static final long RETRY_DELAY_MS = 1000;

    @Override
    public List<KongfzVo> getProductByKongfz(String keyword, String searchType, String sortType, String conditionValue, String cookies, String publisher, String author) {
        // 记录程序开始时间
        long startTime = System.currentTimeMillis();
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        // 获取Cookie的API地址
//        String cookieUrl = "https://test.kongfz.buzhiyushu.cn/api/auth/getCookies/1915230113968467969/18904056801/Long6166@";
        // 调用孔夫子API获取图书信息
        String searchUrl = "https://search.kongfz.com/pc-gw/search-web/client/pc/product/keyword/list";
        Map<String, String> params = new HashMap<>();
        params.put("searchType", searchType);
        params.put("dataType", "0");
        params.put("page", "1");
        params.put("keyword", keyword);
        params.put("sortType", sortType);
        params.put("quality", conditionValue);
        params.put("actionPath", "sortType,quality");
        params.put("quaSelect", "2");
        params.put("userArea", "13003000000");
        if (publisher != null && !publisher.trim().isEmpty()) {
            params.put("press", publisher);
        }
        if (author != null && !author.trim().isEmpty()) {
            params.put("author", author);
        }

        List<KongfzVo> productList = new ArrayList<>();
        Exception lastException = null;

        for (int attempt = 0; attempt < MAX_RETRIES; attempt++) {
            try {
                if (StringUtils.isEmpty(cookies)) {
                    throw new ServiceException("Cookie数据为空，响应内容：" + cookies);
                }
                // 将参数编码并拼接到URL
                StringBuilder urlWithParams = new StringBuilder(searchUrl);
                if (!params.isEmpty()) {
                    urlWithParams.append("?");
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        String encodedKey = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8);
                        String encodedValue = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8);
                        urlWithParams.append(encodedKey).append("=").append(encodedValue).append("&");
                    }
                    // 删除末尾多余的"&"
                    urlWithParams.deleteCharAt(urlWithParams.length() - 1);
                }


                // 设置请求头
                Map<String, String> headers = new HashMap<>();
                // headers.put("Cookie", "PHPSESSID=" + cookie);

                // 构建HTTP请求
                HttpRequest request = HttpRequest.newBuilder().uri(URI.create(urlWithParams.toString())).header("Cookie", "PHPSESSID=" + cookies).GET() // 显式指定GET方法
                        .build();
                // 记录请求开始时间
                long requestStartTime = System.currentTimeMillis();
                // 发送HTTP请求并获取响应
                HttpClient client = HttpClient.newBuilder()
                        .executor(executorService) // 使用声明的线程池
                        .connectTimeout(Duration.ofSeconds(5))
                        .version(HttpClient.Version.HTTP_2)
                        .followRedirects(HttpClient.Redirect.NORMAL)
                        .proxy(ProxySelector.getDefault())
                        .build();
                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                System.out.println("响应状态码: " + response.statusCode() + "数据" + response);
                // 记录请求结束时间
                long requestEndTime = System.currentTimeMillis();
                // 计算请求耗时
                long requestTime = requestEndTime - requestStartTime;
                // 打印到控制台
                System.out.println("请求耗时：" + requestTime + "ms");

                // 打印响应内容，特别是在出错时
                String responseBody = response.body();
//                System.out.println("孔夫子API响应: " + responseBody);

                // 检查状态码，非200状态码可能表示请求失败
                if (response.statusCode() != 200) {
                    System.err.println("孔夫子API返回非200状态码: " + response.statusCode());
                    throw new ServiceException("孔夫子API请求失败，状态码: " + response.statusCode() + ", 响应内容: " + responseBody);
                }

                // 检查响应内容中是否包含错误信息
                Map<String, Object> responseMap = JSON.parseObject(responseBody);
                if (responseMap != null && responseMap.containsKey("status") && !Integer.valueOf(1).equals(responseMap.get("status"))) {
                    System.err.println(" 孔夫子API返回错误:" + responseBody);
                    String errorMessage = responseMap.containsKey("message") ? responseMap.get("message").toString() : "未知错误";
                    throw new ServiceException(errorMessage);
                }

                // 解析响应JSON
                if (responseMap != null && responseMap.get("data") != null) {
                    Map<String, Object> data = (Map<String, Object>) responseMap.get("data");
                    if (data.get("itemResponse") != null) {
                        Map<String, Object> itemResponse = (Map<String, Object>) data.get("itemResponse");
                        List<Map<String, Object>> list = (List<Map<String, Object>>) itemResponse.get("list");

                        // 只取前12条记录
                        int limit = Math.min(12, list.size());
                        for (int i = 0; i < limit; i++) {
                            Map<String, Object> item = list.get(i);
                            KongfzVo productVo = new KongfzVo();
                            // 设置ProductVo的属性
                            productVo.setName((String) item.get("title"));
                            productVo.setAuthor((String) item.get("author"));
                            productVo.setPress((String) item.get("press"));
                            productVo.setShopName((String) item.get("shopName"));
                            Object priceObj = item.get("price");
                            if (priceObj instanceof Number) {
                                productVo.setPrice(((Number) priceObj).longValue());
                            }
                            productVo.setImgUrl((String) item.get("imgUrl"));
                            productVo.setImgBigUrl((String) item.get("imgBigUrl"));
                            productVo.setPriceText((String) item.get("priceText"));
                            productVo.setQualityText((String) item.get("qualityText"));
                            // 关键修复：解析运费信息
                            Map<String, Object> postage = (Map<String, Object>) item.get("postage");
                            if (postage != null) {
                                List<Map<String, Object>> shippingList = (List<Map<String, Object>>) postage.get("shippingList");
                                if (shippingList != null && !shippingList.isEmpty()) {
                                    // 取第一个运费选项
                                    Map<String, Object> shipping = shippingList.get(0);
                                    // 处理 shippingFee
                                    Object shippingFeeObj = shipping.get("shippingFee");
                                    if (shippingFeeObj != null) {
                                        BigDecimal shippingFee = new BigDecimal(shippingFeeObj.toString());
                                        productVo.setShippingFee(shippingFee);
                                    }
                                    // 处理 shippingFeeText
                                    productVo.setShippingFeeText((String) shipping.get("shippingFeeText"));
                                }
                            }
                            productList.add(productVo);
                        }
                        // 记录程序结束时间
                        long endTime = System.currentTimeMillis();
                        System.out.println("程序运行时间：" + (endTime - startTime) + "毫秒");
                        // 关闭线程池
                        shutdownAndAwaitTermination(executorService);
                        return productList;
                    }
                }

            } catch (Exception e) {
                lastException = e;
                System.err.println("孔夫子API请求失败: " + e.getMessage());

                if (attempt < MAX_RETRIES - 1) {
                    try {
                        Thread.sleep(RETRY_DELAY_MS * (attempt + 1));
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        // 确保在异常情况下也关闭线程池
                        shutdownAndAwaitTermination(executorService);
                        throw new ServiceException("重试过程被中断");
                    }
                }
            }
        }

        // 确保在所有重试失败时也关闭线程池
        shutdownAndAwaitTermination(executorService);
        // 如果所有重试都失败，抛出最后一次的异常
        throw new ServiceException((lastException != null ? lastException.getMessage() : "未知错误"));
    }

    // 添加线程池关闭的辅助方法
    private void shutdownAndAwaitTermination(ExecutorService pool) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown(); // 禁止新任务提交
            try {
                // 等待现有任务完成
                if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                    pool.shutdownNow(); // 取消当前执行的任务
                    // 等待任务响应关闭操作
                    if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                        System.err.println("线程池未能完全终止");
                    }
                }
            } catch (InterruptedException ie) {
                // (重新)取消如果当前线程也被中断
                pool.shutdownNow();
                // 保持中断状态
                Thread.currentThread().interrupt();
            }
        }
    }


    @Override
    public ZhishuShopGoodsVo selectShopGoodsByItemNumber(String itemNumber) {
        return baseMapper.selectShopGoodsByItemNumbers(itemNumber);
    }

    /**
     * 根据货号查询商品
     *
     * @param artNo
     * @return
     */
    @Override
    public ZhishuShopGoodsVo selectShopGoodsByArtNo(String artNo) {
        return baseMapper.selectShopGoodsByArtNo(artNo);
    }

    /**
     * 提交商品信息
     *
     * @return 商品信息
     */
    @Override
    public ProductSubmitResultVo submitProduct(ProductForm form) {
        // 书名去除首位空格
        form.setName(form.getName().trim());
        String depotName = form.getDepotName();
        if (StringUtils.isBlank(depotName)) {
            throw new IllegalArgumentException("仓库名称不能为空");
        }

        Long userId = sysUserMapper.selectUserIdByNameAndPassWord(form.getPhoneNumber());
        Long depotId = TDepotMapper.getDepotIdByName(depotName, userId);
        Long shelvesId = TShelvesMapper.getShelvesIdByName(form.getShelvesName(), depotId);
        //获取三级货区信息
        TFreightVo freightVo = TFreightMapper.selectByFreightName(form.getFreightName(), shelvesId);
        Long freightId = freightVo.getId();
        // 获取品相数值
        // 中文
        String conCodeTxt = form.getConditionCode();
        // 对应的数值
        String conCode = CnumberUtils.getQualityNum(conCodeTxt);
        // 对应的字母
        String letterCode = CnumberUtils.getQualityNum(conCode);

        if (conCode == null) {
            throw new IllegalArgumentException("无效的中文品相名称: " + conCode);
        }
        // 获取货号
        String artNo = cnumberUtils.getArtNo(Double.valueOf(new BigDecimal(conCode).divide(new BigDecimal(10)).toString()), userId, form.getBarcode(), depotId, shelvesId, freightId, form.getSeries());
        // 根据isbn 货号 userid 品相 价格 查询是否存在一样的数据
        long count = baseMapper.selectCountByIsbnAndArtNoAndUserIdAndBarcode(form.getBarcode(), artNo, userId.toString(), letterCode, form.getPrice().toString());

        ZhishuShopGoods shopGoods = new ZhishuShopGoods();


        if (count == 0) {
            // 添加库存表
            shopGoods.setIsbn(form.getBarcode());
            shopGoods.setGoodsName(form.getName());
            shopGoods.setUserId(userId);
            shopGoods.setPrice(form.getPrice());
            shopGoods.setProductId("");
            shopGoods.setConditionCode(letterCode);
            shopGoods.setDepotId(depotId);
            shopGoods.setTenantId("000000");
//            shopGoods.setCategoryId(form.getCategoryId());
            if (form.getBarcode().equals("0000000000000")) {
                shopGoods.setTemplateType("2");
            }
            shopGoods.setFixPrice(form.getFixPrice());
            shopGoods.setInventory(Long.valueOf(0));
            // 根据仓库获取Id
            shopGoods.setArtNo(artNo);
            shopGoods.setIsJoinDistribution(Integer.parseInt(StringUtils.isNotEmpty(freightVo.getAllowDistribution()) ? freightVo.getAllowDistribution() : "0"));

            baseMapper.insert(shopGoods);
            List<FilesVo> list = form.getFiles();
            if (list != null && !list.isEmpty()) {
                for (FilesVo filesVo : list) {
                    String url = filesVo.getUrl();
                    // 过滤掉临时路径
                    if (url == null || url.isEmpty()) {
                        continue;
                    }
                    // 跳过临时文件路径，只保留线上图片
                    if (url.startsWith("wxfile://") ||
                            url.startsWith("file://") ||
                            url.startsWith("blob:") ||
                            url.contains("tmp")) {
                        continue;
                    }

                    // 只插入 https 图片路径
                    if (url.startsWith("https://")) {
                        ZhishuShopImagesBo zhishuShopImagesBo = new ZhishuShopImagesBo();
                        zhishuShopImagesBo.setGoodsId(shopGoods.getId());
                        zhishuShopImagesBo.setPath(url);
                        zhishuShopImagesService.insertByBo(zhishuShopImagesBo);
                    }
                }
            }

//            List<FilesVo> list = form.getFiles();
//            for (FilesVo filesVo : list) {
//                ZhishuShopImagesBo zhishuShopImagesBo = new ZhishuShopImagesBo();
//                zhishuShopImagesBo.setGoodsId(shopGoods.getId());
//                zhishuShopImagesBo.setPath(filesVo.getUrl());
//                zhishuShopImagesService.insertByBo(zhishuShopImagesBo);
//            }
            operatingInventory(1, shopGoods.getId(), Math.toIntExact(form.getInventory()), 4, null, userId);
            shopGoods.setInventory(form.getInventory());
            if (form.getBarcode() == null) {
                // 增加商品审核
                TBookAudit tBookAudit = new TBookAudit();
                tBookAudit.setGoodsName(form.getName());
                tBookAudit.setIsbn(form.getBarcode());
                tBookAudit.setUserId(userId);
                tBookAudit.setProductId("");
                tBookAudit.setArtNo(artNo);
                tBookAudit.setPrice(form.getPrice());
                tBookAudit.setFixPrice(form.getFixPrice());
                tBookAudit.setConditionCode(letterCode);
                tBookAudit.setInventory(Long.valueOf(form.getInventory()));
                tBookAudit.setTenantId("000000");
                tBookAudit.setStatus("2");
                tBookAuditMapper.insert(tBookAudit);
            }
        } else if (count > 0) {
            ZhishuShopGoods existingGoods = baseMapper.selectartNoByIsbnAndConditionCodeAndArtNo(form.getBarcode(), letterCode, artNo, form.getPrice(), userId);
            // 价格相同 修改
            long newInventory = existingGoods.getInventory() + form.getInventory();
            shopGoods.setId(existingGoods.getId());
            List<FilesVo> list = form.getFiles();
            for (FilesVo filesVo : list) {
                ZhishuShopImagesBo zhishuShopImagesBo = new ZhishuShopImagesBo();
                zhishuShopImagesBo.setGoodsId(shopGoods.getId());
                zhishuShopImagesBo.setPath(filesVo.getUrl());
                zhishuShopImagesService.insertByBo(zhishuShopImagesBo);
            }
            operatingInventory(1, shopGoods.getId(), Math.toIntExact(form.getInventory()), 4, null, userId);
            shopGoods.setInventory(newInventory);
            tBookAuditMapper.updateInventory(newInventory, userId, letterCode, artNo, form.getPrice(), form.getBarcode());
        }



        /**
         * 执行孔夫子店铺自动发布商品线程
         */
        //赋值分类
        shopGoods.setCategoryId(form.getCategoryId());
        shopGoods.setDepotId(depotId);
        shopGoods.setPrice(form.getPrice());
        TDepotVo depotVo = depotService.queryById(depotId);
        TLogisticsVo logisticsVo = logisticsService.queryById(depotVo.getTemplateId());
        if (logisticsVo == null) {
            shopGoods.setTemplateMinPrice("0");
        } else {
            shopGoods.setTemplateMinPrice(logisticsVo.getFirPrice() == null ? "0" : logisticsVo.getFirPrice().toString());
        }

        System.out.println("shopGoods:" + shopGoods);
        TShopDepotAotuMapper tShopDepotAotuMapper = applicationContext.getBean(TShopDepotAotuMapper.class);
        KfzAutoAddRunnable kfzAutoAddRunnable = new KfzAutoAddRunnable(userId,
                shopService,
                shopDetailService,
                shopGoodsPublishedService,
                kongfzService,
                this,
                applicationContext,
                zhishuShopGoodsDetailService,
                shopGoods,
                tShopDepotAotuMapper);
        Thread thread = new Thread(kfzAutoAddRunnable, "yxy-submitFromCopyrightPage");
        thread.setDaemon(true); // 设置为守护线程
        thread.start();
        // 创建返回对象
        ProductSubmitResultVo result = new ProductSubmitResultVo();
        result.setGoodsId(shopGoods.getId());
        result.setUserId(userId);
        result.setDepotId(depotId);
        result.setShelvesId(shelvesId);
        result.setFreightId(freightId);
        result.setArtNo(artNo);

        return result;
    }


    /**
     * 上传商品照片
     *
     * @param photos 照片文件列表
     * @return 商品信息
     */
    @Override
    public void uploadPhotos(MultipartFile[] photos) {
        // 确保上传目录存在
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            try {
                Files.createDirectories(uploadPath);
            } catch (IOException e) {
                throw new RuntimeException("无法创建上传目录", e);
            }
        }

        // 遍历照片文件并保存
        for (MultipartFile photo : photos) {
            if (photo.isEmpty()) {
                continue; // 跳过空文件
            }

            try {
                // 生成唯一文件名
                String fileName = System.currentTimeMillis() + "_" + photo.getOriginalFilename();
                Path filePath = uploadPath.resolve(fileName);

                // 保存文件
                Files.copy(photo.getInputStream(), filePath);
                System.out.println("照片已保存：" + filePath);
            } catch (IOException e) {
                throw new RuntimeException("照片保存失败", e);
            }
        }
    }

    /**
     * 分页查询商品信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商品信息分页列表
     */
    @Override
    public TableDataInfo<ZhishuShopGoodsVo> queryPageList(ZhishuShopGoodsBo bo, PageQuery pageQuery) {
        Long userId;
        if(bo.getIsQueryAllGoods() != null && bo.getIsQueryAllGoods() == 2){
            bo.setIsJoinDistribution(1);
        }
        if(bo.getIsQueryAllGoods() == 2 && StringUtils.isNotEmpty(bo.getWarehouseUserId())){
            //修改为单独查一个仓库
            userId = Long.parseLong(bo.getWarehouseUserId());
            bo.setIsQueryAllGoods(1);
        }else{
            userId = LoginHelper.getUserId();
        }

        // 小程序传递的userId
        if (userId == null) {
            // 这里假设bo中有getUserId方法，如果没有需要根据实际情况调整
            if (bo.getUserId() != null) {
                userId = bo.getUserId();
            }
        }

        bo.setUserId(userId);
        // 动态拼接查询条件
        LambdaQueryWrapper<ZhishuShopGoods> lqw = buildQueryWrapper(bo);

        // 获取当前用户id
        Page<ZhishuShopGoodsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(item -> {
            if (item.getBookPic() == null) {
                String path = baseMapper.selectByBookPic(item.getId());
                if (StringUtils.isNotEmpty(path) && !path.contains("wxfile")) {
                    item.setBookPic(path);
                } else {
                    item.setBookPic("");
                }
            }
        });
        // 若查询条件不为空构建响应参数
        if (ObjectUtil.isNotEmpty(result.getRecords())) {
            // 根据UserId查询用户电话号码
            List<Long> userIdList = result.getRecords().stream().map(ZhishuShopGoodsVo::getUserId).distinct().toList();
            Map<Long, Map<String,String>> userPhoneNumberMap = new LambdaQueryChainWrapper<>(sysUserMapper)
                    .in(SysUser::getUserId, userIdList)
                    .list().stream().collect(Collectors.toMap(SysUser::getUserId, user -> {
                        Map<String, String> info = new HashMap<>();
                        info.put("phonenumber", user.getPhonenumber());
                        info.put("warehouseName", user.getWarehouseName() == null ? "" : user.getWarehouseName());
                        return info;
                    }));
            // 根据depotId查询仓库名称
            List<Long> depotIdList = result.getRecords().stream().map(ZhishuShopGoodsVo::getDepotId).distinct().toList();
            List<TDepot> depotList = new LambdaQueryChainWrapper<>(TDepotMapper).in(TDepot::getId, depotIdList).list();
            Map<Long, TDepot> depotMap = new HashMap<>();
            if (ObjectUtil.isNotEmpty(depotList)) {
                for (TDepot tDepot : depotList) {
                    tDepot.setName(tDepot.getName() + tDepot.getUnit());
                    depotMap.put(tDepot.getId(), tDepot);
                }
            }
            List<Long> templateIdList = depotList.stream().map(TDepot::getTemplateId).distinct().toList();
            // 根据仓库id查询物流信息
            Map<Long, TLogistics> logisticsMap = new HashMap<>();
            if (ObjectUtil.isNotEmpty(templateIdList)) {
                List<TLogistics> logisticsList = new LambdaQueryChainWrapper<>(tLogisticsMapper).in(TLogistics::getId, templateIdList).list();
                if (ObjectUtil.isNotEmpty(logisticsList)) {
                    for (TLogistics tLogistics : logisticsList) {
                        logisticsMap.put(tLogistics.getId(), tLogistics);
                    }

                }
            }

            // 循环赋值
            for (ZhishuShopGoodsVo record : result.getRecords()) {
                // 电话打码
                if (ObjectUtil.isNotEmpty(userPhoneNumberMap)) {
                    Map<String,String> userMap = userPhoneNumberMap.get(record.getUserId());
                    String phoneNumber = userMap.get("phonenumber");
                    String warehouseName = userMap.get("warehouseName");
                    if (ObjectUtil.isNotEmpty(phoneNumber)) {
                        String phoneNumberMark = EncryptionUtil.maskPhoneNumber(Long.valueOf(phoneNumber));
                        record.setPhoneNumberMark(phoneNumberMark);
                    }
                    if (StringUtils.isNotEmpty(warehouseName)){
                        record.setWarehouseName(warehouseName);
                    }
                }
                // // 商品Id打码
                // if (!userId.equals(record.getUserId())) {
                //     record.setId(EncryptionUtil.maskString(record.getId()));
                // }
                record.setUserId(null);
                // 品相转换
                record.setConditionCode(CHINESE_TO_CODE_MAP2.get(record.getConditionCode()));
                // 价格转换
                // 除于100后保留两位小数
                record.setPrice(record.getPrice());
                if (ObjectUtil.isNotEmpty(depotMap)) {
                    TDepot tDepot = depotMap.get(record.getDepotId());
                    if (ObjectUtil.isNotEmpty(tDepot) && ObjectUtil.isNotNull(tDepot)) {
                        // 赋值仓库名称
                        record.setDepotName(tDepot.getName());

                        // 赋值模板名称，详细地址，最低价格
                        if (ObjectUtil.isNotEmpty(logisticsMap)) {

                            TLogistics tLogistics = logisticsMap.get(tDepot.getTemplateId());
                            if (ObjectUtil.isNotEmpty(tLogistics)) {
                                // 赋值模板名称
                                record.setTemplateName(tLogistics.getTemplateName());
                                // 赋值模板Id
                                record.setTemplateId(tLogistics.getId());
                                if (ObjectUtil.isNotEmpty(tLogistics.getShippingRange())) {
                                    // 赋值详细地址
                                    String split = tLogistics.getDeliveryAddress().split("/")[0];
                                    record.setDeliveryAddress(split);
                                    // 赋值最低价格
                                    ObjectMapper objectMapper = new ObjectMapper();

                                    // 将 JSON 转换为 Map<String, List<String>>
                                    Map<String, List<String>> regionMap = null;
                                    try {
                                        regionMap = objectMapper.readValue(tLogistics.getShippingRange(), Map.class);
                                    } catch (JsonProcessingException e) {
                                        throw new ServiceException("解析模板运送范围失败", 555);
                                    }
                                    if (ObjectUtil.isNotEmpty(regionMap)) {
                                        List<BigDecimal> priceList = new ArrayList<>();
                                        // 遍历 Map 并修改每个列表中的第二个元素
                                        for (Map.Entry<String, List<String>> entry : regionMap.entrySet()) {
                                            List<String> list = entry.getValue();
                                            String strValue = String.valueOf(list.get(1));
                                            priceList.add(new BigDecimal(strValue));
                                        }
                                        BigDecimal minPrice = Collections.min(priceList);
                                        record.setPricingMethod(tLogistics.getPricingMethod());
                                        record.setTemplateMinPrice(minPrice);
                                    }
                                }

                            }
                        }
                    }

                }

            }
        }
        return TableDataInfo.build(result);
    }


    public Page<ZhishuShopGoodsVo> queryPageList2(ZhishuShopGoodsBo bo, PageQuery pageQuery) {
        // 动态拼接查询条件
        LambdaQueryWrapper<ZhishuShopGoods> lqw = buildQueryWrapper(bo);
        // 获取当前用户id
        Page<ZhishuShopGoodsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        // 若查询条件不为空构建响应参数
        if (ObjectUtil.isNotEmpty(result.getRecords())) {
            // 根据UserId查询用户电话号码
            List<Long> userIdList = result.getRecords().stream().map(ZhishuShopGoodsVo::getUserId).distinct().toList();
            Map<Long, String> userPhoneNumberMap = new LambdaQueryChainWrapper<>(sysUserMapper)
                    .in(SysUser::getUserId, userIdList)
                    .list().stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getPhonenumber));
            // 根据depotId查询仓库名称
            List<Long> depotIdList = result.getRecords().stream().map(ZhishuShopGoodsVo::getDepotId).distinct().toList();
            List<TDepot> depotList = new LambdaQueryChainWrapper<>(TDepotMapper).in(TDepot::getId, depotIdList).list();
            Map<Long, TDepot> depotMap = new HashMap<>();
            if (ObjectUtil.isNotEmpty(depotList)) {
                for (TDepot tDepot : depotList) {
                    tDepot.setName(tDepot.getName() + tDepot.getUnit());
                    depotMap.put(tDepot.getId(), tDepot);
                }
            }
            List<Long> templateIdList = depotList.stream().map(TDepot::getTemplateId).distinct().toList();
            // 根据仓库id查询物流信息
            Map<Long, TLogistics> logisticsMap = new HashMap<>();
            if (ObjectUtil.isNotEmpty(templateIdList)) {
                List<TLogistics> logisticsList = new LambdaQueryChainWrapper<>(tLogisticsMapper).in(TLogistics::getId, templateIdList).list();
                if (ObjectUtil.isNotEmpty(logisticsList)) {
                    for (TLogistics tLogistics : logisticsList) {
                        logisticsMap.put(tLogistics.getId(), tLogistics);
                    }

                }
            }

            // 循环赋值
            for (ZhishuShopGoodsVo record : result.getRecords()) {
                // 电话打码
                if (ObjectUtil.isNotEmpty(userPhoneNumberMap)) {
                    String phoneNumber = userPhoneNumberMap.get(record.getUserId());
                    if (ObjectUtil.isNotEmpty(phoneNumber)) {
                        String phoneNumberMark = EncryptionUtil.maskPhoneNumber(Long.valueOf(phoneNumber));
                        record.setPhoneNumberMark(phoneNumberMark);
                    }
                }
                record.setUserId(null);
                // 品相转换
                record.setConditionCode(CHINESE_TO_CODE_MAP2.get(record.getConditionCode()));
                // 价格转换
                // 除于100后保留两位小数
                record.setPrice(record.getPrice());
                if (ObjectUtil.isNotEmpty(depotMap)) {
                    TDepot tDepot = depotMap.get(record.getDepotId());
                    if (ObjectUtil.isNotEmpty(tDepot) && ObjectUtil.isNotNull(tDepot)) {
                        // 赋值仓库名称
                        record.setDepotName(tDepot.getName());

                        // 赋值模板名称，详细地址，最低价格
                        if (ObjectUtil.isNotEmpty(logisticsMap)) {

                            TLogistics tLogistics = logisticsMap.get(tDepot.getTemplateId());
                            if (ObjectUtil.isNotEmpty(tLogistics)) {
                                // 赋值模板名称
                                record.setTemplateName(tLogistics.getTemplateName());
                                // 赋值模板Id
                                record.setTemplateId(tLogistics.getId());
                                if (ObjectUtil.isNotEmpty(tLogistics.getShippingRange())) {
                                    // 赋值详细地址
                                    String split = tLogistics.getDeliveryAddress().split("/")[0];
                                    record.setDeliveryAddress(split);
                                    // 赋值最低价格
                                    ObjectMapper objectMapper = new ObjectMapper();

                                    // 将 JSON 转换为 Map<String, List<String>>
                                    Map<String, List<String>> regionMap = null;
                                    try {
                                        regionMap = objectMapper.readValue(tLogistics.getShippingRange(), Map.class);
                                    } catch (JsonProcessingException e) {
                                        throw new ServiceException("解析模板运送范围失败", 555);
                                    }
                                    if (ObjectUtil.isNotEmpty(regionMap)) {
                                        List<BigDecimal> priceList = new ArrayList<>();
                                        // 遍历 Map 并修改每个列表中的第二个元素
                                        for (Map.Entry<String, List<String>> entry : regionMap.entrySet()) {
                                            List<String> list = entry.getValue();
                                            String strValue = String.valueOf(list.get(1));
                                            priceList.add(new BigDecimal(strValue));
                                        }
                                        BigDecimal minPrice = Collections.min(priceList);
                                        record.setPricingMethod(tLogistics.getPricingMethod());
                                        record.setTemplateMinPrice(minPrice);
                                    }
                                }

                            }
                        }
                    }

                }

            }
        }
        return result;
    }

    /**
     * 查询符合条件的商品信息列表
     *
     * @param bo 查询条件
     * @return 商品信息列表
     */
    @Override
    public List<ZhishuShopGoodsVo> queryList(ZhishuShopGoodsBo bo) {
        if (bo.getUserId() == null){
            Long userId = LoginHelper.getUserId();
            bo.setUserId(userId);
        }
        LambdaQueryWrapper<ZhishuShopGoods> lqw = buildQueryWrapper(bo);
        List<ZhishuShopGoodsVo> list = baseMapper.selectVoList(lqw);
        // 若查询条件不为空构建响应参数
        if (ObjectUtil.isNotEmpty(list)) {
            // 根据depotId查询仓库名称
            List<Long> depotIdList = list.stream().map(ZhishuShopGoodsVo::getDepotId).distinct().toList();
            List<TDepot> depotList = new LambdaQueryChainWrapper<>(TDepotMapper).in(TDepot::getId, depotIdList).list();
            Map<Long, String> depotNameMap = depotList.stream().collect(Collectors.toMap(TDepot::getId, TDepot::getName));
            List<Long> templateIdList = depotList.stream().map(TDepot::getTemplateId).distinct().toList();
            // 根据仓库id查询物流信息
            Map<Long, TLogistics> logisticsMap = new HashMap<>();
            if (ObjectUtil.isNotEmpty(templateIdList)) {
                List<TLogistics> logisticsList = new LambdaQueryChainWrapper<>(tLogisticsMapper).in(TLogistics::getId, templateIdList).list();
                if (ObjectUtil.isNotEmpty(logisticsList)) {
                    for (TLogistics tLogistics : logisticsList) {
                        logisticsMap.put(tLogistics.getWarehouseId(), tLogistics);
                    }
                }
            }

            // 循环赋值
            for (ZhishuShopGoodsVo record : list) {
                // 品相转换
                record.setConditionCode(CHINESE_TO_CODE_MAP2.get(record.getConditionCode()));
                // 价格转换
                record.setPrice(record.getPrice().divide(new BigDecimal(100)));

                // 赋值仓库名称
                if (ObjectUtil.isNotEmpty(depotNameMap)) {
                    record.setDepotName(depotNameMap.get(record.getDepotId()));
                }
                // 赋值模板名称，详细地址，最低价格
                if (ObjectUtil.isNotEmpty(logisticsMap)) {
                    TLogistics tLogistics = logisticsMap.get(record.getDepotId());
                    if (ObjectUtil.isNotEmpty(tLogistics)) {
                        // 赋值模板名称
                        record.setTemplateName(tLogistics.getTemplateName());
                        // 赋值模板Id
                        record.setTemplateId(tLogistics.getId());
                        if (ObjectUtil.isNotEmpty(tLogistics.getShippingRange())) {
                            // 赋值详细地址
                            record.setDeliveryAddress(tLogistics.getDeliveryAddress());
                            // 赋值最低价格
                            ObjectMapper objectMapper = new ObjectMapper();

                            // 将 JSON 转换为 Map<String, List<String>>
                            Map<String, List<String>> regionMap = null;
                            try {
                                regionMap = objectMapper.readValue(tLogistics.getShippingRange(), Map.class);
                            } catch (JsonProcessingException e) {
                                throw new ServiceException("解析模板运送范围失败", 555);
                            }
                            if (ObjectUtil.isNotEmpty(regionMap)) {
                                List<BigDecimal> priceList = new ArrayList<>();
                                // 遍历 Map 并修改每个列表中的第二个元素
                                for (Map.Entry<String, List<String>> entry : regionMap.entrySet()) {
                                    List<String> regionMaplist = entry.getValue();
                                    priceList.add(new BigDecimal(regionMaplist.get(2)));
                                }
                                BigDecimal minPrice = Collections.min(priceList);
                                record.setPricingMethod(tLogistics.getPricingMethod());
                                record.setTemplateMinPrice(minPrice);
                            }
                        }

                    }
                }
            }
        }
        return list;
    }

    private LambdaQueryWrapper<ZhishuShopGoods> buildQueryWrapper(ZhishuShopGoodsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZhishuShopGoods> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(ZhishuShopGoods::getCreateTime);
//        lqw.orderByAsc(ZhishuShopGoods::getId);
        // 若不是查询所有商品，则拼接用id过滤
        if (IsQueryAllGoodsEnum.NO.getCode().equals(bo.getIsQueryAllGoods())) {
            // 用户Id
            lqw.eq(ObjectUtil.isNotEmpty(bo.getUserId()), ZhishuShopGoods::getUserId, bo.getUserId());
        } else {
            // 查询所有商品
            lqw.and(wrapper -> wrapper
                    .eq(ObjectUtil.isNotEmpty(bo.getUserId()), ZhishuShopGoods::getUserId, bo.getUserId())
                    .or()
                    .eq(ZhishuShopGoods::getIsJoinDistribution, IsJoinDistributionEnum.YES.getCode()));
        }
        // 是否分销
        lqw.eq(ObjectUtil.isNotEmpty(bo.getIsJoinDistribution()), ZhishuShopGoods::getIsJoinDistribution, bo.getIsJoinDistribution());
        // 管理员可以查看所有数据
        //  if (bo.getUserId()  != null && !Long.valueOf(1).equals(bo.getUserId()))  {
        //      lqw.eq(ZhishuShopGoods::getUserId, bo.getUserId());
        //  }
        // 商品名称
        lqw.like(StringUtils.isNotBlank(bo.getGoodsName()), ZhishuShopGoods::getGoodsName, bo.getGoodsName());
        // 货号
        lqw.like(StringUtils.isNotBlank(bo.getArtNo()), ZhishuShopGoods::getArtNo, bo.getArtNo());


        // 图片是否为空
        if (ObjectUtil.isNotNull(bo.getIsBookPicNull())) {
            List<ZhishuShopImages> zhishuShopImages = baseMapper.selectImages();
//             2. 根据查询条件处理
            if (bo.getIsBookPicNull() == 0) {
                // 情况1：要求无图（记录不存在或path为空）
                if (!zhishuShopImages.isEmpty()) {
                    // 排除fistImage中有图片路径的
                    List<String> goodsIds = zhishuShopImages.stream()
                            .filter(image -> StringUtils.isNotEmpty(image.getPath()))
                            .map(ZhishuShopImages::getGoodsId)
                            .toList();
                    lqw.notIn(ZhishuShopGoods::getId, goodsIds);
                } else {
                    lqw.eq(ZhishuShopGoods::getId, -1);
                }
            } else {
                // 情况2：要求有图（path不为空）
                if (!zhishuShopImages.isEmpty()) {
                    List<String> goodsIds = zhishuShopImages.stream()
                            .filter(image -> StringUtils.isNotEmpty(image.getPath()))
                            .map(ZhishuShopImages::getGoodsId)
                            .toList();
                    lqw.in(ZhishuShopGoods::getId, goodsIds);
                } else {
                    lqw.eq(ZhishuShopGoods::getId, -1);
                }
            }
        }


        // 原始货号
        lqw.like(StringUtils.isNotBlank(bo.getOriginalArtNo()), ZhishuShopGoods::getOriginalArtNo, bo.getOriginalArtNo());

        if (StringUtils.isNotEmpty(bo.getMinprice()) && bo.getMaxprice() != null) {
            String operator = bo.getMinprice();
            Long price = new BigDecimal(bo.getMaxprice()).multiply(new BigDecimal(100)).longValue();
            switch (operator) {
                case "=":
                    lqw.eq(ZhishuShopGoods::getPrice, price);
                    break;
                case ">":
                    lqw.gt(ZhishuShopGoods::getPrice, price); // 使用 gt 而不是 ge
                    break;
                case ">=":
                    lqw.ge(ZhishuShopGoods::getPrice, price);
                    break;
                case "<":
                    lqw.lt(ZhishuShopGoods::getPrice, price); // 使用 lt 而不是 le
                    break;
                case "<=":
                    lqw.le(ZhishuShopGoods::getPrice, price);
                    break;
                default:
                    break;
            }
        }

//        // 最低价格
//        Optional.ofNullable(bo.getMinprice()).map(price -> price * 100).ifPresent(value -> lqw.ge(ZhishuShopGoods::getPrice, value));
//        // 最高价格
//        Optional.ofNullable(bo.getMaxprice()).map(price -> price * 100).ifPresent(value -> lqw.le(ZhishuShopGoods::getPrice, value));
//        // 最低库存
//        lqw.ge(ObjectUtil.isNotNull(bo.getMininventory()), ZhishuShopGoods::getInventory, bo.getMininventory());
//        // 最高库存
//        lqw.le(ObjectUtil.isNotNull(bo.getMaxinventory()), ZhishuShopGoods::getInventory, bo.getMaxinventory());

        if (StringUtils.isNotEmpty(bo.getMininventory()) && bo.getMaxinventory() != null) {
            String operator = bo.getMininventory();
            Long inventory = bo.getMaxinventory();
            switch (operator) {
                case "=":
                    lqw.eq(ZhishuShopGoods::getInventory, inventory);
                    break;
                case ">":
                    lqw.gt(ZhishuShopGoods::getInventory, inventory); // 使用 gt 而不是 ge
                    break;
                case ">=":
                    lqw.ge(ZhishuShopGoods::getInventory, inventory);
                    break;
                case "<":
                    lqw.lt(ZhishuShopGoods::getInventory, inventory); // 使用 lt 而不是 le
                    break;
                case "<=":
                    lqw.le(ZhishuShopGoods::getInventory, inventory);
                    break;
                default:
                    break;
            }
        }


        // 商品编号
        lqw.eq(StringUtils.isNotBlank(bo.getItemNumber()), ZhishuShopGoods::getProductId, bo.getItemNumber());

        // ISBN
        if (StringUtils.isNotBlank(bo.getIsbn()) || bo.getIsExistIsbn() != null) {
            if (bo.getIsExistIsbn() != null) {
                if (bo.getIsExistIsbn() == 0) {
                    // 情况1：isExistIsbn=0
                    if (StringUtils.isNotBlank(bo.getIsbn())) {
                        if (bo.getIsbn().startsWith("678")) {
                            lqw.likeRight(ZhishuShopGoods::getIsbn, bo.getIsbn());
                        } else {
                            // 不符合678开头的条件，返回空结果
                            lqw.eq(ZhishuShopGoods::getId, -1);
                        }
                    } else {
                        // 默认查询678开头的记录
                        lqw.likeRight(ZhishuShopGoods::getIsbn, "678");
                    }
                } else {
                    // 情况2：isExistIsbn=1，查询不以678开头的记录
                    lqw.notLikeRight(ZhishuShopGoods::getIsbn, "0")
                            .notLikeRight(ZhishuShopGoods::getIsbn, "1")
                            .notLikeRight(ZhishuShopGoods::getIsbn, "4")
                            .notLikeRight(ZhishuShopGoods::getIsbn, "5")
                            .notLikeRight(ZhishuShopGoods::getIsbn, "6")
                            .notLikeRight(ZhishuShopGoods::getIsbn, "8")
                            .eq(StringUtils.isNotBlank(bo.getIsbn()), ZhishuShopGoods::getIsbn, bo.getIsbn());
                }
            } else {
                // 情况3：isExistIsbn=null，精确查询
                lqw.eq(ZhishuShopGoods::getIsbn, bo.getIsbn());
            }
        }

        // 品相
        if (StringUtils.isNotBlank(bo.getConditionCode())) {
//            String conditionCode = CHINESE_TO_CODE_MAP1.get(bo.getConditionCode());
//            Assert.isTrue(ObjectUtil.isNotEmpty(conditionCode), "没有对应品级");
            lqw.eq(ZhishuShopGoods::getConditionCode, bo.getConditionCode());
        }
        // 仓库名称 仓库Id
        if (ObjectUtil.isNotNull(bo.getDepotId()) || ObjectUtil.isNotEmpty(bo.getDepotName())) {



            List<TDepot> depotList = new LambdaQueryChainWrapper<>(TDepotMapper).eq(ObjectUtil.isNotNull(bo.getDepotId()), TDepot::getId, bo.getDepotId()).like(ObjectUtil.isNotEmpty(bo.getDepotName()), TDepot::getName, bo.getDepotName()).list();
            if (ObjectUtil.isNotEmpty(depotList)) {
                List<Long> depotIds = depotList.stream().map(TDepot::getId).toList();
                lqw.in(ZhishuShopGoods::getDepotId, depotIds);
            }
        }
        // 模板名称 模板Id 详细地址
        if (ObjectUtil.isNotNull(bo.getTemplateId()) || ObjectUtil.isNotEmpty(bo.getTemplateName())) {
            List<TLogistics> logisticsList = new LambdaQueryChainWrapper<>(tLogisticsMapper).eq(ObjectUtil.isNotNull(bo.getTemplateId()), TLogistics::getId, bo.getTemplateId()).like(ObjectUtil.isNotEmpty(bo.getTemplateName()), TLogistics::getTemplateName, bo.getTemplateName()).like(ObjectUtil.isNotEmpty(bo.getAddress()), TLogistics::getDeliveryAddress, bo.getAddress()).list();
            if (ObjectUtil.isNotEmpty(logisticsList)) {
                List<Long> warehouseId = logisticsList.stream().map(TLogistics::getWarehouseId).toList();
                lqw.in(ZhishuShopGoods::getDepotId, warehouseId);
            }
        }


        // 货区ids列表
        if (ObjectUtil.isNotEmpty(bo.getCargoAreaIds())) {
            Integer cargoAreaId = bo.getCargoAreaIds().size();
            ArrayList<String> ids = new ArrayList<>();
            List<ZhishuShopGoods> zhishuShopGoodsList = new LambdaQueryChainWrapper<>(baseMapper).eq(ObjectUtil.isNotNull(bo.getCargoAreaIds()), ZhishuShopGoods::getDepotId, bo.getCargoAreaIds().get(0)).list();
            if (ObjectUtil.isNotEmpty(zhishuShopGoodsList)) {
                List<TDepot> depotList = new LambdaQueryChainWrapper<>(TDepotMapper).eq(ObjectUtil.isNotNull(bo.getCargoAreaIds()), TDepot::getId, bo.getCargoAreaIds().get(0)).list();
                if (ObjectUtil.isNotEmpty(depotList)) {
                    if (cargoAreaId == 1) {
                        List<Long> depotIds = depotList.stream().map(TDepot::getId).toList();
                        lqw.in(ZhishuShopGoods::getDepotId, depotIds);
                    } else if (cargoAreaId == 2) {
                        List<TShelves> shelvesList = new LambdaQueryChainWrapper<>(TShelvesMapper).eq(ObjectUtil.isNotNull(bo.getCargoAreaIds()), TShelves::getId, bo.getCargoAreaIds().get(1)).list();
                        if (ObjectUtil.isNotEmpty(shelvesList)) {
                            // 获取depotList中的code
                            List<String> depotCodes = depotList.stream().map(TDepot::getCode).toList();
                            // 获取shelvesList中的code
                            List<String> sheCodes = shelvesList.stream().map(TShelves::getCode).toList();
                            String depotCode = depotCodes.get(0) + sheCodes.get(0);
                            // 判断zhishuShopGoodsList中的artNo的前缀是否包含depotCode
                            for (ZhishuShopGoods item : zhishuShopGoodsList) {
                                if (item.getArtNo().startsWith(depotCode)) {
                                    ids.add(item.getId());
                                }
                            }
                            if (ids.isEmpty()) {
                                lqw.eq(ZhishuShopGoods::getDepotId, -1);
                            } else {
                                lqw.in(ZhishuShopGoods::getId, ids);
                            }
                        } else {
                            lqw.eq(ZhishuShopGoods::getDepotId, -1);
                        }
                    } else if (cargoAreaId == 3) {
                        List<TShelves> shelvesList = new LambdaQueryChainWrapper<>(TShelvesMapper).eq(ObjectUtil.isNotNull(bo.getCargoAreaIds()), TShelves::getId, bo.getCargoAreaIds().get(1)).list();
                        List<TFreight> freightList = new LambdaQueryChainWrapper<>(TFreightMapper).eq(ObjectUtil.isNotNull(bo.getCargoAreaIds()), TFreight::getId, bo.getCargoAreaIds().get(2)).list();
                        if (ObjectUtil.isNotEmpty(shelvesList) && ObjectUtil.isNotEmpty(freightList)) {
                            // 获取depotList中的code
                            List<String> depotCodes = depotList.stream().map(TDepot::getCode).toList();
                            // 获取shelvesList中的code
                            List<String> sheCodes = shelvesList.stream().map(TShelves::getCode).toList();
                            // 获取freightList中的code
                            List<String> freCodes = freightList.stream().map(TFreight::getCode).toList();
                            String depotCode = depotCodes.get(0) + sheCodes.get(0) + freCodes.get(0);
                            // 判断zhishuShopGoodsList中的artNo的前缀是否包含depotCode
                            for (ZhishuShopGoods item : zhishuShopGoodsList) {
                                if (item.getArtNo().startsWith(depotCode)) {
                                    ids.add(item.getId());
                                }
                            }
                            if (ids.isEmpty()) {
                                lqw.eq(ZhishuShopGoods::getDepotId, -1);
                            } else {
                                lqw.in(ZhishuShopGoods::getId, ids);
                            }
                        } else {
                            lqw.eq(ZhishuShopGoods::getDepotId, -1);
                        }
                    }
                } else {
                    lqw.eq(ZhishuShopGoods::getDepotId, -1);
                }
            } else {
                lqw.eq(ZhishuShopGoods::getDepotId, -1);
            }
        }

        // 发货地址
        if (ObjectUtil.isNotNull(bo.getAddress())) {
            List<TLogistics> logisticsList = new LambdaQueryChainWrapper<>(tLogisticsMapper).eq(ObjectUtil.isNotNull(bo.getAddress()), TLogistics::getDeliveryProvince, bo.getAddress()).list();
            if (ObjectUtil.isNotEmpty(logisticsList)) {
                List<Long> depotIds = new ArrayList<>();
                for (TLogistics item : logisticsList) {
                    List<TDepot> depotList = new LambdaQueryChainWrapper<>(TDepotMapper)
                            .eq(TDepot::getTemplateId, item.getId())
                            .list();
                    depotIds.addAll(depotList.stream().map(TDepot::getId).toList());
                }

                if (ObjectUtil.isNotEmpty(depotIds)) {
                    lqw.in(ZhishuShopGoods::getDepotId, depotIds);
                } else {
                    // 如果没有匹配的仓库，直接返回空结果
                    lqw.eq(ZhishuShopGoods::getId, -1);
                }
            } else {
                // 如果没有匹配的物流信息，直接返回空结果
                lqw.eq(ZhishuShopGoods::getId, -1);
            }
        }

        // 添加入库时间比较
        if (ObjectUtil.isNotNull(bo.getStartTime()) && ObjectUtil.isNotNull(bo.getEndTime())) {
            lqw.between(ZhishuShopGoods::getCreateTime, bo.getStartTime(), bo.getEndTime());
        } else if (ObjectUtil.isNotNull(bo.getStartTime())) {
            // 只有开始时间，查询该时间之后的数据
            lqw.ge(ZhishuShopGoods::getCreateTime, bo.getStartTime());
        } else if (ObjectUtil.isNotNull(bo.getEndTime())) {
            // 只有结束时间，查询该时间之前的数据
            lqw.le(ZhishuShopGoods::getCreateTime, bo.getEndTime());
        }


        return lqw;
    }


    public static final Map<String, String> CHINESE_TO_CODE_MAP2 = IntStream.range(0, CHINESE_CODE.length).boxed().collect(Collectors.toMap(i -> CONDITION_CODE[i],  // 值：字母标识（如"A"）
            i -> CHINESE_CODE[i],  // 键：中文标识（如"一品"）
            (oldVal, newVal) -> oldVal, LinkedHashMap::new       // 保持插入顺序
    ));

    /**
     * 新增商品信息
     *
     * @param bo 商品信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ZhishuShopGoodsBo bo) {
        validEntityBeforeSave(bo);
        ZhishuShopGoods add = MapstructUtils.convert(bo, ZhishuShopGoods.class);
        Long userId = LoginHelper.getUserId();
        add.setUserId(userId);
        add.setProductId("");
//        if (add.getFixPrice() != null) {
//            add.setFixPrice(add.getFixPrice() * 100);
//        }
//        if (add.getPrice() != null) {
//            add.setPrice(add.getPrice() * 100);
//        }
        add.setConditionCode(CHINESE_TO_CODE_MAP1.get(add.getConditionCode()));
        Double s = convertChineseToCode(bo.getConditionCode());
        List<TShelves> sheCount = baseMapper.selectSheCount(bo.getDepotId());
        if (sheCount.size() == 0) {
            throw new RuntimeException("二级货区不存在,请先创建二级货区");
        }
        List<TFreight> freCount = baseMapper.selectFreCount1(sheCount);
        if (freCount.size() == 0) {
            throw new RuntimeException("三级货区不存在,请创建三级货区");
        }
        Map<Long, Long> map = new HashMap<>();
        sheCount.forEach(she -> {
            // 跳过无效code长度（非1位或2位）
            if (she.getCode().length() != 1 && she.getCode().length() != 2) {
                return; // 在forEach中相当于continue
            }
            List<TFreight> tFreight = baseMapper.selectBySId(she.getId());
            if (tFreight == null) {
                return; // 跳过空数据
            }
            for (int i = 0; i < tFreight.size(); i++) {
                if (tFreight.get(i).getCode() == null) {
                    return; // 跳过空数据
                }
                // 核心匹配逻辑
                if ((she.getCode().length() == 2 && tFreight.get(i).getCode().length() == 1) || (she.getCode().length() == 1 && tFreight.get(i).getCode().length() == 2)) {
                    map.put(tFreight.get(i).getId(), she.getId());
                }
            }
        });
        if (map.isEmpty()) {
            return false;
        }
        Long sheId = null;
        Long freId = null;
        // 1. 转换为可随机访问的Entry集合
        List<Map.Entry<Long, Long>> entries = new ArrayList<>(map.entrySet());
        // 2. 线程安全随机选择（Java 8+）
        if (!entries.isEmpty()) {
            Map.Entry<Long, Long> randomEntry = entries.get(ThreadLocalRandom.current().nextInt(entries.size()));
            freId = randomEntry.getKey();
            sheId = randomEntry.getValue();
        }


        String artNo = cnumberUtils.getArtNo(s, userId, bo.getIsbn(), bo.getDepotId(), sheId, freId, null);
        add.setArtNo(artNo);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }


    //    @Override
    public void insertByBo1(ZhishuShopGoodsBo bo,String type) {
        validEntityBeforeSave(bo);
        ZhishuShopGoods add = MapstructUtils.convert(bo, ZhishuShopGoods.class);
        add.setConditionCode(CHINESE_TO_CODE_MAP1.get(add.getConditionCode()));
        add.setPrice(add.getPrice() * 100);
        if (add.getIsbn() == null) {
            boolean flag = baseMapper.insert(add) > 0;
        } else {
            add.setProductId("");
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
        }

        //修改成功后，记录自营书品库存修改表
        StockChangeLog stockChangeLog = new StockChangeLog();
        stockChangeLog.setShopGoodsId(Long.parseLong(add.getId()));
        //类型  2-订单减扣 3-退单添加
        stockChangeLog.setType(Integer.parseInt(type));
        stockChangeLog.setAboutId("0");
        stockChangeLog.setBeforeInv(0L);
        stockChangeLog.setAfterInv(bo.getInventory());
        stockChangeLog.setCreateBy(bo.getUserId());
        stockChangeLog.setUpdateBy(bo.getUserId());
        stockChangeLog.setCreateTime(DateUtils.getNowDate());
        stockChangeLog.setUpdateTime(DateUtils.getNowDate());
        stockChangeLog.setDelFlag("0");
        stockChangeLogMapper.insert(stockChangeLog);
    }

    public void insertByBo2(ZhishuShopGoodsBo bo, List<ZhishuShopGoods> zhishuShopGoodsList,
                            List<StockChangeLog> stockChangeLogList, List<ZhishuShopImages> zhishuShopImagesList,
                            String accessToken,Long taskId,Long shopId) {
//        validEntityBeforeSave(bo);
        //查询当前货号是否在自营书品已经存在
        ZhishuShopGoodsVo zhishuShopGoodsVo = selectShopGoodsByArtNo(bo.getArtNo());
        if(zhishuShopGoodsVo == null){
            ZhishuShopGoods add = MapstructUtils.convert(bo, ZhishuShopGoods.class);
            add.setTaskId(taskId);
            add.setConditionCode(CHINESE_TO_CODE_MAP1.get(add.getConditionCode()));
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                // 获取pdd图片
                bo.setId(add.getId());
                // 增加图片
                if (ObjectUtil.isNotEmpty(add.getBookPic())) {
                    ZhishuShopImages zhishuShopImages = new ZhishuShopImages();
                    zhishuShopImages.setGoodsId(add.getId());
                    zhishuShopImages.setPath(add.getBookPic());
                    zhishuShopImages.setCreateBy(add.getUserId());
                    zhishuShopImages.setUpdateBy(add.getUserId());
                    zhishuShopImages.setCreateTime(DateUtils.getNowDate());
                    zhishuShopImages.setUpdateTime(DateUtils.getNowDate());
                    zhishuShopImages.setDelFlag("0");
                    zhishuShopImagesList.add(zhishuShopImages);
                }
                // 增加库存操作日志
                StockChangeLog stockChangeLog = new StockChangeLog();
                stockChangeLog.setShopGoodsId(Long.valueOf(add.getId()));
                stockChangeLog.setType(5);
                // 孔网拉取的数据初始库存为0
                stockChangeLog.setBeforeInv(0L);
                stockChangeLog.setAfterInv((long) add.getInventory());
                stockChangeLog.setCreateBy(add.getUserId());
                stockChangeLog.setUpdateBy(add.getUserId());
                stockChangeLog.setCreateTime(DateUtils.getNowDate());
                stockChangeLog.setUpdateTime(DateUtils.getNowDate());
                stockChangeLog.setDelFlag("0");
                // 增加库存操作日志
                stockChangeLog.setAfterInv((long) add.getInventory());
                stockChangeLogList.add(stockChangeLog);
                // todo 新增已发布商品记录
                ShopGoodsPublishedBo shopGoodsPublishedBo = new ShopGoodsPublishedBo();
                shopGoodsPublishedBo.setShopId(shopId+"");
                shopGoodsPublishedBo.setShopGoodsId(add.getId());
                shopGoodsPublishedBo.setPlatformId(bo.getProductId());
                shopGoodsPublishedBo.setCreateBy(add.getUserId());
                shopGoodsPublishedBo.setCreateTime(DateUtils.getNowDate());
                shopGoodsPublishedService.insertByBo(shopGoodsPublishedBo);
                zhishuShopGoodsList.add(add);
            }
        }else{
            //已存在自营书品,校验已发布商品是否存在记录
            ShopGoodsPublishedVo shopGoodsPublishedVo = shopGoodsPublishedService.queryByShopIdAndShopGoodsId(shopId+"",zhishuShopGoodsVo.getId());
            if(shopGoodsPublishedVo == null){
                //如果为空代表没有已发布商品记录，新增记录
                ShopGoodsPublishedBo shopGoodsPublishedBo = new ShopGoodsPublishedBo();
                shopGoodsPublishedBo.setShopId(shopId+"");
                shopGoodsPublishedBo.setShopGoodsId(zhishuShopGoodsVo.getId());
                shopGoodsPublishedBo.setPlatformId(bo.getProductId());
                shopGoodsPublishedBo.setCreateBy(zhishuShopGoodsVo.getUserId());
                shopGoodsPublishedBo.setCreateTime(DateUtils.getNowDate());
                shopGoodsPublishedService.insertByBo(shopGoodsPublishedBo);
            }
        }
    }

    private String fullBookPic(ZhishuShopGoods add) {
        // 获取md5加密的32位首位小写字母
        String md5 = DigestUtils.md5Hex(add.getGoodsName());
        String substring = md5.substring(0, 1);
        return String.format("https://book.center.image.buzhiyushu.cn/%s/%s%s", substring, add.getIsbn(), "_s_01.jpg");
    }


    @Transactional(rollbackFor = Exception.class)
    public Boolean insertListGoods(ZhishuShopGoods add) {
        Long message = baseMapper.findBookMsgByISBN(add);
        if (message == 0) {
            // Integer Inventory =  baseMapper.selectGoods(add);
            // if(Inventory!=0){
            //     add.setInventory(add.getInventory() + Inventory);
            //     baseMapper.updateBook(add);
            // }else {
            Integer msg = baseMapper.setExamineBook(add);
            System.out.println(msg);
        }
        return true;
        // }else{
        //     return false;
    }

    // }


    private String callApi(String apiUrl) throws Exception {
        URL url = new URL(apiUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setInstanceFollowRedirects(true); // 自动跟随重定向

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder response = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null) {
            response.append(output);
        }
        conn.disconnect();

        return response.toString();
    }

    private String parseBookName(String jsonResponse) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(jsonResponse);

        // 解析出 book_name
        JsonNode dataNode = root.path("data");
        if (dataNode.isMissingNode()) {
            throw new RuntimeException("Data field not found in response");
        }

        JsonNode bookNameNode = dataNode.path("book_name");
        if (bookNameNode.isMissingNode()) {
            throw new RuntimeException("book_name field not found in data");
        }

        return bookNameNode.asText();
    }

    public Boolean insertByBo(List<ZhishuShopGoodsBo> bo, Long userId,String type) {
        for (ZhishuShopGoodsBo goodsBo : bo) {
            // 检查书名是否为null，如果是则根据ISBN搜索
            if (goodsBo.getGoodsName() == null && goodsBo.getIsbn() != null && !goodsBo.getIsbn().isEmpty()) {
                String apiUrl = "https://book.center.yushutx.com/api/es/searchByISBN?isbn=" + goodsBo.getIsbn();
                try {
                    String response = callApi(apiUrl);
                    String bookName = parseBookName(response);
                    goodsBo.setGoodsName(bookName);
                } catch (Exception e) {
                    // 异常处理，可以根据实际情况调整
                    log.error("Error searching book by ISBN: {}", e.getMessage());
                }
            }

            // 将ZhishuShopGoodsBo数据 转换为到ZhishuShopGoods数据
            Integer isJoinDistribution = goodsBo.getIsJoinDistribution() == null ?  this.parseShipmentId(userId.toString(), goodsBo.getArtNo().substring(0, 5)) : goodsBo.getIsJoinDistribution();


            ZhishuShopGoods zhishuShopGoods = MapstructUtils.convert(goodsBo, ZhishuShopGoods.class);
            zhishuShopGoods.setUserId(userId);
            zhishuShopGoods.setConditionCode(CHINESE_TO_CODE_MAP1.get(zhishuShopGoods.getConditionCode()));
            zhishuShopGoods.setPrice(zhishuShopGoods.getPrice() * 100);
            zhishuShopGoods.setIsJoinDistribution(isJoinDistribution);
            if (zhishuShopGoods.getPrice() != null) {
                zhishuShopGoods.setFixPrice(zhishuShopGoods.getPrice() * 100);
            }
            ZhishuShopGoodsVo zhishuShopGoodsVo = baseMapper.selectShopGoodsByItemNumber1(zhishuShopGoods);
            zhishuShopGoods.setUserId(userId);
            if (zhishuShopGoodsVo != null ) {
                Long Inventory = Long.parseLong(zhishuShopGoodsVo.getInventory());
                Long oldInventory = Inventory;
                Long newInventory = Inventory + zhishuShopGoods.getInventory();
                // 商品存在
                zhishuShopGoods.setInventory(newInventory);
                Integer a = baseMapper.updateByProduct(zhishuShopGoods);
                // 添加日志
                //修改成功后，记录自营书品库存修改表
                StockChangeLog stockChangeLog = new StockChangeLog();
                stockChangeLog.setShopGoodsId(Long.parseLong(zhishuShopGoodsVo.getId()));
                //类型  2-订单减扣 3-退单添加
                stockChangeLog.setType(Integer.parseInt(type));
                stockChangeLog.setAboutId("0");
                stockChangeLog.setBeforeInv(oldInventory);
                stockChangeLog.setAfterInv(newInventory);
                stockChangeLog.setCreateBy(zhishuShopGoods.getUserId());
                stockChangeLog.setUpdateBy(zhishuShopGoods.getUserId());
                stockChangeLog.setCreateTime(DateUtils.getNowDate());
                stockChangeLog.setUpdateTime(DateUtils.getNowDate());
                stockChangeLog.setDelFlag("0");
                stockChangeLogMapper.insert(stockChangeLog);
            } else {
                goodsBo.setUserId(userId);
                goodsBo.setIsJoinDistribution(isJoinDistribution);
                this.insertByBo1(goodsBo,type);
            }

            /**
             * yxy增加代码：如果 goodsBo 的 params 不为空，则进行新增已发布商品
             */
            if (goodsBo.getParams() != null) {
                ShopGoodsPublishedBo shopGoodsPublishedBo = new ShopGoodsPublishedBo();
                // 商品id
                shopGoodsPublishedBo.setShopGoodsId(goodsBo.getId());
                // 店铺id
                shopGoodsPublishedBo.setShopId(goodsBo.getParams().get("shopId") == null ? null : goodsBo.getParams().get("shopId").toString());
                // 三方平台商品id
                shopGoodsPublishedBo.setPlatformId(goodsBo.getParams().get("trilateralId") == null ? null : goodsBo.getParams().get("trilateralId").toString());
                // 创建人
                shopGoodsPublishedBo.setCreateBy(userId);
                shopGoodsPublishedService.insertByBo(shopGoodsPublishedBo);
            }
        }
        return true;
    }

    public Boolean insertByBo1(List<ZhishuShopGoodsBo> bo, Long userId, List<ZhishuShopGoods> zhishuShopGoodsList,
                               List<StockChangeLog> stockChangeLogList, List<ZhishuShopImages> zhishuShopImagesList,
                               String accessToken,Long taskId,Long shopId) {
        for (ZhishuShopGoodsBo goodsBo : bo) {
            this.insertByBo2(goodsBo, zhishuShopGoodsList, stockChangeLogList, zhishuShopImagesList,accessToken,taskId,shopId);

            // 新增商品详情
            if(ObjectUtil.isEmpty(goodsBo.getIsbn()) || Objects.equals(goodsBo.getIsbn().substring(0,1),"6")){
                System.out.println("商品描述详情:"+JSONObject.toJSONString(goodsBo));
                ZhishuShopGoodsDetailBo zhishuShopGoodsDetail = new ZhishuShopGoodsDetailBo();
                zhishuShopGoodsDetail.setPid(Long.valueOf(goodsBo.getId()));
                zhishuShopGoodsDetail.setAuthor(goodsBo.getAuthor());
                zhishuShopGoodsDetail.setPublisher(goodsBo.getPublisher());
                zhishuShopGoodsDetail.setPublishertime(goodsBo.getPublisherTime());
                zhishuShopGoodsDetail.setFormat(goodsBo.getFormat());
                zhishuShopGoodsDetail.setWordage(goodsBo.getWordage());
                zhishuShopGoodsDetail.setUnifiedisbn(goodsBo.getUnifiedIsbn());
                zhishuShopGoodsDetailService.insertByBo(zhishuShopGoodsDetail);
            }
        }
        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertList(List<ZhishuShopGoodsBo> list, Long depotId, String Filename) {
        // 开始时间
        long time1 = System.currentTimeMillis();
        // 获取列表总数量
        int count = list.size();

        // 每批次插入的数据量
        int pageSize = 1000;
        // 根据总数量和每批次的数量计算需要的线程数
        int threadNum = count % pageSize == 0 ? (count / pageSize) : (count / pageSize + 1);
        // 获取当前用户id
        Long userId = LoginHelper.getUserId();

        // 通过变量存储数据库中数据
        List<ZhishuShopGoodsBo> countList = baseMapper.selectAll(userId);
        // 生成任务key
        String cat = buildTaskKey(depotId.toString(), Filename, LocalDateTime.now());

        // 判断当前仓库是否有货架
        List<TShelves> sheCount = baseMapper.selectSheCount(depotId);
        if (sheCount.size() == 0) {
            throw new RuntimeException("当前一级货区未存在二级货区");
        }
        // 判断当前货区是否有货位
        List<TFreight> freCount = baseMapper.selectFreCount1(sheCount);
        if (freCount.size() == 0) {
            throw new RuntimeException("当前一级货区未存在三级货区");
        }

        Map<Long, Long> map = new HashMap<>();
        sheCount.forEach(she -> {
            // 跳过无效code长度（非1位或2位）
            if (she.getCode().length() != 1 && she.getCode().length() != 2) {
                return; // 在forEach中相当于continue
            }

            List<TFreight> tFreight = baseMapper.selectBySId(she.getId());
            if (tFreight == null) {
                return; // 跳过空数据
            }
            for (int i = 0; i < tFreight.size(); i++) {
                if (tFreight.get(i).getCode() == null) {
                    return; // 跳过空数据
                }
                // 核心匹配逻辑
                if ((she.getCode().length() == 2 && tFreight.get(i).getCode().length() == 1) || (she.getCode().length() == 1 && tFreight.get(i).getCode().length() == 2)) {
                    map.put(tFreight.get(i).getId(), she.getId());
                }
            }
        });
        if (map.isEmpty()) {
            return false;
        }


        baseMapper.insertTask(depotId, Filename, count, userId);

        // 初始化线程池
        ExecutorService executor = Executors.newFixedThreadPool(100);
        // 创建计数器
        CountDownLatch end = new CountDownLatch(threadNum);
        // 将列表按照线程数量进行分批处理
        Lists.partition(list, threadNum).forEach(batch -> executor.execute(() -> {
            try {
                // 5.并行化ArtNo生成（线程安全处理）
                // 随机获取sheCount列表中的任意一个数并判断是否为空
                Long sheId = null;
                Long freId = null;
                // 1. 转换为可随机访问的Entry集合
                List<Map.Entry<Long, Long>> entries = new ArrayList<>(map.entrySet());
                // 2. 线程安全随机选择（Java 8+）
                if (!entries.isEmpty()) {
                    Map.Entry<Long, Long> randomEntry = entries.get(ThreadLocalRandom.current().nextInt(entries.size()));
                    freId = randomEntry.getKey();
                    sheId = randomEntry.getValue();
                }

                processArtNoConcurrently(list, userId, depotId, sheId, freId);
                Boolean b = this.insertByBo(batch, userId,null);

            } finally {
                // 6. 计数器减一，表示一个线程完成任务
                end.countDown();
            }
        }));

        try {
            // 等待所有线程完成任务
            end.await();
            // 关闭线程池
            executor.shutdown();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ServiceException("任务被中断");
        }
        // finally {
        //     // 7.双重保障清理机制（即使线程崩溃也会执行）
        //     redisTemplate.delete(depotId);
        //     log.info(" 任务[{}]已执行完成并清理锁", userId);
        // }
        long time2 = System.currentTimeMillis();
        System.out.println("总耗时：" + (time2 - time1));
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertListGoodsInfo(List<ZhishuShopGoodsBo> list, Long depotId, Long shelvesDepotId, Long freightDepotId, String Filename, String code,Long userId,String type) {
        // 获取当前用户id
        if (userId == null){
            userId = LoginHelper.getUserId();
        }

        // 开始时间
        long time1 = System.currentTimeMillis();
        // 获取列表总数量
        int count = list.size();

        // 每批次插入的数据量
        int pageSize = 1000;
        // 根据总数量和每批次的数量计算需要的线程数
        int threadNum = count % pageSize == 0 ? (count / pageSize) : (count / pageSize + 1);


        // 通过变量存储数据库中数据
        List<ZhishuShopGoodsBo> countList = baseMapper.selectAll(userId);
        // 生成任务key
        String cat = buildTaskKey(depotId.toString(), Filename, LocalDateTime.now());

        baseMapper.insertTask(depotId, Filename, count, userId);

        // 初始化线程池
        ExecutorService executor = Executors.newFixedThreadPool(100);
        // 创建计数器
        CountDownLatch end = new CountDownLatch(threadNum);
        // 将列表按照线程数量进行分批处理
        Long finalUserId = userId;
        Lists.partition(list, threadNum).forEach(batch -> executor.execute(() -> {
            try {
                // 直接使用传入的ID
                Long sheId = shelvesDepotId;
                Long freId = freightDepotId;

                processArtNoConcurrently(list, finalUserId, depotId, sheId, freId);
                Boolean b = this.insertByBo(batch, finalUserId,type);
            } finally {
                // 计数器减一，表示一个线程完成任务
                end.countDown();
            }
        }));

        try {
            // 等待所有线程完成任务
            end.await();
            // 关闭线程池
            executor.shutdown();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ServiceException("任务被中断");
        }

        long time2 = System.currentTimeMillis();
        System.out.println("总耗时：" + (time2 - time1));
        return true;
    }
    /**
     * 处理ArtNo生成的并发问题
     */
    private void processArtNoConcurrently(List<ZhishuShopGoodsBo> list, Long userId, Long depotId, Long sheId, Long freId) {

        List<TDepot> tDepotList = tDepotMapper.selectV(userId);
        List<TShelves> tShelvesList = tShelvesMapper.selectM(userId);
        List<TFreight> tFreightList = tShelvesMapper.selectFList(userId);
        // 并行处理每个商品对象
        list.stream().forEach(zhishuShopGoodsBo -> {
//            if (zhishuShopGoodsBo.getIsArtNoConversion() == 0) {
//                return;
//            }

           int count= baseMapper.selectArtNobyartNo(zhishuShopGoodsBo.getArtNo(), userId);
            if(count>0){
                return;
            }
            // 设置商品对象的用户ID
            zhishuShopGoodsBo.setUserId(userId);
            // 初始化新的ArtNo为空字符串
            String newArtNo = "";
            // 接收新的artNo
            String artNo1 = zhishuShopGoodsBo.getArtNo();
            // 获取商品的品相
            String conCode = zhishuShopGoodsBo.getConditionCode();
            // 获取商品的ISBN
            String isbn = zhishuShopGoodsBo.getIsbn();
            // 调用方法获取新的ArtNo
            Double s = convertChineseToCode(conCode);

            String letterCode = CnumberUtils.CHINESE_TO_CODE_MAP.get(conCode);
            // 判断artNo是否为
//            if (StringUtils.isEmpty(artNo1)) {
            // 调用生成货号的工具类
            newArtNo = cnumberUtils.getArtNo(s, userId, isbn, depotId, sheId, freId, letterCode, tDepotList, tShelvesList, tFreightList);
//            } else if (artNo1.length() < 13) {
            // 货号小于13位，则补全货号

//                String depotCode = TDepotMapper.selectByCode(userId, depotId);
//                String sheCode = TShelvesMapper.selectFreCode(depotCode, userId);
//                String freCode = String.valueOf(generateRandomNumber(1, 5));
//                String conditionCode = getConditionCode(convertChineseToCode(zhishuShopGoodsBo.getConditionCode()));
//                newArtNo = depotCode + sheCode + freCode + conditionCode + "-" + artNo1;
//            } else {
//                newArtNo = artNo1;
//            }
            zhishuShopGoodsBo.setArtNo(newArtNo);
        });
    }


    /**
     * 修改商品信息
     *
     * @param bo 商品信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ZhishuShopGoodsBo bo) {
        ZhishuShopGoods update = MapstructUtils.convert(bo, ZhishuShopGoods.class);
        if (update != null) {
            update.setConditionCode(CHINESE_TO_CODE_MAP1.get(bo.getConditionCode()));
        }
        try {
            boolean inven = false;
            ZhishuShopGoods zhishuShopGoods = baseMapper.selectById(update.getId());
            if (bo.getInventory() != null && !bo.getInventory().equals(zhishuShopGoods.getInventory())) {
                int caozuoType = 0;
                int inverend = 0;
                if (zhishuShopGoods.getInventory() == null) {
                    caozuoType = 1;
                    inverend = bo.getInventory().intValue();
                } else {
                    int newInventory = bo.getInventory().intValue();
                    int oldInventory = zhishuShopGoods.getInventory().intValue();
                    // 通过三元运算符实现当newInventory大于oldInventory时，caozuoType为1(增加库存)，否则为2(减少库存)
                    caozuoType = newInventory > oldInventory ? 1 : 2;
                    inverend = newInventory > oldInventory ? newInventory - oldInventory : oldInventory - newInventory;
                }
                boolean authorizeStatus = getshopAuthorize(zhishuShopGoods);
                if (authorizeStatus) {
                    //执行库存同步操作
                    Boolean invent = CaoZuoInvent(caozuoType, zhishuShopGoods, inverend);
                    // 获取当前库存数量
                    Boolean count = baseMapper.updateChunkInventory(update);
                    if (invent && count) {
                        inven = true;
                    }
                    if (!inven) {
                        throw new RuntimeException("线上库存修改失败");
                    }
                }
            }
            return inven;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取店铺授权状态
     *
     * @param zhishuShopGoods
     * @return
     */
    public Boolean getshopAuthorize(ZhishuShopGoods zhishuShopGoods) {
        List<ShopGoodsPublishedVo> shopGoodsPublishedVoList = shopGoodsPublishedService.queryByShopGoodsId(zhishuShopGoods.getId());
        // 循环根据店铺Id查询出店铺信息
        List<String> shopNames = new ArrayList<>();
        for (ShopGoodsPublishedVo goodsPublishedVo : shopGoodsPublishedVoList) {
            // 根据店铺Id查询出店铺信息
            ShopVo shop = shopService.queryById(Long.valueOf(goodsPublishedVo.getShopId()));
            if (shop == null){
                shopGoodsPublishedService.deleteWithValidByIds(List.of(goodsPublishedVo.getId()), true);
                continue;
            }
            // 根据店铺类型分别推送平台同步库存
            try {
                if (shop.getShopAuthorize().equals("2")) {
                    shopNames.add(shop.getShopName());
                }
            } catch (Exception e) {
                throw new RuntimeException(shop.getShopName() + "同步失败：" + e);
            } finally {
                continue;
            }
        }
        if (!shopNames.isEmpty()) {
            String formattedShops = String.join("，", shopNames); // 中文逗号分隔
            throw new RuntimeException("店铺：" + formattedShops + ",授权已过期,请重新授权");
        }
        return true;
    }


    /**
     * 根据库存操作类型操作库存并同步平台库存
     *
     * @param operationType
     * @param zhishuShopGoods
     * @param count
     * @return
     */
    public Boolean CaoZuoInvent(Integer operationType, ZhishuShopGoods zhishuShopGoods, Integer count) {
        Boolean result = operatingInventory(operationType, zhishuShopGoods.getId(), count, 1, "0", zhishuShopGoods.getUserId());
        Assert.isTrue(result, "操作redis/数据库库存失败");
        // 根据商品Id查询出拥有同商品的店铺Id和平台商品Id
        List<ShopGoodsPublishedVo> shopGoodsPublishedVoList = shopGoodsPublishedService.queryByShopGoodsId(zhishuShopGoods.getId());
        // 循环根据店铺Id查询出店铺信息
        for (ShopGoodsPublishedVo goodsPublishedVo : shopGoodsPublishedVoList) {
            // 根据店铺Id查询出店铺信息
            ShopVo shop = shopService.queryById(Long.valueOf(goodsPublishedVo.getShopId()));
            if (shop == null){
                shopGoodsPublishedService.deleteWithValidByIds(List.of(goodsPublishedVo.getId()), true);
                continue;
            }
            // 根据店铺类型分别推送平台同步库存
            try {
                InventorySynchronizedStrategy strategy = InventorySynchronizedStrategyFactory.getStrategy(shop.getShopType());
                /**
                 * operationType  1 添加库存任务  2 减少库存任务
                 * type          3 添加库存   2 减少库存
                 */
                Integer type = operationType == 1 ? 3 : 2;
                strategy.inventorySynchronized(shop, goodsPublishedVo,type);
            } catch (Exception e) {
                throw new RuntimeException(shop.getShopName() + "同步失败：" + e);
            } finally {
                continue;
            }
        }
        return true;
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZhishuShopGoodsBo entity) {

        // 获取当前用户id
        // Long userId = LoginHelper.getUserId();
        // if (entity.getArtNo() == null || entity.getArtNo().length() < 13) {
        //     Double s = convertChineseToCode(entity.getConditionCode());
        //     entity.setUserId(userId);
        //     String artNo = cnumberUtils.getArtNo(s, userId, entity.getIsbn(), null, null, null, null);
        //     entity.setArtNo(artNo);
        //
        // }

        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除商品信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        boolean message = false;
        ArrayList<String> idsList = new ArrayList<>();
        if (isValid) {
//              删除商品信息
//             循环ids设置ZhishuShopGoods中的id和设置库存为0
            ids.forEach(id -> {
                ZhishuShopGoods zhishuShopGoods = baseMapper.selectById(id);
                if (zhishuShopGoods.getInventory() != null) {
                    Integer inventory = zhishuShopGoods.getInventory().intValue();
                    Boolean result = CaoZuoInvent(2, zhishuShopGoods, inventory);
                    if (result) {
                        idsList.add(id);
                    }
                }
            });
            if (!idsList.isEmpty()) {
                for (String id : idsList) {
                    // 查询是否存在已发布商品信息
                    Integer count = baseMapper.selectPubCount(id);
                    if (count > 0) {
                        // 删除已发布商品信息
                        baseMapper.delPubGood(id);
                    }
                }
                message = baseMapper.deleteIds(idsList) > 0;
            }
        } else {
            for (String id : ids) {
                // 查询是否存在已发布商品信息
                Integer count = baseMapper.selectPubCount(id);
                if (count > 0) {
                    // 删除已发布商品信息
                    baseMapper.delPubGood(id);
                }
            }
            message = baseMapper.deleteIds(ids) > 0;
        }

        // baseMapper.selectPubCount(ids);

        return message;
    }


    /**
     * 构建任务的唯一键
     * <p>
     * 该方法通过结合仓库ID、目录路径的MD5值和时间来生成一个全局唯一的任务键
     * 使用MD5值是为了确保即使目录路径非常长，生成的键也不会超过一定的长度，并且是唯一的
     * 时间格式化为yyyyMMddHHmm是为了确保时间的部分在键中是固定长度和格式的
     *
     * @param depotId     仓库ID，标识任务所属的仓库
     * @param catalogPath 目录路径，标识任务所在的目录结构
     * @param time        时间，标识任务创建的时间
     * @return 返回构建的任务键字符串
     */
    public static String buildTaskKey(String depotId, String catalogPath, LocalDateTime time) {
        return String.format("TASK:%s:%s:%s", depotId, DigestUtils.md5Hex(catalogPath), time.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")));
    }

    public static final Map<String, String> CHINESE_TO_CODE_MAP1 = IntStream.range(0, CHINESE_CODE.length).boxed().collect(Collectors.toMap(i -> CHINESE_CODE[i],    // 键：中文标识（如"一品"）
            i -> CONDITION_CODE[i],  // 值：字母标识（如"A"）
            (oldVal, newVal) -> oldVal, LinkedHashMap::new       // 保持插入顺序
    ));

    public static final Map<String, Double> CHINESE_TO_CODE_MAP = IntStream.range(0, CHINESE_CODE.length).boxed().collect(Collectors.toMap(i -> CHINESE_CODE[i],    // 键：中文标识（如"一品"）
            i -> CONDITION_CODES[i],  // 值：字母标识（如"1"）
            (oldVal, newVal) -> oldVal, LinkedHashMap::new       // 保持插入顺序
    ));

    // 品相映射表
    public static final Map<Double, String> CODE_MAP = IntStream.range(0, CONDITION_CODES.length).boxed().collect(Collectors.toMap(i -> CONDITION_CODES[i],
            i -> CONDITION_CODE[i],
            (oldVal, newVal) -> oldVal, () -> new TreeMap<>(Comparator.comparingDouble(Double::doubleValue))));

    public Double convertChineseToCode(String chineseName) {
        Double code = CHINESE_TO_CODE_MAP.get(chineseName);
        if (code == null) {
            throw new IllegalArgumentException("无效的中文品名: " + chineseName);
        }
        return code;
    }

    private int generateRandomNumber(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }


    public static String getConditionCode(double input) {
        return CODE_MAP.getOrDefault(input, "UNDEFINED");
    }

    /**
     * 调用Python脚本查询图书信息
     *
     * @param isbn ISBN编号
     * @return 查询结果
     */
    public ProductVo queryBookByPython(String isbn) {
        try {
            // 1. 确认线上Python脚本路径
            String scriptPath = "/www/wwwroot/python/chaxun.py"; // 线上绝对路径
            File scriptFile = new File(scriptPath);

            // 2. 检查脚本是否存在
            if (!scriptFile.exists()) {
                throw new RuntimeException("Python脚本不存在: " + scriptPath);
            }

            // 3. 检查执行权限（Linux/Unix环境）
            if (!scriptFile.canExecute()) {
                throw new RuntimeException("Python脚本无执行权限: " + scriptPath);
            }

            // 4. 构建进程命令（明确使用python3）
            ProcessBuilder processBuilder = new ProcessBuilder("python3", scriptPath, // 脚本路径
                    isbn       // ISBN参数
            );
            processBuilder.redirectErrorStream(true); // 合并错误流到标准输出

            // 5. 启动进程并等待完成
            System.out.println("执行命令: " + String.join(" ", processBuilder.command()));
            Process process = processBuilder.start();

            // 6. 读取输出
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }

            // 7. 检查执行结果
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("Python脚本执行失败，退出码: " + exitCode + "\n输出: " + output);
            }

            // 8. 解析JSON结果
            return JSON.parseObject(output.toString().trim(), ProductVo.class);
        } catch (Exception e) {
            throw new RuntimeException("调用Python脚本失败: " + e.getMessage(), e);
        }
    }

    /**
     * 查询上书记录
     */
//    @Override
//    public List<ZhishuShopGoodsVo> selectShopGoodsByPhoneNumber(String phoneNumber) {
//        Long userId = sysUserMapper.selectUserIdByNameAndPassWord(phoneNumber);
//        // 获取用户对应的店铺ID列表
//        Map<String, List<Long>> shopIdsMap = getShopIdsByUserId(userId);
//        // 获取拼多多店铺ID列表
//        List<Long> pddShopIds = shopIdsMap.get("1");
//        // 获取孔夫子店铺ID列表
//        List<Long> kfzShopIds = shopIdsMap.get("2");
//        // 根据UserId获取商品列表ID
//        List<ZhishuShopGoodsVo> goodsList = baseMapper.selectShopGoodsByUser(userId);
//        // 提取当前用户上传的商品ID列表
//        List<String> goodsIds = goodsList.stream().map(ZhishuShopGoodsVo::getId).collect(Collectors.toList());
//
//        // 合并所有店铺ID
//        List<Long> allShopIds = new ArrayList<>();
//        if (pddShopIds != null) allShopIds.addAll(pddShopIds);
//        if (kfzShopIds != null) allShopIds.addAll(kfzShopIds);
//
//        // 查询所有商品的发布状态
//        if (!goodsIds.isEmpty() && !allShopIds.isEmpty()) {
//            List<Map<String, Object>> publishedStatusList = shopGoodsPublishedService.selectPublishedStatus(goodsIds, allShopIds);
//
//            // 将发布状态设置到商品对象中
//            Map<String, Map<String, Object>> statusMap = publishedStatusList.stream()
//                .collect(Collectors.toMap(
//                    map -> String.valueOf(map.get("goodsId")),
//                    map -> map,
//                    (v1, v2) -> v1
//                ));
//
//            goodsList.forEach(goods -> {
//                Map<String, Object> status = statusMap.get(goods.getId());
//                if (status != null) {
//                    goods.setPddPublishedStatus((Long) status.get("pddStatus"));
//                    goods.setKfzPublishedStatus((Long) status.get("kfzStatus"));
//                } else {
//                    goods.setPddPublishedStatus(0L);
//                    goods.setKfzPublishedStatus(0L);
//                }
//            });
//        }
//
//        // 获取商品图片
//        if (!goodsIds.isEmpty()) {
//            // 批量查询图片路径
//            List<Map<String, Object>> imagePathList = zhishuShopImagesMapper.batchQueryFirstPathByGoodsIds(goodsIds);
//
//            // 将图片路径列表转换为Map
//            Map<String, String> imagePathMap = imagePathList.stream()
//                .collect(Collectors.toMap(
//                    map -> String.valueOf(map.get("goodsId")),
//                    map -> String.valueOf(map.get("path")),
//                    (v1, v2) -> v1
//                ));
//
//            // 设置图片路径并调用getFiles方法获取图片
//            goodsList.forEach(goods -> {
//                String path = imagePathMap.get(goods.getId());
//                if (path != null && !path.isEmpty()) {
//                    try {
//                        // 调用getFiles方法获取图片
//                        String bookPic = uploadUtil.getFiles(null, goods.getGoodsName(), path);
//                        goods.setBookPic(bookPic);
//                    } catch (Exception e) {
//                        // 记录错误但继续处理其他商品
//                        log.error("获取商品图片失败: goodsId={}, path={}", goods.getId(), path, e);
//                    }
//                }
//            });
//        }
//
//        return goodsList;
//    }
    public Map<String, List<Long>> getShopIdsByUserId(Long userId) {
        // 构建查询条件
        LambdaQueryWrapper<Shop> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Shop::getCreateBy, userId)
                .eq(Shop::getStatus, "0")  // 正常状态
                .eq(Shop::getDelFlag, "0") // 未删除
                .select(Shop::getId, Shop::getShopType); // 只查询需要的字段

        // 执行查询
        List<Shop> shopList = shopMapper.selectList(wrapper);

        // 按店铺类型分组
        Map<String, List<Long>> resultMap = new HashMap<>();

        // 初始化结果Map
        resultMap.put("1", new ArrayList<>()); // 拼多多店铺
        resultMap.put("2", new ArrayList<>()); // 孔夫子店铺
        resultMap.put("5", new ArrayList<>()); // 闲鱼店铺

        // 遍历店铺列表，按类型分组
        for (Shop shop : shopList) {
            String shopType = shop.getShopType();
            if (shopType != null) {
                List<Long> idList = resultMap.getOrDefault(shopType, new ArrayList<>());
                idList.add(shop.getId());
                resultMap.put(shopType, idList);
            }
        }

        return resultMap;
    }


    /**
     * 初始化Redis库存
     */
    @Override
    public void batchInitInventoryToRedis() {
        List<ZhishuShopGoods> goodsList = new LambdaQueryChainWrapper<>(baseMapper).list();
        batchRedisInitInventory(goodsList);
    }

    public void batchRedisInitInventory(List<ZhishuShopGoods> goodsList) {
        if (ObjectUtil.isNotEmpty(goodsList)) {
            RBatch batch = RedisUtils.getClient().createBatch();

            goodsList.forEach(goods -> {
                String inventoryKey = "zhishu_shop_goods_inventory:" + goods.getId();
                RListAsync<Object> list = batch.getList(inventoryKey);
                for (int i = 0; i < goods.getInventory(); i++) {
                    list.addAsync(goods.getId());
                }
            });

            // 执行批量操作
            batch.execute();
        }
    }

    /**
     * 操作Redis/db库存
     *
     * @param shopGoodsId
     * @param count
     * @return
     */
    @Override
    public Boolean operatingInventory(Integer operationType, String shopGoodsId, Integer count, Integer type, String aboutId, Long operationBy) {
        // 确定操作类型
        OperationInventoryTypeEnum operationEnum = OperationInventoryTypeEnum.valueOfCode(operationType);
        // 指定redis库000000
        String inventoryKey = "zhishu_shop_goods_inventory:" + shopGoodsId;
        String lockKey = "lock:" + shopGoodsId; // 分布式锁的键
        RLock lock = null;
        boolean isLockAcquired = false;
        try {
            // 尝试获取分布式锁
             lock = RedisUtils.getClient().getLock(lockKey);
            isLockAcquired = lock.tryLock(10, 10, TimeUnit.SECONDS); // 尝试获取锁，等待时间10秒，锁持有时间为10秒

            if (!isLockAcquired) {
                throw new ServiceException("未能获取到锁，请稍后重试");
            }

            // 查询原始库存
            ZhishuShopGoods zhishuShopGoods = new LambdaQueryChainWrapper<>(baseMapper)
                    .eq(ZhishuShopGoods::getId, shopGoodsId)
                    .oneOpt().orElseThrow(() -> new ServiceException("查询商品数据异常-shopGoodsId：" + shopGoodsId));

            Long currentInventorySize = zhishuShopGoods.getInventory();

            boolean dbUpdateResult = false;

            // 增加库存操作日志
            StockChangeLog stockChangeLog = new StockChangeLog();
            stockChangeLog.setShopGoodsId(Long.valueOf(shopGoodsId));
            stockChangeLog.setType(type);
            stockChangeLog.setAboutId(aboutId);
            stockChangeLog.setBeforeInv((long) zhishuShopGoods.getInventory());
            stockChangeLog.setCreateBy(operationBy);
            stockChangeLog.setUpdateBy(operationBy);
            stockChangeLog.setCreateTime(DateUtils.getNowDate());
            stockChangeLog.setUpdateTime(DateUtils.getNowDate());
            stockChangeLog.setDelFlag("0");

            switch (operationEnum) {
                case REDUCE_INVENTORY:
                    //减少库存
                    if (currentInventorySize < count) {
                        stockChangeLog.setAfterInv((long) currentInventorySize); // 库存保持不变
                        break; // 跳出switch，继续后续流程
                    }
                    // 扣除库存

                    // 更新数据库中的库存
                    dbUpdateResult = new LambdaUpdateChainWrapper<>(baseMapper).eq(ZhishuShopGoods::getId, shopGoodsId).setSql("inventory = inventory - " + count).update();
                    stockChangeLog.setAfterInv((long) (currentInventorySize - count));
                    break;
                case INCREASE_INVENTORY:
                    // 增加库存

                    // 更新数据库中的库存
                    dbUpdateResult = new LambdaUpdateChainWrapper<>(baseMapper).eq(ZhishuShopGoods::getId, shopGoodsId).setSql("inventory = inventory + " + count).update();
                    stockChangeLog.setAfterInv((long) (currentInventorySize + count));
                    break;
                default:
                    throw new ServiceException("未知的操作类型");
            }

            if (!dbUpdateResult) {
                throw new ServiceException("扣减库存，操作数据库失败");
            }

            int insert = stockChangeLogMapper.insert(stockChangeLog);
            if (insert <= 0) {
                throw new ServiceException("库存操作日志插入失败");
            }
            return true;
        } catch (ServiceException be) {
            System.out.println("库存操作异常: " + be.getMessage() + be);
            throw be;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复线程中断状态
            throw new ServiceException(e.getMessage());
        } finally {
            // 确保释放锁
            safeUnlock(lock, isLockAcquired);
        }
    }

    private void safeUnlock(RLock lock, boolean isLockAcquired) {
        if (isLockAcquired && lock != null) {
            try {
                // 检查当前线程是否还持有锁
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                } else {
                    System.err.println("当前线程已不再持有锁，跳过释放操作");
                }
            } catch (Exception e) {
                System.err.println("释放锁异常: " + e.getMessage());
                // 这里可以记录日志，但不要抛出异常
            }
        }
    }




    /**
     * 比对店铺商品信息并生成Excel文件
     *
     * @param request
     */
    @Async
    @Override
    public void goodsComparison(GoodsComparisonRequest request) {
        Long shopId = request.getShopId();
        Long userId = request.getUserId();
        List<ZhishuShopGoodsRequest> zhishuShopGoodsRequestList = request.getZhishuShopGoodsRequestList();
        // 尝试获取锁
        String lockKey = "WriteExcelKey_" + shopId;
        String lockValue = "WriteExcelLock";
        Duration lockExpireDuration = Duration.ofMinutes(2); // 设置锁的过期时间为2分钟
        String writeExcelLock = RedisUtils.getCacheObject(lockKey);
        // 若获取存在说明存在读取该文件的线程，则直接返回，不进行后续操作
        if (ObjectUtil.isNotEmpty(writeExcelLock)) throw new ServiceException("已在处理该文件，请勿重复操作");
        System.out.println("获取到redis锁，执行读取文件操作");
        // 若不存在，则设置锁，并执行后续操作
        RedisUtils.setCacheObject(lockKey, lockValue, lockExpireDuration);
        ScheduledExecutorService scheduler = null;
        ScheduledFuture<?> future = null;
        try {
            scheduler = Executors.newScheduledThreadPool(1);
            // 设置一个定时任务来不断延长锁的过期时间
            Runnable renewLockTask = () -> {
                RedisUtils.setCacheObject(lockKey, lockValue, lockExpireDuration);
                System.out.println("Redis锁过期时间已更新");
            };
            // 启动定时任务
            future = scheduler.scheduleAtFixedRate(renewLockTask, 0, INITIAL_DELAY_AND_PERIOD, TimeUnit.SECONDS);

            // 使用并发流处理
            List<ZhishuShopGoodsRequest> changedData = Collections.synchronizedList(new ArrayList<>());
            List<ZhishuShopGoodsRequest> newData = Collections.synchronizedList(new ArrayList<>());

            List<String> artNoList = zhishuShopGoodsRequestList.stream()
                    .map(ZhishuShopGoodsRequest::getArtNo)
                    .filter(Objects::nonNull) // 过滤掉 null
                    .filter(s -> !s.isEmpty()) // 过滤掉 空字符串 ""
                    .distinct() // 去重
                    .toList();
            List<ZhishuShopGoods> alreadyExistList = new ArrayList<>();
            if (!ObjectUtil.isEmpty(artNoList)) {
                // 查出数据库是否存在数据
                alreadyExistList = new LambdaQueryChainWrapper<>(baseMapper)
                        .in(ZhishuShopGoods::getArtNo, artNoList)
                        .list();
            }
            Map<String, ZhishuShopGoods> goodsHashMap = new HashMap<>();
            if (ObjectUtil.isNotEmpty(alreadyExistList)) {
                for (ZhishuShopGoods zhishuShopGoods : alreadyExistList) {
                    goodsHashMap.put(zhishuShopGoods.getProductId(), zhishuShopGoods);
                }
            }

            for (ZhishuShopGoodsRequest zhishuShopGoodsRequest : zhishuShopGoodsRequestList) {
                // 是否发生变化辨识
                Boolean isChanged = false;
                // 若经过ISBN码、价格、货号都匹配，则却该数据已在库中存在，则进行具体的其他参数值对比，看是否有其他参数做了修改
                if (ObjectUtil.isNotEmpty(alreadyExistList)) {
                    // 默认取第一条，多条情况为数据存在异常，不考虑
                    if (ObjectUtil.isNotEmpty(goodsHashMap)) {
                        ZhishuShopGoods zhishuShopGoods = goodsHashMap.get(zhishuShopGoodsRequest.getItemNumber());
                        if (ObjectUtil.isNotEmpty(zhishuShopGoods)) {
                            // 判断ISBN码是否发生变化
                            if (!Objects.equals(zhishuShopGoodsRequest.getIsbn(), zhishuShopGoods.getIsbn()))
                                isChanged = true;
                            // 判断品相是否发生变化
                            double conditionCode = Math.round(zhishuShopGoodsRequest.getConditionCode().doubleValue()) / 10.0;
                            String conditionCodeString = CnumberUtils.getConditionCode(conditionCode);
                            if (!conditionCodeString.equals(zhishuShopGoods.getConditionCode())) isChanged = true;
                            // 判断库存是否发生变化
                            if (!zhishuShopGoodsRequest.getInventory().equals(zhishuShopGoods.getInventory().intValue()))
                                isChanged = true;
                            // 将原数据库中该条数据的id赋值给当前新拉取下来的数据,用于后续更新数据库
                            zhishuShopGoodsRequest.setId(zhishuShopGoods.getId());
                            if (isChanged) {
                                changedData.add(zhishuShopGoodsRequest);
                            }
                        } else {
                            // 若数据库中未查询到符合判定规则的数据，说明该数据为新增数据，将其加入到newData中
                            newData.add(zhishuShopGoodsRequest);
                        }
                    }
                } else {
                    // 若数据库中未查询到符合判定规则的数据，说明该数据为新增数据，将其加入到newData中
                    newData.add(zhishuShopGoodsRequest);
                }
            }

            List<String> fileNameList = new ArrayList<>();
            // 分别指定新增和修改的数据生成的Excel文件存储路径，文件名称前缀，并写到该路径下
            if (!changedData.isEmpty()) {
                fileNameList.add("Changed_" + shopId + "_0.xlsx");
                ExcelFileHandlerUtil.handleExport(changedData, UrlUtil.getUrl(), "Changed", shopId.toString(), ZhishuShopGoodsRequest.class);
            }
            if (!newData.isEmpty()) {
                fileNameList.add("New_" + shopId + "_0.xlsx");
                ExcelFileHandlerUtil.handleExport(newData, UrlUtil.getUrl(), "New", shopId.toString(), ZhishuShopGoodsRequest.class);
            }


            RedisUtils.setCacheObject("lastGoodsSynTime_" + shopId, request.getCurrentDateTime());

            if (!newData.isEmpty() || !changedData.isEmpty()) {
                // 查询店铺名称
                ShopVo shop = shopService.queryById(shopId);
                // 将任务信息插入到数据库中，创建一条任务
                TaskBo taskBo = new TaskBo();
                taskBo.setTaskType(TaskTypeEnum.SYNC_GOODS_KFZ.getCode());
                taskBo.setShopIds(shopId.toString());
                taskBo.setShopNames(shop.getShopName());
                taskBo.setFileName(String.join("/", fileNameList));
                taskBo.setDataNum((long) zhishuShopGoodsRequestList.size());
                taskBo.setTaskStatus("0");
                taskBo.setStatus("0");
                taskBo.setCreateBy(userId);
                taskServiceImpl.insertByBo(taskBo);
            }

            // 发送消息给前端告知拉取下来的数据已比对完毕
            scheduledExecutorService.schedule(() ->

            {
                SseMessageDto dto = new SseMessageDto();
                dto.setMessage("已拉取到商品数据总计：" + zhishuShopGoodsRequestList.size() + "条，新增：" + newData.size() + "条新数据，更新：" + changedData.size() + "条数据");
                dto.setUserIds(List.of(userId));
                SseMessageUtils.publishMessage(dto);
            }, 5, TimeUnit.SECONDS);
        } catch (Exception e) {
            // 捕获其他未知异常
            log.error("商品导入写入Excel过程中发生异常: {}", e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        } finally {
            // 取消定时任务
            if (future != null) {
                future.cancel(false);
            }
            // 关闭线程池
            if (scheduler != null) {
                scheduler.shutdownNow();
            }
            // 确保释放锁
            RedisUtils.deleteObject(lockKey);
            System.out.println("已释放redis锁");
        }

    }

    // 新增成员变量，用于存储分批处理的状态
    private final ConcurrentHashMap<Long, BatchProcessingContext> batchContextMap = new ConcurrentHashMap<>();

    /**
     * 分批比对商品
     */
    @Override
    public void batchGoodsComparison(BatchGoodsRequest request) {
        Long shopId = request.getShopId();
        Long userId = request.getUserId();

        // 获取或创建处理上下文
        BatchProcessingContext context = batchContextMap.computeIfAbsent(shopId, k -> {
            BatchProcessingContext newContext = new BatchProcessingContext();
            newContext.setShopId(shopId);
            newContext.setUserId(userId);
            newContext.setCurrentDateTime(request.getCurrentDateTime());
            newContext.setTotalBatches(request.getTotalBatches());

            // 初始化锁
            String lockKey = "WriteExcelKey_" + shopId;
            String lockValue = "WriteExcelLock";
            Duration lockExpireDuration = Duration.ofMinutes(30); // 延长锁时间
            RedisUtils.setCacheObject(lockKey, lockValue, lockExpireDuration);
            newContext.setLockKey(lockKey);

            return newContext;
        });

        try {
            // 处理当前批次数据
            processBatchData(request.getBatchData(), context);

            // 更新已接收批次计数
            int received = context.getReceivedBatches().incrementAndGet();

            // 如果是最后一批，完成处理
            if (request.getIsLastBatch() && received == context.getTotalBatches()) {
                completeBatchProcessing(context);
            }
        } catch (Exception e) {
            // 发生异常时清理资源
            cleanupBatchProcessing(context);
            throw new ServiceException("分批处理商品数据异常: " + e.getMessage() + "异常详情：" + e);
        }
    }

    /**
     * 处理单批数据
     */
    private void processBatchData(List<ZhishuShopGoodsRequest> batchData, BatchProcessingContext context) {
        List<String> artNoList = batchData.stream()
                .map(ZhishuShopGoodsRequest::getArtNo)
                .filter(Objects::nonNull)
                .filter(s -> !s.isEmpty())
                .distinct()
                .toList();

        // 查询数据库已有数据
        List<ZhishuShopGoods> alreadyExistList = Collections.emptyList();
        if (!artNoList.isEmpty()) {
            alreadyExistList = new LambdaQueryChainWrapper<>(baseMapper)
                    .in(ZhishuShopGoods::getArtNo, artNoList)
                    .list();
        }

        Map<String, ZhishuShopGoods> goodsHashMap = alreadyExistList.stream()
                .collect(Collectors.toMap(ZhishuShopGoods::getProductId, Function.identity()));

        // 分类处理当前批次数据
        for (ZhishuShopGoodsRequest request : batchData) {
            Boolean isChanged = false;

            if (!goodsHashMap.isEmpty()) {
                ZhishuShopGoods existingGoods = goodsHashMap.get(request.getItemNumber());
                if (existingGoods != null) {
                    // 检查数据是否有变化
                    if (!Objects.equals(request.getIsbn(), existingGoods.getIsbn())) {
                        isChanged = true;
                    }

                    double conditionCode = Math.round(request.getConditionCode().doubleValue()) / 10.0;
                    String conditionCodeString = CnumberUtils.getConditionCode(conditionCode);
                    if (!conditionCodeString.equals(existingGoods.getConditionCode())) {
                        isChanged = true;
                    }

                    if (!request.getInventory().equals(existingGoods.getInventory().intValue())) {
                        isChanged = true;
                    }

                    request.setId(existingGoods.getId());

                    if (isChanged) {
                        context.getAllChangedData().add(request);
                    }
                } else {
                    context.getAllNewData().add(request);
                }
            } else {
                context.getAllNewData().add(request);
            }
        }
    }

    /**
     * 完成批次处理
     */
    private void completeBatchProcessing(BatchProcessingContext context) {
        ScheduledExecutorService scheduler = null;
        ScheduledFuture<?> future = null;

        try {
            // 设置锁续期
            scheduler = Executors.newScheduledThreadPool(1);
            Runnable renewLockTask = () -> {
                RedisUtils.setCacheObject(context.getLockKey(), "WriteExcelLock", Duration.ofMinutes(30));
            };
            future = scheduler.scheduleAtFixedRate(renewLockTask, 0, 1, TimeUnit.MINUTES);

            // 处理所有数据
            List<String> fileNameList = new ArrayList<>();

            if (!context.getAllChangedData().isEmpty()) {
                fileNameList.add("Changed_" + context.getShopId() + "_0.xlsx");
                ExcelFileHandlerUtil.handleExport(
                        context.getAllChangedData(),
                        UrlUtil.getUrl(),
                        "Changed",
                        context.getShopId().toString(),
                        ZhishuShopGoodsRequest.class
                );
            }

            if (!context.getAllNewData().isEmpty()) {
                fileNameList.add("New_" + context.getShopId() + "_0.xlsx");
                ExcelFileHandlerUtil.handleExport(
                        context.getAllNewData(),
                        UrlUtil.getUrl(),
                        "New",
                        context.getShopId().toString(),
                        ZhishuShopGoodsRequest.class
                );
            }

            // 更新同步时间
            RedisUtils.setCacheObject("lastGoodsSynTime_" + context.getShopId(), context.getCurrentDateTime());

            if (!context.getAllNewData().isEmpty() || !context.getAllChangedData().isEmpty()) {
                // 查询店铺名称
                ShopVo shop = shopService.queryById(context.getShopId());

                // 创建任务
                TaskBo taskBo = new TaskBo();
                taskBo.setTaskType(TaskTypeEnum.SYNC_GOODS_KFZ.getCode());
                taskBo.setShopIds(context.getShopId().toString());
                taskBo.setShopNames(shop.getShopName());
                taskBo.setFileName(String.join("/", fileNameList));
                taskBo.setDataNum((long) (context.getAllNewData().size() + context.getAllChangedData().size()));
                taskBo.setTaskStatus("0");
                taskBo.setStatus("0");
                taskBo.setCreateBy(context.getUserId());
                taskServiceImpl.insertByBo(taskBo);
            }

            // 发送通知
            scheduledExecutorService.schedule(() -> {
                SseMessageDto dto = new SseMessageDto();
                dto.setMessage("已拉取到商品数据总计：" +
                        (context.getAllNewData().size() + context.getAllChangedData().size()) +
                        "条，新增：" + context.getAllNewData().size() +
                        "条新数据，更新：" + context.getAllChangedData().size() + "条数据");
                dto.setUserIds(List.of(context.getUserId()));
                SseMessageUtils.publishMessage(dto);
            }, 5, TimeUnit.SECONDS);
        } finally {
            // 清理资源
            if (future != null) {
                future.cancel(false);
            }
            if (scheduler != null) {
                scheduler.shutdownNow();
            }
            cleanupBatchProcessing(context);
        }
    }

    /**
     * 清理批次处理资源
     */
    private void cleanupBatchProcessing(BatchProcessingContext context) {
        if (context != null) {
            // 释放锁
            RedisUtils.deleteObject(context.getLockKey());
            // 移除上下文
            batchContextMap.remove(context.getShopId());
        }
    }

    /**
     * 根据用户选择货号规则将商品存入数据库
     *
     * @param saveGoodsVo
     */
    @Async
    @Override
    public void saveShopGoodsInDb(SaveGoodsVo saveGoodsVo) {
        System.out.println("开始根据用户选择货号规则将商品存入数据库");
        System.out.println("saveShopGoodsInDb：request-" + JSONObject.toJSONString(saveGoodsVo));
        // 指定读取需要新增的商品Excel文件路径
        String newGoodsExcelPath = Paths.get(UrlUtil.getUrl(), "New_" + saveGoodsVo.getShopId() + "_0.xlsx").toString();
        // 指定读取需要修改的商品Excel文件路径
        String updateGoodsExcelPath = Paths.get(UrlUtil.getUrl(), "Changed_" + saveGoodsVo.getShopId() + "_0.xlsx").toString();
        // 初期化任务对象
        TaskBo taskBo = new TaskBo();
        taskBo.setId(saveGoodsVo.getTaskId());

        // 尝试获取锁
        String lockKey = "ReadExcelKey_" + saveGoodsVo.getShopId();
        String lockValue = "ReadExcelLock";
        Duration lockExpireDuration = Duration.ofMinutes(2); // 设置锁的过期时间为2分钟
        String readExcelLock = RedisUtils.getCacheObject(lockKey);
        // 若获取存在说明存在读取该文件的线程，则直接返回，不进行后续操作
        if (ObjectUtil.isNotEmpty(readExcelLock)) throw new ServiceException("已在处理该文件，请勿重复操作");
        System.out.println("获取到redis锁，执行读取文件操作");
        // 若不存在，则设置锁，并执行后续操作
        RedisUtils.setCacheObject(lockKey, lockValue, lockExpireDuration);
        ScheduledExecutorService scheduler = null;
        ScheduledFuture<?> future = null;
        try {
            scheduler = Executors.newScheduledThreadPool(1);
            // 设置一个定时任务来不断延长锁的过期时间
            Runnable renewLockTask = () -> {
                RedisUtils.setCacheObject(lockKey, lockValue, lockExpireDuration);
                System.out.println("Redis锁过期时间已更新");
            };
            // 启动定时任务
            future = scheduler.scheduleAtFixedRate(renewLockTask, 0, INITIAL_DELAY_AND_PERIOD, TimeUnit.SECONDS);

            // 修改任务执行状态为执行中
            taskBo.setTaskStatus(TaskStatusTypeEnum.EXECUTING.getCode());
            taskServiceImpl.updateByBo(taskBo);

            // 分别定义两个列表，用于存储读取的数据
            List<ZhishuShopGoodsRequest> newDataList = new ArrayList<>();
            List<ZhishuShopGoodsRequest> updateDataList = new ArrayList<>();
            try {
                System.out.println("尝试读取新增的数据：path-" + newGoodsExcelPath);
                // 尝试读取新增的数据
                newDataList = EasyExcel.read(newGoodsExcelPath)
                        .head(ZhishuShopGoodsRequest.class)
                        .sheet("New_" + saveGoodsVo.getShopId() + "_0")
                        .doReadSync();
            } catch (Exception e) {
                // 读取不到说明没有对应需要处理的数据，不做处理，仅记录日志以防其他未知原因导致，不抛出异常
                System.out.println("未能读取新增数据文件: " + newGoodsExcelPath + "原因：{}" + e.getMessage());
            }
            try {
                System.out.println("尝试读取更新的数据：path-" + newGoodsExcelPath);
                // 尝试读取更新的数据
                updateDataList = EasyExcel.read(updateGoodsExcelPath)
                        .head(ZhishuShopGoodsRequest.class)
                        .sheet("Changed_" + saveGoodsVo.getShopId() + "_0")
                        .doReadSync();
            } catch (Exception e) {
                // 读取不到说明没有对应需要处理的数据，不做处理，仅记录日志以防其他未知原因导致，不抛出异常
                System.out.println("未能读取新增数据文件: " + updateGoodsExcelPath + "原因：{}" + e.getMessage());
            }

            // 查询当前任务状态，若任务状态为暂停/停止，说明存在未执行完数据，读取txt文件
            TaskVo taskVo = taskService.queryById(saveGoodsVo.getTaskId());
            AtomicInteger successMarkI;
            AtomicInteger failMarkI;
            if (TaskStatusTypeEnum.EXECUTE_PAUSE_STOP.getCode().equals(taskVo.getTaskStatus())) {
                // 初始化markI计数器用来统计处理成功的数据条数，AtomicInteger线程安全
                successMarkI = new AtomicInteger(taskVo.getDataNum().intValue() - (newDataList.size() + updateDataList.size()));
                // 初始化markI计数器用来统计处理失败的数据条数，AtomicInteger线程安全
                failMarkI = new AtomicInteger(newDataList.size() + updateDataList.size());
            } else if (TaskStatusTypeEnum.EXECUTED.getCode().equals(taskVo.getTaskStatus())) {
                return;
            } else {
                // 初始化markI计数器用来统计处理成功的数据条数，AtomicInteger线程安全
                successMarkI = new AtomicInteger(0);
                // 初始化markI计数器用来统计处理失败的数据条数，AtomicInteger线程安全
                failMarkI = new AtomicInteger(0);
            }

            // 将新增的和更新的数据合并到一起并写入文件
            writeAllDateToExcel(newDataList, updateDataList, saveGoodsVo.getShopId(), saveGoodsVo.getTaskId(), ZhishuShopGoodsRequest.class);

            // 总计读取数据条数
            Integer totalNum = newDataList.size() + updateDataList.size();
            // 根据商店id查询出对应的userId
            ShopVo shopVo = shopService.queryById(saveGoodsVo.getShopId());
            System.out.println("根据商店id查询出对应的userId：" + JSONObject.toJSONString(shopVo));
            Long userId = shopVo.getCreateBy();

            // 查询出该用户下所有货架
            List<FreightGoodsCountVo> freightGoodsCountList = baseMapper.selectFreightGoodsNumber(userId, saveGoodsVo.getFreightIdList());
            if (ObjectUtil.isEmpty(freightGoodsCountList))
                throw new ServiceException("该用户下或没有三级货区，请检查后重试");

            // 对新增的数据进行处理
            List<ZhishuShopGoodsRequest> failedInsertedList = new CopyOnWriteArrayList<>();
            List<ZhishuShopGoodsRequest> successInsertedList = new CopyOnWriteArrayList<>();
            if (ObjectUtil.isNotEmpty(newDataList)) {
                // 将 newDataList 分成 8 个批次
                int totalSize = newDataList.size();
                int batchSize = (int) Math.ceil((double) totalSize / 8);
                List<List<ZhishuShopGoodsRequest>> partitionedData = new ArrayList<>();
                for (int i = 0; i < totalSize; i += batchSize) {
                    int end = Math.min(i + batchSize, totalSize);
                    partitionedData.add(newDataList.subList(i, end));
                }
                // 使用 CopyOnWriteArrayList 确保线程安全
                CountDownLatch latch = new CountDownLatch(partitionedData.size());
                long newTime = System.currentTimeMillis();

                for (List<ZhishuShopGoodsRequest> subList : partitionedData) {
                    ThreadPoolUtils.execute(() -> {
                        try {
                            for (ZhishuShopGoodsRequest newData : subList) {
                                // TODO 新增数据处理逻辑
                                try {
                                    AtomicBoolean insertNewDataStatus = new AtomicBoolean(true);
                                    zhishuShopGoodsAopService.insertNewDataList(newData, userId, freightGoodsCountList, saveGoodsVo, failedInsertedList, successInsertedList, successMarkI, failMarkI, shopVo, totalNum, newTime, insertNewDataStatus, taskVo.getTaskType());
                                } catch (Exception e) {
                                    log.error(e.getMessage());
                                    failedInsertedList.add(newData);
                                }
                                // 将这条数据写入到异常记录中，后去完成后会删除
                                ExcelFileHandlerUtil.syncWriteRecord(UrlUtil.getUrl(), "Error_New_" + saveGoodsVo.getShopId() + "_" + Thread.currentThread().getId(), List.of(newData), "0");
                            }
                        } finally {
                            latch.countDown();
                        }
                    });
                }
                try {
                    latch.await(); // 等待所有线程完成
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    log.error("线程等待中断", e);
                }
                // 数据处理完毕删除异常文件
                ExcelFileHandlerUtil.deleteFilesByPrefix(UrlUtil.getUrl(), "Error_New_" + saveGoodsVo.getShopId());
                // 将这条数据写入到历史版本中
                if (!successInsertedList.isEmpty()) {
                    ExcelFileHandlerUtil.handleExport(successInsertedList, UrlUtil.getUrl(), "New", saveGoodsVo.getShopId().toString() + "_" + newTime, ZhishuShopGoodsRequest.class);
                }
                // 处理失败数据和文件删除
                if (!failedInsertedList.isEmpty()) {
                    ExcelFileHandlerUtil.handleExport(failedInsertedList, UrlUtil.getUrl(), "New", saveGoodsVo.getShopId().toString(), ZhishuShopGoodsRequest.class);
                } else {
                    FileUtil.fileDelete(newGoodsExcelPath);
                }
            }
            // 对更新的数据进行处理
            List<ZhishuShopGoodsRequest> failedUpdateList = new CopyOnWriteArrayList<>();
            List<ZhishuShopGoodsRequest> successUpdateList = new CopyOnWriteArrayList<>();
            if (ObjectUtil.isNotEmpty(updateDataList)) {
                // 将 updateDataList 分成 8 个批次
                int totalSize = updateDataList.size();
                int batchSize = (int) Math.ceil((double) totalSize / 8);
                List<List<ZhishuShopGoodsRequest>> partitionedData = new ArrayList<>();
                for (int i = 0; i < totalSize; i += batchSize) {
                    int end = Math.min(i + batchSize, totalSize);
                    partitionedData.add(updateDataList.subList(i, end));
                }
                CountDownLatch latch = new CountDownLatch(partitionedData.size());
                long updateTime = System.currentTimeMillis();
                for (List<ZhishuShopGoodsRequest> subList : partitionedData) {
                    ThreadPoolUtils.execute(() -> {
                        try {
                            for (ZhishuShopGoodsRequest changedData : subList) {
                                // TODO 更新数据处理逻辑
                                try {
                                    AtomicBoolean updateChangedDataStatus = new AtomicBoolean(true);
                                    zhishuShopGoodsAopService.updateChangedDataList(changedData, userId, freightGoodsCountList, saveGoodsVo, failedUpdateList, successUpdateList, successMarkI, failMarkI, shopVo, totalNum, updateTime, updateChangedDataStatus);
                                } catch (Exception e) {
                                    log.error(e.getMessage());
                                    failedUpdateList.add(changedData);
                                }
                                // 将这条数据写入到异常记录中，后去完成后会删除
                                ExcelFileHandlerUtil.syncWriteRecord(UrlUtil.getUrl(), "Error_Changed_" + saveGoodsVo.getShopId() + "_" + Thread.currentThread().getId(), List.of(changedData), "0");
                            }
                        } finally {
                            latch.countDown(); // 当前线程完成
                        }
                    });
                }
                try {
                    latch.await(); // 等待所有线程完成
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    log.error("线程等待中断", e);
                }
                // 数据处理完毕删除异常文件
                ExcelFileHandlerUtil.deleteFilesByPrefix(UrlUtil.getUrl(), "Error_Changed_" + saveGoodsVo.getShopId());
                // 将这条数据写入到历史版本中
                if (!successUpdateList.isEmpty()) {
                    ExcelFileHandlerUtil.handleExport(successUpdateList, UrlUtil.getUrl(), "Changed",
                            saveGoodsVo.getShopId().toString() + "_" + updateTime, ZhishuShopGoodsRequest.class);
                }
                // 处理失败数据和文件删除
                if (!failedUpdateList.isEmpty()) {
                    ExcelFileHandlerUtil.handleExport(failedUpdateList, UrlUtil.getUrl(), "Changed", saveGoodsVo.getShopId().toString(), ZhishuShopGoodsRequest.class);
                } else {
                    FileUtil.fileDelete(updateGoodsExcelPath);
                }
            }

            // 数据全部正常执行完毕，修改任务状态为已完成
            if (ObjectUtil.isNotEmpty(failedInsertedList) || ObjectUtil.isNotEmpty(failedUpdateList)) {
                // 若存在失败数据则修改任务状态为暂停/停止
                taskBo.setTaskStatus(TaskStatusTypeEnum.EXECUTE_PAUSE_STOP.getCode());
            } else {
                // 若不存在失败数据则修改任务状态为已完成
                taskBo.setTaskStatus(TaskStatusTypeEnum.EXECUTED.getCode());
            }
            taskServiceImpl.updateByBo(taskBo);

            // 发送消息给前端告知拉取下来的数据已下载完毕
            scheduledExecutorService.schedule(() -> {
                SseMessageDto dto = new SseMessageDto();
                dto.setMessage("成功新增：" + successInsertedList.size() + "条，新增失败：" + failedInsertedList.size() + "条，更新成功：" + successUpdateList.size() + "条,更新失败：" + failedUpdateList.size() + "条");
                dto.setUserIds(List.of(userId));
                SseMessageUtils.publishMessage(dto);
            }, 5, TimeUnit.SECONDS);

        } catch (Exception e) {
            // 若执行中出现异常，修改任务执行结束
            taskBo.setTaskStatus(TaskStatusTypeEnum.EXECUTE_PAUSE_STOP.getCode());
            taskServiceImpl.updateByBo(taskBo);
            // 捕获其他未知异常
            log.error("读取商品导入Excel过程中发生异常: {}", e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        } finally {
            // 取消定时任务
            if (future != null) {
                future.cancel(false);
            }
            // 关闭线程池
            if (scheduler != null) {
                scheduler.shutdownNow();
            }
            // 确保释放锁
            RedisUtils.deleteObject(lockKey);
            System.out.println("已释放redis锁");
        }
    }


    /**
     * 将全部数据写入到Excel中
     *
     * @param newDataList
     * @param updateDataList
     * @param shopId
     * @param taskId
     * @param clazz
     * @param <T>
     */
    private <T> void writeAllDateToExcel(List<T> newDataList, List<T> updateDataList, Long shopId, Long taskId, Class<T> clazz) {
        List<T> allDataList = new ArrayList<>();
        allDataList.addAll(newDataList);
        allDataList.addAll(updateDataList);
        EasyExcelUtil.exportToExcel(UrlUtil.getUrl(), taskId + "" + shopId + ".xlsx", allDataList, "0", clazz);
    }

    @Override
    public ProductForm repeatBook(ProductForm form) {
        Long userId = sysUserMapper.selectUserIdByNameAndPassWord(form.getPhoneNumber());
        Long depotId = TDepotMapper.getDepotIdByName(form.getDepotName(), userId);
        Long shelvesId = TShelvesMapper.getShelvesIdByName(form.getShelvesName(), depotId);
        Long freightId = TFreightMapper.getFreightIdByName(form.getFreightName(), shelvesId);
        // 获取品相数值
        String conCode = null;
        String chineseName = form.getConditionCode();
        String letterCode = null;
        if (CnumberUtils.CHINESE_TO_CODE_MAP.containsKey(chineseName)) {
            // String letterCode = CnumberUtils.CHINESE_TO_CODE_MAP.get(chineseName);
            letterCode = CnumberUtils.CHINESE_TO_CODE_MAP.get(chineseName);
            for (Map.Entry<Double, String> entry : CnumberUtils.CODE_MAP.entrySet()) {
                if (entry.getValue().equals(letterCode)) {
                    conCode = String.valueOf(entry.getKey());
                    break;
                }
            }
        }
        if (conCode == null) {
            throw new IllegalArgumentException("无效的中文品相名称: " + chineseName);
        }
        String artNo = cnumberUtils.getArtNo(Double.valueOf(conCode), userId, form.getBarcode(), depotId, shelvesId, freightId, null);
        System.out.println("重复商品货号为：" + artNo);
        // 查询对应的图片

        Long count = baseMapper.selectArtNoCount1(artNo, form.getPrice(), letterCode);
        System.out.println("重复商品数量为：" + count);
        String shopId = baseMapper.selectArtNoCount(artNo, form.getPrice());
        System.out.println("重复商品ID为：" + shopId);
        String image = baseMapper.queryByShopId(shopId);
        System.out.println("重复商品图片为：" + image);
        ProductForm productForm = new ProductForm();
        productForm.setImage(image);
        productForm.setArtNo(artNo);
        productForm.setCount(count);
        productForm.setName(form.getName());
        System.out.println("==============" + productForm);
        return productForm;
    }

    /**
     * 根据库存操作类型操作库存并同步平台库存
     *
     * @param operationType
     * @param shopGoodsPublishedVo
     * @param count
     * @return
     */
    @Override
    public Boolean operatingGoodsInventory(Long shopId, Integer shopType, Integer operationType, ShopGoodsPublishedVo shopGoodsPublishedVo, Integer count, String orderSn) {
        Integer type;
        if (operationType == 1) {
            // 退单添加
            type = 3;
        } else {
            // 订单减扣
            type = 2;
        }
        Boolean result = operatingInventory(operationType, shopGoodsPublishedVo.getShopGoodsId(), count, type, orderSn, null);
        Assert.isTrue(result, "操作redis/数据库库存失败");
        // 根据商品Id查询出拥有同商品的店铺Id和平台商品Id
        List<ShopGoodsPublishedVo> shopGoodsPublishedVoList = shopGoodsPublishedService.queryByShopGoodsId(shopGoodsPublishedVo.getShopGoodsId());

        // 若是订单扣减或是孔夫子平台操作则去除掉自己
        if (type == 2 || shopType == 2) {
            // 过滤掉自己的
            shopGoodsPublishedVoList = shopGoodsPublishedVoList.stream().filter(o -> !o.getShopId().equals(shopId.toString())).toList();
        }
        System.out.println("shopGoodsPublishedVoList:" + shopGoodsPublishedVoList+"zhuxiaodong1028");

        // 循环根据店铺Id查询出店铺信息
        for (ShopGoodsPublishedVo goodsPublishedVo : shopGoodsPublishedVoList) {
            // 根据店铺Id查询出店铺信息
            ShopVo shop = shopService.queryById(Long.valueOf(goodsPublishedVo.getShopId()));
            if (shop == null){
                shopGoodsPublishedService.deleteWithValidByIds(List.of(goodsPublishedVo.getId()), true);
                continue;
            }
            // 根据店铺类型分别推送平台同步库存
            InventorySynchronizedStrategy strategy = InventorySynchronizedStrategyFactory.getStrategy(shop.getShopType());
            Objects.requireNonNull(strategy).inventorySynchronized(shop, goodsPublishedVo,type);
        }
        return true;
    }

    @Override
    public Boolean goofishoperatingGoodsInventory(Long shopId, Integer shopType, Integer operationType, ZhishuShopGoodsVo zhishuShopGoodsVo, Integer count, String orderSn) {
        Integer type;
        if (operationType == 1) {
            // 退单添加
            type = 3;
        } else {
            // 订单减扣
            type = 2;
        }
        Boolean result = operatingInventory(operationType, zhishuShopGoodsVo.getId(), count, type, orderSn, null);
        Assert.isTrue(result, "操作redis/数据库库存失败");
        // 根据商品Id查询出拥有同商品的店铺Id和平台商品Id
        List<ShopGoodsPublishedVo> shopGoodsPublishedVoList = shopGoodsPublishedService.queryByShopGoodsId(zhishuShopGoodsVo.getId());

        // 若是订单扣减或是孔夫子平台操作则去除掉自己
        if (type == 2 || shopType == 2) {
            // 过滤掉自己的
            shopGoodsPublishedVoList = shopGoodsPublishedVoList.stream().filter(o -> !o.getShopId().equals(shopId.toString())).toList();
        }
        System.out.println("shopGoodsPublishedVoList:" + shopGoodsPublishedVoList+"zhuxiaodong1028");

        // 循环根据店铺Id查询出店铺信息
        for (ShopGoodsPublishedVo goodsPublishedVo : shopGoodsPublishedVoList) {
            // 根据店铺Id查询出店铺信息
            ShopVo shop = shopService.queryById(Long.valueOf(goodsPublishedVo.getShopId()));
            if (shop == null){
                shopGoodsPublishedService.deleteWithValidByIds(List.of(goodsPublishedVo.getId()), true);
                continue;
            }
            // 根据店铺类型分别推送平台同步库存
            InventorySynchronizedStrategy strategy = InventorySynchronizedStrategyFactory.getStrategy(shop.getShopType());
            Objects.requireNonNull(strategy).inventorySynchronized(shop, goodsPublishedVo,type);
        }
        return true;
    }

    /**
     * Excel文件处理
     *
     * @param filePath
     */
    private void fileProcessing(String filePath) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        Path source = Paths.get(filePath);
        Path target = Paths.get(UrlUtil.getUrl(), source.getFileName().toString().replace(".xlsx", "_" + timestamp + ".xlsx"));
        try {
            // 文件移动
            Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            log.error("文件移动失败: {}", e.getMessage());
        }
    }

    /**
     * 货号处理
     *
     * @param saveArtNoRule       保存商品规则：0-不修改直接保存货号 1-按照系统默认规则保存货号
     * @param conditionCode       品相码（如9.5/8.0）
     * @param userId              用户Id
     * @param isbn                ISBN
     * @param oldArtNo            原始货号
     * @param freightGoodsCountVo 货区信息
     * @return
     */
    @Override
    public String artNoProcessing(Integer saveArtNoRule, Long userId, String isbn, String oldArtNo, double conditionCode, FreightGoodsCountVo freightGoodsCountVo) {
        // 若保存商品规则：1-按照系统默认规则保存货号
        if (saveArtNoRule == 1) {
            // 若传入货号为null或空字符串""
            return cnumberUtils.getArtNo(conditionCode, userId, isbn, freightGoodsCountVo.getDepotId(), freightGoodsCountVo.getShelvesId(), freightGoodsCountVo.getFreightId(), "A");
        }
        // 若保存商品规则：0-不修改直接保存货号 ，则不做处理直接返回原本的货号
        // 或其他暂时未知情况货号规则，暂时先返回原本货号
        return oldArtNo;
    }


    /**
     * 随机修改孔夫子货号（仅测试使用）
     */
    @Override
    public void randomUpdateArtNo(Long userId, Long shopId) {
        List<ZhishuShopGoods> list = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(ZhishuShopGoods::getUserId, userId)
                .list();
        for (ZhishuShopGoods zhishuShopGoods : list) {
            UpdateArtNoRequest request = new UpdateArtNoRequest();
            request.setShopId(shopId);
            request.setProductId(Long.valueOf(zhishuShopGoods.getProductId()));
            request.setArtNo(generateRandomString());
            try {
                kfzClient.updateArtNo(UrlUtil.getKfzServiceUrl(), request);
            } catch (Exception e) {
                log.error("同步货号失败：{}", e.getMessage());
            }
        }

    }

    @Override
    public void goodsAdd(Map map) {
        // 获取用户系统库数据
        Long userId;
        if (map.get("userId") != null && StringUtils.isNotEmpty(map.get("userId").toString())) {
            userId = Long.parseLong(map.get("userId").toString());
        } else {
            userId = LoginHelper.getUserId();
        }
        // 店铺ids
        List<String> shopIdList = (List<String>) map.get("shopIds");
        // 商品信息download
        List<List> bookList = map.get("bookList") == null ? new ArrayList<>() : (List<List>) map.get("bookList");

        for (String shopId : shopIdList) {
            ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
            if (shopService.checkUsageCount(shopVo) == 0){
                // 无可用额度
                continue;
            }
            Map createMap = new HashMap();
            createMap.put("shop_id",shopVo.getId().toString());
            createMap.put("shop_type",shopVo.getShopType());
            createMap.put("task_count",bookList.size()+"");
            createMap.put("task_type","8");

            // 图片类型 1 仅官图  2 仅实拍图  11 优先实拍图  12 优先官图
            String imageSelect = map.get("imageSelect").toString();
            // 对应 1 仅官图 2 仅实拍图  3 优先官图  4 优先实拍图
            switch (imageSelect){
                case "1","2":createMap.put("img_type",imageSelect);break;
                case "3":createMap.put("img_type","2");break;
                case "12":createMap.put("img_type","3");break;
                case "11":createMap.put("img_type","4");break;
            }

            String createResStr = InterfaceUtils.postFormWithSign(UrlUtil.getNewTaskUrl(),"/task/create",createMap);
            map.put("createResStr",createResStr);



            // 执行线程
            ShopGoodsTaskRunnable shopGoodsTaskRunnable = new ShopGoodsTaskRunnable(this, map, userId,shopVo);
            Thread thread = new Thread(shopGoodsTaskRunnable, "yxy-goodsAdd");
            thread.start();

        }

    }

    @Override
    public void goodsAutoAdd(Map map) {
        // 获取用户系统库数据
        Long userId;
        if (map.get("userId") != null && StringUtils.isNotEmpty(map.get("userId").toString())) {
            userId = Long.parseLong(map.get("userId").toString());
        } else {
            userId = LoginHelper.getUserId();
        }
        // 店铺ids
        List<String> shopIdList = (List<String>) map.get("shopIds");
        // 商品信息
        List<List> bookList = (List<List>) map.get("bookList");

        String shopIds = "";
        String shopNames = "";
        String isbn = bookList.get(0).get(1).toString();
        String bookName = bookList.get(0).get(2).toString();
        String artNo = bookList.get(0).get(6) == null ? "" : bookList.get(0).get(6).toString();

        for (String shopId : shopIdList) {
            ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
            if (shopNames.equals("")) {
                shopIds = shopId;
                shopNames = shopVo.getShopName();
            } else {
                shopIds = shopIds + "," + shopId;
                shopNames = shopNames + "," + shopVo.getShopName();
            }
        }
        TaskBo taskBo = new TaskBo();
        // 存储任务信息
        taskBo.setTaskType("1");
        taskBo.setFileName("小程序-"+bookName+"-"+isbn+"-"+artNo);
        taskBo.setShopIds(shopIds);
        taskBo.setShopNames(shopNames);
        taskBo.setDataNum(Long.parseLong(bookList.size() + ""));
        taskBo.setTaskStatus("0");
        taskBo.setCreateBy(userId);
        taskService.insertByBo(taskBo);
        goodsAdd2(map, taskBo, userId);
    }

    public void goodsAdd2(Map map, TaskBo taskBo, Long userId) {

        String pati = map.get("X-PDD-Pati") == null ? "" : map.get("X-PDD-Pati").toString();

        // 线程锁对象初始化
        lockMap.put(String.valueOf(Thread.currentThread().getId()), new Object());
        runMap.put(String.valueOf(Thread.currentThread().getId()), false);

        String mark = map.get("mark") != null ? map.get("mark").toString() : "";
        //分类
        String categoryId = map.get("categoryId") != null ? map.get("categoryId").toString() : "";

        // 店铺ids
        List<String> shopIdList = (List<String>) map.get("shopIds");
        // 商品信息
        List<List> bookList = (List<List>) map.get("bookList");

        for (String shopId : shopIdList) {
            ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
            //如果是孔夫子店铺则等待十秒钟
            if(shopVo.getShopType().equals("2")){
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    System.out.println("睡眠失败");
                }
            }
            for (List list : bookList) {
                taskWait(String.valueOf(Thread.currentThread().getId()));

                String goodsId = list.get(0).toString();
                String isbn = list.get(1).toString();
                String bookName = list.get(2).toString();
                String price = new BigDecimal(list.get(3).toString()).divide(new BigDecimal(100)).toString();

                String stock = list.get(4).toString();
                // 品相
                String conditionCode = list.get(5) == null ? "" : list.get(5).toString();
                String artNo = list.get(6) == null ? "" : list.get(6).toString();
                // 运费
                String templateMinPrice = list.get(7) == null ? "" : list.get(7).toString();

                //先获取redis是否存在该商品的自拍图
                Object zhishuShopImagesVoObj = RedisUtils.getSecondCacheObject(goodsId+"-img");
                if(zhishuShopImagesVoObj == null){
                    List<ZhishuShopImagesVo> zhishuShopImagesVoList = zhishuShopImagesService.selectShopImagesByShopId(goodsId);
                    if(!zhishuShopImagesVoList.isEmpty()){
                        RedisUtils.setSecondCacheObject(goodsId+"-img",JsonUtil.transferToJson(zhishuShopImagesVoList));
                    }
                }

                Map goMap = new HashMap();
                goMap.put("priority", "1");
                goMap.put("retry_count", "3");
                goMap.put("isbn", isbn);
                goMap.put("totalPrice", price);
                goMap.put("stock", stock);
                goMap.put("bookName", bookName);
                goMap.put("code", "");
                goMap.put("imgBigUrl", "");
                goMap.put("artNo", artNo);
                goMap.put("taskId", taskBo.getId().toString());
                goMap.put("shopId", shopId);
                goMap.put("imageSelect", "12");
                goMap.put("goodsId", goodsId);
                goMap.put("conditionCode", conditionCode);
                goMap.put("mark", map.get("mark"));
                goMap.put("templateMinPrice", templateMinPrice);
                goMap.put("categoryId", categoryId);

                System.out.println("task_verifyPricePublishGoods接口"+goMap);

                try {
                    InterfaceUtils.postForm("http://146.56.192.164:10098", "/api/task_verifyPricePublishGoods", goMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        lockMap.remove(String.valueOf(Thread.currentThread().getId()));
        runMap.remove(String.valueOf(Thread.currentThread().getId()));
    }


    @Override
    public void goodsAdd(Map map, Long userId,ShopVo shopVo) {
        // 获取余额
        Long usageCount = shopService.checkUsageCount(shopVo);

        // 商品信息download
        List<List> bookList = map.get("bookList") == null ? new ArrayList<>() : (List<List>) map.get("bookList");
        ZhishuShopGoodsBo bo =  map.get("params") != null ? MapUtils.convertToObject((Map) map.get("params"),ZhishuShopGoodsBo.class) : null;
        if(bo == null){
            bo = new ZhishuShopGoodsBo();
            bo.setIsQueryAllGoods(1);
        }
        bo.setUserId(userId);
        int pageNum = 1,pageSize = 1000;
        //查询全部自营商品数据一键发布
        PageQuery pageQuery = new PageQuery(pageSize,pageNum);
        String createResStr = map.get("createResStr").toString();
        Map createResMap = JsonUtil.transferToObj(createResStr,Map.class);
        String taskId = createResMap.get("data").toString();
        List<Map<String,Object>> bodyList = new ArrayList<>();
        if (usageCount  > 0){
            if(bookList.isEmpty()){
                //一键发布
                while (true){
                    pageQuery.setPageNum(pageNum);
                    pageQuery.setPageSize(pageSize);
                    Page<ZhishuShopGoodsVo> pageList =  queryPageList2(bo, pageQuery);

                    List<ZhishuShopGoodsVo> zhishuShopGoodsVoList = pageList.getRecords();
                    // 提取列表中的全部商品id
                    List<Long> shopGoodsIds = zhishuShopGoodsVoList.stream()
                            .map(vo -> Long.valueOf(vo.getId()))  // String转Long
                            .collect(Collectors.toList());
                    // 查询是否存在商品记录
                    List<ShopGoodsPublishedVo> result = shopGoodsPublishedService.selectByShopGoodsIds(shopGoodsIds,shopVo.getId());
                    // 提取查询到的已存在发布记录的商品id
                    Set<Long> publishedGoodsIds = result.stream()
                            .map(vo -> Long.valueOf(vo.getShopGoodsId()))
                            .collect(Collectors.toSet());


                    // 过滤掉已发布的商品（即不在publishedGoodsIds中的保留）
                    List<ZhishuShopGoodsVo> filteredList = zhishuShopGoodsVoList.stream()
                            .filter(vo -> !publishedGoodsIds.contains(Long.valueOf(vo.getId())))
                            .collect(Collectors.toList());

                    // 替换原列表（如果需要）
                    zhishuShopGoodsVoList = filteredList;

                    for (ZhishuShopGoodsVo zhishuShopGoodsVo : zhishuShopGoodsVoList){
                        String goodsId = zhishuShopGoodsVo.getId();
                        String isbn = zhishuShopGoodsVo.getIsbn();
                        String bookName = zhishuShopGoodsVo.getGoodsName();
                        String price = zhishuShopGoodsVo.getPrice().divide(new BigDecimal(100)).toString();
                        String stock = zhishuShopGoodsVo.getInventory().toString();
                        // 品相
                        String conditionCode = StringUtils.isEmpty(zhishuShopGoodsVo.getConditionCode()) ? "" : zhishuShopGoodsVo.getConditionCode();
                        String artNo = StringUtils.isEmpty(zhishuShopGoodsVo.getArtNo()) ? "" : zhishuShopGoodsVo.getArtNo();
                        // 运费
                        String templateMinPrice = zhishuShopGoodsVo.getTemplateMinPrice() == null ? "" : zhishuShopGoodsVo.getTemplateMinPrice().toString();
                        List<ZhishuShopImagesVo> zhishuShopImagesVoList = zhishuShopImagesService.selectShopImagesByShopId(goodsId);
                        Map body = new HashMap();
                        Map bookInfo = new HashMap();
                        bookInfo.put("isbn",isbn);
                        bookInfo.put("book_name",bookName);
                        if(!zhishuShopImagesVoList.isEmpty()){
                            JSONObject imageObject = new JSONObject();
                            List<String> carouselUrlArray = new ArrayList<>();
                            for (ZhishuShopImagesVo zhishuShopImagesVo : zhishuShopImagesVoList){
                                String path = zhishuShopImagesVo.getPath();
                                // 只有拼多多店铺并且是孔夫子图片上传图片
                                if(path.contains("www0.kfzimg.com") && shopVo.getShopType().equals("1")){
                                    path = path.replace("_s","_n");
                                    Map imgMap = new HashMap();
                                    imgMap.put("shop_id",shopVo.getId().toString());
                                    imgMap.put("img_url",path);
                                    String pddImgData =  InterfaceUtils.postFormWithSign(UrlUtil.getNewTaskUrl(),"/uploadImg/ImgUploadToPdd",imgMap);
                                    Map pddImgMap = JsonUtil.transferToObj(pddImgData,Map.class);
                                    if (pddImgMap.get("code").equals("200")){
                                        path = pddImgMap.get("data").toString();
                                    }
                                }
                                carouselUrlArray.add(path);
                            }
                            imageObject.put("carousel_url_array",carouselUrlArray);
                            bookInfo.put("image_object",imageObject);
                        }
                        body.put("book_info",bookInfo);
                        Map detail = new HashMap();
                        BigDecimal totalPrice = new BigDecimal(price).multiply(new BigDecimal(100));
                        detail.put("price",totalPrice.longValue());
                        detail.put("stock",Long.parseLong(stock));
                        // 商品编码
                        detail.put("out_goods_id",isbn);
                        // 规格编码
                        detail.put("sku_code",artNo);
                        // 运费
                        detail.put("shipping_cost",new BigDecimal(templateMinPrice).multiply(new BigDecimal(100)).longValue());
                        // 品相
                        detail.put("condition",Integer.parseInt(CnumberUtils.getQualityNum(conditionCode)));
                        // 上下架状态
                        detail.put("is_onsale",0);
                        //商品id
                        JSONObject json = new JSONObject();
                        json.put("erp_goods_id",goodsId);
                        json.put("user_id",userId+"");
                        detail.put("msg",json.toString());
                        body.put("detail",detail);
                        bodyList.add(body);
                        if (bodyList.size() % 1000 == 0){
                            String response = InterfaceUtils.postTaskBodyWithSign(UrlUtil.getNewTaskUrl(), "/task/setTaskBody", taskId, bodyList);
                            System.out.println("新发布任务发布"+bodyList.size()+"条");
                            // 清空列表，准备下一批
                            bodyList.clear();
                        }
                    }
                    if (!bodyList.isEmpty()) {
                        String response = InterfaceUtils.postTaskBodyWithSign(UrlUtil.getNewTaskUrl(), "/task/setTaskBody", taskId, bodyList);
                        System.out.println("新发布任务发布"+bodyList.size()+"条");
                        // 清空列表，准备下一批
                        bodyList.clear();
                    }
                    pageNum++;

                    usageCount--;
                    //获取总数
                    if((pageList.getTotal() / 1000 + 1) < pageNum || pageList.getRecords().isEmpty() || usageCount == 0){
                        break;
                    }
                }
            }else{

                // 提取列表中的全部商品id
                List<Long> shopGoodsIds = bookList.stream()
                        .map(vo -> Long.valueOf(vo.get(0).toString()))  // String转Long
                        .collect(Collectors.toList());
                // 查询是否存在商品记录
                List<ShopGoodsPublishedVo> result = shopGoodsPublishedService.selectByShopGoodsIds(shopGoodsIds,shopVo.getId());
                // 提取查询到的已存在发布记录的商品id
                Set<Long> publishedGoodsIds = result.stream()
                        .map(vo -> Long.valueOf(vo.getShopGoodsId()))
                        .collect(Collectors.toSet());

                // 过滤掉已发布的商品（即不在publishedGoodsIds中的保留）
                List filteredList = bookList.stream()
                        .filter(vo -> !publishedGoodsIds.contains(Long.valueOf(vo.get(0).toString())))
                        .collect(Collectors.toList());

                // 替换原列表（如果需要）
                bookList = filteredList;

                for (List list : bookList) {
                    String goodsId = list.get(0).toString();
                    String isbn = list.get(1).toString();
                    String bookName = list.get(2).toString();
                    String price = new BigDecimal(list.get(3).toString()).divide(new BigDecimal(100)).toString();
                    String stock = list.get(4).toString();
                    // 品相
                    String conditionCode = list.get(5) == null ? "" : list.get(5).toString();
                    String artNo = list.get(6) == null ? "" : list.get(6).toString();
                    // 运费
                    String templateMinPrice = list.get(7) == null ? "" : list.get(7).toString();
                    List<ZhishuShopImagesVo> zhishuShopImagesVoList = zhishuShopImagesService.selectShopImagesByShopId(goodsId);
                    Map body = new HashMap();
                    Map bookInfo = new HashMap();
                    bookInfo.put("isbn",isbn);
                    bookInfo.put("book_name",bookName);
                    if(!zhishuShopImagesVoList.isEmpty()){
                        JSONObject imageObject = new JSONObject();
                        List<String> carouselUrlArray = new ArrayList<>();
                        for (ZhishuShopImagesVo zhishuShopImagesVo : zhishuShopImagesVoList){
                            String path = zhishuShopImagesVo.getPath();
                            if(path.contains("www0.kfzimg.com")){
                                path = path.replace("_s","_n");
                                Map imgMap = new HashMap();
                                imgMap.put("shop_id",shopVo.getId().toString());
                                imgMap.put("img_url",path);
                                String pddImgData =  InterfaceUtils.postFormWithSign(UrlUtil.getNewTaskUrl(),"/uploadImg/ImgUploadToPdd",imgMap);
                                Map pddImgMap = JsonUtil.transferToObj(pddImgData,Map.class);
                                if (pddImgMap.get("code").equals("200")){
                                    path = pddImgMap.get("data").toString();
                                }
                            }
                            carouselUrlArray.add(path);
                        }
                        imageObject.put("carousel_url_array",carouselUrlArray);
                        bookInfo.put("image_object",imageObject);
                    }
                    body.put("book_info",bookInfo);
                    Map detail = new HashMap();
                    BigDecimal totalPrice = new BigDecimal(price).multiply(new BigDecimal(100));
                    detail.put("price",totalPrice.longValue());
                    detail.put("stock",Long.parseLong(stock));
                    // 商品编码
                    detail.put("out_goods_id",isbn);
                    // 规格编码
                    detail.put("sku_code",artNo);
                    // 运费
                    detail.put("shipping_cost",new BigDecimal(templateMinPrice).multiply(new BigDecimal(100)).longValue());
                    // 品相
                    detail.put("condition",Integer.parseInt(CnumberUtils.getQualityNum(conditionCode)));
                    // 上下架状态
                    detail.put("is_onsale",0);
                    // erp 商品id
                    JSONObject json = new JSONObject();
                    json.put("erp_goods_id",goodsId);
                    json.put("user_id",userId+"");
                    detail.put("msg",json.toString());
                    body.put("detail",detail);
                    bodyList.add(body);
                    if (bodyList.size() % 1000 == 0){
                        String response = InterfaceUtils.postTaskBodyWithSign(UrlUtil.getNewTaskUrl(), "/task/setTaskBody", taskId, bodyList);
                        System.out.println("新发布任务发布"+bodyList.size()+"条");
                        // 清空列表，准备下一批
                        bodyList.clear();
                    }

                    usageCount--;
                    if (usageCount == 0){
                        break;
                    }
                }
                // 处理剩余数据
                if (!bodyList.isEmpty()) {
                    String response = InterfaceUtils.postTaskBodyWithSign(UrlUtil.getNewTaskUrl(), "/task/setTaskBody", taskId, bodyList);
                    System.out.println("新发布任务发布结束："+bodyList.size()+"条");
                }
            }


            // 更新使用次数
            shopService.updateUsageCount(shopVo,usageCount);
        }
    }

    // 线程暂停
    public void taskWait(String threadId) {
        if (runMap.get(threadId)) {
            try {
                synchronized (lockMap.get(threadId)) {
                    lockMap.get(threadId).wait();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public int zanTing(String threadId) {
        if (runMap.get(threadId) == null) {
            return 0;
        }
        runMap.put(threadId, true);
        return 1;
    }

    @Override
    public int huanXing(String threadId) {
        if (lockMap.get(threadId) == null) {
            return 0;
        }
        synchronized (lockMap.get(threadId)) {
            runMap.put(threadId, false);
            lockMap.get(threadId).notify();
        }
        return 1;
    }

    @Override
    public List<StockChangeLogVo> selectShopStockLog(String id) {
        List<StockChangeLogVo> list = baseMapper.selectStockLog(id);
        try{
            if (!list.isEmpty()) {
                Map params = new HashMap<>();
                params.put("jsonList",JsonUtil.transferToJson(list));
                String result = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/erpGoodsOrder/handleShopStockLog",params);
                list = JsonUtil.transferToObj(result,List.class);
            }
        } catch (Exception e){
            System.out.println("关联数据查询失败");
        }
        return list;
    }

    @Override
    public Integer queryInventory(Long shopGoodsId) {
        String inventoryKey = "zhishu_shop_goods_inventory:" + shopGoodsId;
        // 获取当前库存数量
        RList<Object> inventoryList = RedisUtils.getClient().getList(inventoryKey);
        int currentInventorySize = inventoryList.size();
        if (currentInventorySize == 0) {
            return 0;
        } else {
            return currentInventorySize;
        }
    }

    @Override
    public List<AuthorPressVo> getAuthorAndPublisher(String keyword, String cookies) {
        // 定义两个URL
        String authorUrl = "https://search.kongfz.com/pc-gw/search-web/client/pc/product/keyword/more/author/facet";
        String pressUrl = "https://search.kongfz.com/pc-gw/search-web/client/pc/product/keyword/more/press/facet";

        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("keyword", keyword);

        // 存储结果的列表
        List<AuthorPressVo> resultList = new ArrayList<>();

        try {
            // 构建作者查询URL
            StringBuilder authorUrlWithParams = new StringBuilder(authorUrl);
            if (!params.isEmpty()) {
                authorUrlWithParams.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String encodedKey = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8);
                    String encodedValue = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8);
                    authorUrlWithParams.append(encodedKey).append("=").append(encodedValue).append("&");
                }
                authorUrlWithParams.deleteCharAt(authorUrlWithParams.length() - 1);
            }

            // 构建出版社查询URL
            StringBuilder pressUrlWithParams = new StringBuilder(pressUrl);
            if (!params.isEmpty()) {
                pressUrlWithParams.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String encodedKey = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8);
                    String encodedValue = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8);
                    pressUrlWithParams.append(encodedKey).append("=").append(encodedValue).append("&");
                }
                pressUrlWithParams.deleteCharAt(pressUrlWithParams.length() - 1);
            }

            // 构建HTTP客户端
            HttpClient client = HttpClient.newBuilder()
                    .executor(Executors.newFixedThreadPool(20))
                    .connectTimeout(Duration.ofSeconds(5))
                    .version(HttpClient.Version.HTTP_2)
                    .followRedirects(HttpClient.Redirect.NORMAL)
                    .proxy(ProxySelector.getDefault())
                    .build();

            // 发送作者查询请求
            HttpRequest authorRequest = HttpRequest.newBuilder()
                    .uri(URI.create(authorUrlWithParams.toString()))
                    .header("Cookie", "PHPSESSID=" + cookies)
                    .GET()
                    .build();

            // 发送出版社查询请求
            HttpRequest pressRequest = HttpRequest.newBuilder()
                    .uri(URI.create(pressUrlWithParams.toString()))
                    .header("Cookie", "PHPSESSID=" + cookies)
                    .GET()
                    .build();

            // 执行请求并获取响应
            HttpResponse<String> authorResponse = client.send(authorRequest, HttpResponse.BodyHandlers.ofString());
            HttpResponse<String> pressResponse = client.send(pressRequest, HttpResponse.BodyHandlers.ofString());

            // 解析作者响应
            if (authorResponse.statusCode() == 200) {
                JSONObject authorJson = JSON.parseObject(authorResponse.body());
                if (authorJson != null && authorJson.getJSONObject("data") != null) {
                    JSONArray authorLabels = authorJson.getJSONObject("data").getJSONArray("labels");
                    if (authorLabels != null) {
                        for (int i = 0; i < authorLabels.size(); i++) {
                            JSONObject label = authorLabels.getJSONObject(i);
                            AuthorPressVo vo = new AuthorPressVo();
                            vo.setAuthor(label.getString("showName"));
                            resultList.add(vo);
                        }
                    }
                }
            }

            // 解析出版社响应
            if (pressResponse.statusCode() == 200) {
                JSONObject pressJson = JSON.parseObject(pressResponse.body());
                if (pressJson != null && pressJson.getJSONObject("data") != null) {
                    JSONArray pressLabels = pressJson.getJSONObject("data").getJSONArray("labels");
                    if (pressLabels != null) {
                        for (int i = 0; i < pressLabels.size(); i++) {
                            JSONObject label = pressLabels.getJSONObject(i);
                            AuthorPressVo vo = new AuthorPressVo();
                            vo.setPress(label.getString("showName"));
                            resultList.add(vo);
                        }
                    }
                }
            }

        } catch (Exception e) {
            log.error("获取作者和出版社信息失败: {}", e.getMessage(), e);
            throw new ServiceException("获取作者和出版社信息失败: " + e.getMessage());
        }

        return resultList;
    }


    @Override
    public ProductSubmitResultVo submitFromCopyrightPage(ProductForm form) {
        // 书名去除首位空格
        form.setName(form.getName().trim());
        String depotName = form.getDepotName();
        if (StringUtils.isBlank(depotName)) {
            throw new IllegalArgumentException("仓库名称不能为空");
        }

        Long userId = sysUserMapper.selectUserIdByNameAndPassWord(form.getPhoneNumber());
        Long depotId = TDepotMapper.getDepotIdByName(depotName, userId);
        Long shelvesId = TShelvesMapper.getShelvesIdByName(form.getShelvesName(), depotId);
        //获取三级货区信息
        TFreightVo freightVo = TFreightMapper.selectByFreightName(form.getFreightName(), shelvesId);
        Long freightId = freightVo.getId();
        // 获取品相数值
        // 中文
        String conCodeTxt = form.getConditionCode();
        // 对应的数值
        String conCode = CnumberUtils.getQualityNum(conCodeTxt);
        // 对应的字母
        String letterCode = CnumberUtils.getQualityNum(conCode);

        if (conCode == null) {
            throw new IllegalArgumentException("无效的中文品相名称: " + conCode);
        }
        // 获取货号
        String artNo = cnumberUtils.getArtNo(Double.valueOf(new BigDecimal(conCode).divide(new BigDecimal(10)).toString()), userId, form.getBarcode(), depotId, shelvesId, freightId, form.getSeries());
        // 根据isbn 货号 userid 品相 价格 查询是否存在一样的数据
        long count = baseMapper.selectCountByIsbnAndArtNoAndUserIdAndBarcode(form.getBarcode(), artNo, userId.toString(), letterCode, form.getPrice().toString());

        ZhishuShopGoods shopGoods = new ZhishuShopGoods();
        ShopGoodIsbn shopGoodIsbn = new ShopGoodIsbn();

        if (count == 0) {
            // 添加库存表
            shopGoods.setIsbn(form.getBarcode());
            shopGoods.setGoodsName(form.getName());
            shopGoods.setUserId(userId);
            shopGoods.setPrice(form.getPrice());
            shopGoods.setProductId("");
            shopGoods.setConditionCode(letterCode);
            shopGoods.setDepotId(depotId);
            shopGoods.setTenantId("000000");
            shopGoods.setFixPrice(form.getFixPrice());
            shopGoods.setInventory(Long.valueOf(0));
            // 根据仓库获取Id
            shopGoods.setArtNo(artNo);
            //新增分销字段
            shopGoods.setIsJoinDistribution(Integer.parseInt(StringUtils.isNotEmpty(freightVo.getAllowDistribution()) ? freightVo.getAllowDistribution() : "0"));
            baseMapper.insert(shopGoods);
            List<FilesVo> list = form.getFiles();
            for (FilesVo filesVo : list) {
                ZhishuShopImagesBo zhishuShopImagesBo = new ZhishuShopImagesBo();
                zhishuShopImagesBo.setGoodsId(shopGoods.getId());
                zhishuShopImagesBo.setPath(filesVo.getUrl());
                zhishuShopImagesService.insertByBo(zhishuShopImagesBo);
            }
            operatingInventory(1, shopGoods.getId(), Math.toIntExact(form.getInventory()), 4, null, userId);
            shopGoods.setInventory(form.getInventory());
            if (form.getBarcode() != null && form.getBarcode().length() == 13 && !form.getBarcode().startsWith("9")) {
                shopGoods.setTemplateType("2");
            }
            shopGoods.setAuthor(form.getAuthor());
            shopGoods.setPublisher(form.getPublisher());
            shopGoods.setFormat(form.getFormat());
            shopGoods.setPrintTime(form.getPrintTime());
            shopGoods.setWordage(form.getWordage());
            shopGoods.setGoodUnifyIsbn(form.getGoodUnifyIsbn());
            shopGoodIsbn.setGoodIsbn(form.getBarcode());
            shopGoodIsbn.setShopGoodsId(shopGoods.getId());
            shopGoodIsbn.setGoodUnifyIsbn(form.getGoodUnifyIsbn());
            shopGoodIsbnMapper.insert(shopGoodIsbn);
            if (form.getBarcode() == null) {
                // 增加商品审核
                TBookAudit tBookAudit = new TBookAudit();
                tBookAudit.setGoodsName(form.getName());
                tBookAudit.setIsbn(form.getBarcode());
                tBookAudit.setUserId(userId);
                tBookAudit.setProductId("");
                tBookAudit.setArtNo(artNo);
                tBookAudit.setPrice(form.getPrice());
                tBookAudit.setFixPrice(form.getFixPrice());
                tBookAudit.setConditionCode(letterCode);
                tBookAudit.setInventory(Long.valueOf(form.getInventory()));
                tBookAudit.setTenantId("000000");
                tBookAudit.setStatus("2");
                tBookAuditMapper.insert(tBookAudit);
            }
        } else if (count > 0) {
            ZhishuShopGoods existingGoods = baseMapper.selectartNoByIsbnAndConditionCodeAndArtNo(form.getBarcode(), letterCode, artNo, form.getPrice(), userId);
            // 价格相同 修改
            long newInventory = existingGoods.getInventory() + form.getInventory();
            shopGoods.setId(existingGoods.getId());
            List<FilesVo> list = form.getFiles();
            for (FilesVo filesVo : list) {
                ZhishuShopImagesBo zhishuShopImagesBo = new ZhishuShopImagesBo();
                zhishuShopImagesBo.setGoodsId(shopGoods.getId());
                zhishuShopImagesBo.setPath(filesVo.getUrl());
                zhishuShopImagesService.insertByBo(zhishuShopImagesBo);
            }
            operatingInventory(1, shopGoods.getId(), Math.toIntExact(form.getInventory()), 4, null, userId);
            shopGoods.setInventory(newInventory);
            if (form.getBarcode() != null && form.getBarcode().length() == 13 && !form.getBarcode().startsWith("9")) {
                shopGoods.setTemplateType("2");
            }
            shopGoods.setAuthor(form.getAuthor());
            shopGoods.setPublisher(form.getPublisher());
            shopGoods.setFormat(form.getFormat());
            shopGoods.setPrintTime(form.getPrintTime());
            shopGoods.setWordage(form.getWordage());
            tBookAuditMapper.updateInventory(newInventory, userId, letterCode, artNo, form.getPrice(), form.getBarcode());
        }


        /**
         * 执行孔夫子店铺自动发布商品线程
         */
        shopGoods.setCategoryId(form.getCategoryId());
        shopGoods.setDepotId(depotId);
        shopGoods.setPrice(form.getPrice());
        TDepotVo depotVo = depotService.queryById(depotId);
        TLogisticsVo logisticsVo = logisticsService.queryById(depotVo.getTemplateId());
        if (logisticsVo == null) {
            shopGoods.setTemplateMinPrice("0");
        } else {
            shopGoods.setTemplateMinPrice(logisticsVo.getFirPrice() == null ? "0" : logisticsVo.getFirPrice().toString());
        }
        System.out.println("shopGoods:" + shopGoods);
        TShopDepotAotuMapper tShopDepotAotuMapper = applicationContext.getBean(TShopDepotAotuMapper.class);
        KfzAutoAddRunnable kfzAutoAddRunnable = new KfzAutoAddRunnable(userId, shopService, shopDetailService, shopGoodsPublishedService, kongfzService, this, applicationContext, zhishuShopGoodsDetailService, shopGoods,tShopDepotAotuMapper);
        Thread thread = new Thread(kfzAutoAddRunnable, "yxy-submitFromCopyrightPage");
        thread.setDaemon(true); // 设置为守护线程
        thread.start();

        ProductSubmitResultVo result = new ProductSubmitResultVo();
        result.setGoodsId(shopGoods.getId());
        result.setUserId(userId);
        result.setDepotId(depotId);
        result.setShelvesId(shelvesId);
        result.setFreightId(freightId);
        result.setArtNo(artNo);

        return result;
    }

    // 定义可用字符集
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static final int LENGTH = 8;

    public static String generateRandomString() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

    public TableDataInfo<ZhishuShopGoodsVo> selectShopGoodsByPhoneNumber(String phoneNumber, int pageNum, int pageSize, String date) {
        Long userId = sysUserMapper.selectUserIdByNameAndPassWord(phoneNumber);

        // 分页查询
        Page<ZhishuShopGoodsVo> page = new Page<>(pageNum, pageSize);

        // 构建日期查询条件
        if (StringUtils.isNotEmpty(date)) {
            // 将日期字符串转换为日期范围
            LocalDate localDate = LocalDate.parse(date);
            LocalDateTime startOfDay = localDate.atStartOfDay();
            LocalDateTime endOfDay = localDate.plusDays(1).atStartOfDay().minusSeconds(1);

            // 使用日期范围查询
            Page<ZhishuShopGoodsVo> goodsPage = baseMapper.selectShopGoodsByUserPageWithDate(
                    page,
                    userId,
                    Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()),
                    Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant())
            );

            List<ZhishuShopGoodsVo> goodsList = goodsPage.getRecords();
            List<String> goodsIds = goodsList.stream().map(ZhishuShopGoodsVo::getId).collect(Collectors.toList());

            // 合并所有店铺ID
            Map<String, List<Long>> shopIdsMap = getShopIdsByUserId(userId);
            List<Long> allShopIds = new ArrayList<>();
            List<Long> pddShopIds = shopIdsMap.get("1");
            List<Long> kfzShopIds = shopIdsMap.get("2");
            List<Long> xyShopIds  = shopIdsMap.get("5");
            if (pddShopIds != null) allShopIds.addAll(pddShopIds);
            if (kfzShopIds != null) allShopIds.addAll(kfzShopIds);
            if (xyShopIds != null) allShopIds.addAll(xyShopIds);

            // 查询所有商品的发布状态
            if (!goodsIds.isEmpty() && !allShopIds.isEmpty()) {
                List<Map<String, Object>> publishedStatusList = shopGoodsPublishedService.selectPublishedStatus(goodsIds, allShopIds);
                Map<String, Map<String, Object>> statusMap = publishedStatusList.stream()
                        .collect(Collectors.toMap(
                                map -> String.valueOf(map.get("goodsId")),
                                map -> map,
                                (v1, v2) -> v1
                        ));
                goodsList.forEach(goods -> {
                    Map<String, Object> status = statusMap.get(goods.getId());
                    if (status != null) {
                        goods.setPddPublishedStatus((Long) status.get("pddStatus"));
                        goods.setKfzPublishedStatus((Long) status.get("kfzStatus"));
                        goods.setXyPublishedStatus((Long) status.get("xyStatus"));
                    } else {
                        goods.setPddPublishedStatus(0L);
                        goods.setKfzPublishedStatus(0L);
                        goods.setXyPublishedStatus(0L);
                    }
                });
            }

            // 获取商品图片
            if (!goodsIds.isEmpty()) {
                List<Map<String, Object>> imagePathList = zhishuShopImagesMapper.batchQueryFirstPathByGoodsIds(goodsIds);
                Map<String, String> imagePathMap = imagePathList.stream()
                        .collect(Collectors.toMap(
                                map -> String.valueOf(map.get("goodsId")),
                                map -> String.valueOf(map.get("path")),
                                (v1, v2) -> v1
                        ));
                goodsList.forEach(goods -> {
                    String path = imagePathMap.get(goods.getId());
                    if (path != null && !path.isEmpty()) {
                        try {
//                            String bookPic = uploadUtil.getFiles("", "", "", path);
                            goods.setBookPic(path);
                        } catch (Exception e) {
                            log.error("获取商品图片失败: goodsId={}, path={}", goods.getId(), path, e);
                        }
                    }
                });
            }

            // 返回分页对象
            return TableDataInfo.build(goodsPage);
        } else {
            // 如果没有日期参数，使用原来的查询方法
            Page<ZhishuShopGoodsVo> goodsPage = baseMapper.selectShopGoodsByUserPage(page, userId);
            List<ZhishuShopGoodsVo> goodsList = goodsPage.getRecords();
            List<String> goodsIds = goodsList.stream().map(ZhishuShopGoodsVo::getId).collect(Collectors.toList());

            // 合并所有店铺ID
            Map<String, List<Long>> shopIdsMap = getShopIdsByUserId(userId);
            List<Long> allShopIds = new ArrayList<>();
            List<Long> pddShopIds = shopIdsMap.get("1");
            List<Long> kfzShopIds = shopIdsMap.get("2");
            List<Long> xyShopIds  = shopIdsMap.get("5");
            if (pddShopIds != null) allShopIds.addAll(pddShopIds);
            if (kfzShopIds != null) allShopIds.addAll(kfzShopIds);
            if (xyShopIds != null) allShopIds.addAll(xyShopIds);

            // 查询所有商品的发布状态
            if (!goodsIds.isEmpty() && !allShopIds.isEmpty()) {
                List<Map<String, Object>> publishedStatusList = shopGoodsPublishedService.selectPublishedStatus(goodsIds, allShopIds);
                Map<String, Map<String, Object>> statusMap = publishedStatusList.stream()
                        .collect(Collectors.toMap(
                                map -> String.valueOf(map.get("goodsId")),
                                map -> map,
                                (v1, v2) -> v1
                        ));
                goodsList.forEach(goods -> {
                    Map<String, Object> status = statusMap.get(goods.getId());
                    if (status != null) {
                        goods.setPddPublishedStatus((Long) status.get("pddStatus"));
                        goods.setKfzPublishedStatus((Long) status.get("kfzStatus"));
                        goods.setXyPublishedStatus((Long) status.get("xyStatus"));
                    } else {
                        goods.setPddPublishedStatus(0L);
                        goods.setKfzPublishedStatus(0L);
                        goods.setXyPublishedStatus(0L);
                    }
                });
            }

            // 获取商品图片
            if (!goodsIds.isEmpty()) {
                List<Map<String, Object>> imagePathList = zhishuShopImagesMapper.batchQueryFirstPathByGoodsIds(goodsIds);
                Map<String, String> imagePathMap = imagePathList.stream()
                        .collect(Collectors.toMap(
                                map -> String.valueOf(map.get("goodsId")),
                                map -> String.valueOf(map.get("path")),
                                (v1, v2) -> v1
                        ));
                goodsList.forEach(goods -> {
                    String path = imagePathMap.get(goods.getId());
                    if (path != null && !path.isEmpty()) {
                        try {
//                            String bookPic = uploadUtil.getFiles("", "", "", path);
                            goods.setBookPic(path);
                        } catch (Exception e) {
                            log.error("获取商品图片失败: goodsId={}, path={}", goods.getId(), path, e);
                        }
                    }
                });
            }

            // 返回分页对象
            return TableDataInfo.build(goodsPage);
        }
    }


    @Override
    public Map selectDepotIds(String userId, String artNo) {
        ArrayList list = new ArrayList();

        String dcode = artNo.substring(0, 2);
        // 当货号第三位是字母时，截取第三和第四位，若为数字，截取第三位
        String scode = "";
        String fcode = "";
        if (artNo.charAt(2) >= 'A' && artNo.charAt(2) <= 'Z') {
            scode = artNo.substring(2, 4);
            fcode = artNo.substring(4, 5);
        } else {
            scode = artNo.substring(2, 3);
            fcode = artNo.substring(3, 5);
        }

        // 查询一级二级三级获取
        Map map = baseMapper.selectArt(userId, dcode, scode, fcode);

        return map;
    }

    @Override
    public StockChangeLog queryStockChangeLogByOrderSn(String orderSn, Integer type) {
        List<StockChangeLog> list = new LambdaQueryChainWrapper<>(stockChangeLogMapper)
                .eq(StockChangeLog::getAboutId, orderSn)
                .eq(StockChangeLog::getType, type)
                .ne(StockChangeLog::getDelFlag, "1")
                .list();
        if (!list.isEmpty())
            return list.get(0);
        return null;
    }

    @Override
    public Boolean operatingGoodsSoldOut(Long shopId, Integer platformType, Integer logType, Integer operationType, ShopGoodsPublishedVo shopGoodsPublishedVo, String orderSn) {
        // 根据商品Id查询出拥有同商品的店铺Id和平台商品Id
        List<ShopGoodsPublishedVo> shopGoodsPublishedVoList = shopGoodsPublishedService.queryByShopGoodsId(shopGoodsPublishedVo.getShopGoodsId());

        // 过滤掉自己的
        shopGoodsPublishedVoList = shopGoodsPublishedVoList.stream().filter(o -> !o.getShopId().equals(shopId.toString())).toList();

        // 循环根据店铺Id查询出店铺信息
        for (ShopGoodsPublishedVo goodsPublishedVo : shopGoodsPublishedVoList) {
            // 根据店铺Id查询出店铺信息
            ShopVo shop = shopService.queryById(Long.valueOf(goodsPublishedVo.getShopId()));
            if (shop == null){
                shopGoodsPublishedService.deleteWithValidByIds(List.of(goodsPublishedVo.getId()), true);
                continue;
            }
            // 根据店铺类型分别推送平台同步库存
            InventorySynchronizedStrategy strategy = InventorySynchronizedStrategyFactory.getStrategy(shop.getShopType());
            strategy.operatingGoodsSoldOut(shop, goodsPublishedVo, platformType, logType, operationType, orderSn);
        }
        return true;
    }

    /**
     * 获取货区对应商品数据
     *
     * @param code
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public TableDataInfo<ZhishuShopGoodsVo> queryGoodListByArtNo(String code, Long userId, int pageNum, int pageSize, String date) {
        // 分页查询
        Page<ZhishuShopGoodsVo> page = new Page<>(pageNum, pageSize);

        // 构建日期查询条件
        if (StringUtils.isNotEmpty(date)) {
            // 将日期字符串转换为日期范围
            LocalDate localDate = LocalDate.parse(date);
            LocalDateTime startOfDay = localDate.atStartOfDay();
            LocalDateTime endOfDay = localDate.plusDays(1).atStartOfDay().minusSeconds(1);

            // 使用日期范围查询
            Page<ZhishuShopGoodsVo> goodsPage = baseMapper.selectShopGoodsByUserPageWithDateArtNo(
                    page,
                    userId,
                    Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()),
                    Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant()),
                    code
            );

            List<ZhishuShopGoodsVo> goodsList = goodsPage.getRecords();
            List<String> goodsIds = goodsList.stream().map(ZhishuShopGoodsVo::getId).collect(Collectors.toList());

            // 合并所有店铺ID
            Map<String, List<Long>> shopIdsMap = getShopIdsByUserId(userId);
            List<Long> allShopIds = new ArrayList<>();
            List<Long> pddShopIds = shopIdsMap.get("1");
            List<Long> kfzShopIds = shopIdsMap.get("2");
            if (pddShopIds != null) allShopIds.addAll(pddShopIds);
            if (kfzShopIds != null) allShopIds.addAll(kfzShopIds);

            // 查询所有商品的发布状态
            if (!goodsIds.isEmpty() && !allShopIds.isEmpty()) {
                List<Map<String, Object>> publishedStatusList = shopGoodsPublishedService.selectPublishedStatus(goodsIds, allShopIds);
                Map<String, Map<String, Object>> statusMap = publishedStatusList.stream()
                        .collect(Collectors.toMap(
                                map -> String.valueOf(map.get("goodsId")),
                                map -> map,
                                (v1, v2) -> v1
                        ));
                goodsList.forEach(goods -> {
                    Map<String, Object> status = statusMap.get(goods.getId());
                    if (status != null) {
                        goods.setPddPublishedStatus((Long) status.get("pddStatus"));
                        goods.setKfzPublishedStatus((Long) status.get("kfzStatus"));
                    } else {
                        goods.setPddPublishedStatus(0L);
                        goods.setKfzPublishedStatus(0L);
                    }
                });
            }

            // 获取商品图片
            if (!goodsIds.isEmpty()) {
                List<Map<String, Object>> imagePathList = zhishuShopImagesMapper.batchQueryFirstPathByGoodsIds(goodsIds);
                Map<String, String> imagePathMap = imagePathList.stream()
                        .collect(Collectors.toMap(
                                map -> String.valueOf(map.get("goodsId")),
                                map -> String.valueOf(map.get("path")),
                                (v1, v2) -> v1
                        ));
                goodsList.forEach(goods -> {
                    String path = imagePathMap.get(goods.getId());
                    if (path != null && !path.isEmpty()) {
                        try {
//                            String bookPic = uploadUtil.getFiles(null, goods.getGoodsName(), path);
                            goods.setBookPic(path);
                        } catch (Exception e) {
                            log.error("获取商品图片失败: goodsId={}, path={}", goods.getId(), path, e);
                        }
                    }
                });
            }

            // 返回分页对象
            return TableDataInfo.build(goodsPage);
        } else {
            // 如果没有日期参数，使用原来的查询方法
            Page<ZhishuShopGoodsVo> goodsPage = baseMapper.selectShopGoodsByUserPageArtNo(page, userId, code);
            List<ZhishuShopGoodsVo> goodsList = goodsPage.getRecords();
            List<String> goodsIds = goodsList.stream().map(ZhishuShopGoodsVo::getId).collect(Collectors.toList());

            // 合并所有店铺ID
            Map<String, List<Long>> shopIdsMap = getShopIdsByUserId(userId);
            List<Long> allShopIds = new ArrayList<>();
            List<Long> pddShopIds = shopIdsMap.get("1");
            List<Long> kfzShopIds = shopIdsMap.get("2");
            if (pddShopIds != null) allShopIds.addAll(pddShopIds);
            if (kfzShopIds != null) allShopIds.addAll(kfzShopIds);

            // 查询所有商品的发布状态
            if (!goodsIds.isEmpty() && !allShopIds.isEmpty()) {
                List<Map<String, Object>> publishedStatusList = shopGoodsPublishedService.selectPublishedStatus(goodsIds, allShopIds);
                Map<String, Map<String, Object>> statusMap = publishedStatusList.stream()
                        .collect(Collectors.toMap(
                                map -> String.valueOf(map.get("goodsId")),
                                map -> map,
                                (v1, v2) -> v1
                        ));
                goodsList.forEach(goods -> {
                    Map<String, Object> status = statusMap.get(goods.getId());
                    if (status != null) {
                        goods.setPddPublishedStatus((Long) status.get("pddStatus"));
                        goods.setKfzPublishedStatus((Long) status.get("kfzStatus"));
                    } else {
                        goods.setPddPublishedStatus(0L);
                        goods.setKfzPublishedStatus(0L);
                    }
                });
            }

            // 获取商品图片
            if (!goodsIds.isEmpty()) {
                List<Map<String, Object>> imagePathList = zhishuShopImagesMapper.batchQueryFirstPathByGoodsIds(goodsIds);
                Map<String, String> imagePathMap = imagePathList.stream()
                        .collect(Collectors.toMap(
                                map -> String.valueOf(map.get("goodsId")),
                                map -> String.valueOf(map.get("path")),
                                (v1, v2) -> v1
                        ));
                goodsList.forEach(goods -> {
                    String path = imagePathMap.get(goods.getId());
                    if (path != null && !path.isEmpty()) {
                        try {
//                            String bookPic = uploadUtil.getFiles(null, goods.getGoodsName(), path);
                            goods.setBookPic(path);
                        } catch (Exception e) {
                            log.error("获取商品图片失败: goodsId={}, path={}", goods.getId(), path, e);
                        }
                    }
                });
            }

            // 返回分页对象
            return TableDataInfo.build(goodsPage);
        }
    }

    /**
     * 根据用户ID查询商品数量
     *
     * @param userId 用户ID
     * @return 商品数量
     */
    @Override
    public Long queryGoodsCountByUserId(Long userId) {
        LambdaQueryWrapper<ZhishuShopGoods> lqw = Wrappers.lambdaQuery(ZhishuShopGoods.class);
        lqw.eq(ZhishuShopGoods::getUserId, userId);
        return baseMapper.selectCount(lqw);
    }

    @Override
    public SysUser queryUserByUserId(Long userId) {
        return sysUserMapper.selectUserById(userId);
    }

    /**
     * 批量移动商品位置
     *
     * @param itemIds         商品ID列表
     * @param userId          用户ID
     *
     * @return 操作结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchMoveItems(List<String> itemIds, String warehouse, String shelf, String freight, Long userId) {
        if (itemIds == null || itemIds.isEmpty()) {
            return "请选择要移动的商品";
        }


//        // 检查仓库、货架、货位是否存在
        TDepotVo depot = baseMapper.selectDepotName(userId, warehouse);
        if (depot == null) {
            return "仓库编码不存在";
        }

        Long sheId = baseMapper.selectSheId(depot.getId(), shelf);
        if (sheId == null) {
            return "货架编码不存在";
        }

        Long freId = baseMapper.selectFreId(sheId, freight);
        if (freId == null) {
            return "货位编码不存在";
        }
        // 拼接新的货号
        String newLocationCode = warehouse + shelf + freight;
        // 校验是否为五位
        if (newLocationCode.length() != 5) {
            return "货位编码长度必须为5位";
        }

        int successCount = 0;
        StringBuilder failItems = new StringBuilder();

        for (String id : itemIds) {
            try {
                // 查询商品信息
                ZhishuShopGoodsVo goodsVo = baseMapper.selectByIdVo(id);
                if (goodsVo == null) {
                    failItems.append(id).append("(商品不存在),");
                    continue;
                }

                // 获取原货号，保留后面的部分
                String artNo = goodsVo.getArtNo();
                String newArtNo = "";

                // 处理新的货号
                if (artNo.length() > 5) {
                    // 替换前5位，保留后面的部分
                    newArtNo = newLocationCode + artNo.substring(5);
                } else if(artNo.isEmpty()){
                    return "原货号错误";
                }

                // 更新商品货号
                ZhishuShopGoodsBo updateBo = new ZhishuShopGoodsBo();
                updateBo.setId(id);
                updateBo.setArtNo(newArtNo);
                updateBo.setUserId(userId);
                updateBo.setDepotId(depot.getId());
                boolean updateByBo =baseMapper.updateByArtNo(updateBo);
                if (updateByBo) {
                    successCount++;
                } else {
                    failItems.append(id).append("(更新失败),");
                }
                // 同时插入货号移动表
                ArtNoMove artNoMove = new ArtNoMove();
                ZhishuShopGoods zhishuShopGoods = baseMapper.selectById(id);
                artNoMove.setOldArtNo(artNo);
                artNoMove.setNewArtNo(newArtNo);
                artNoMove.setUserId(userId);
                artNoMove.setOldDepotId(zhishuShopGoods.getDepotId());
                artNoMove.setNewDepotId(depot.getId());
                artNoMove.setCreateBy(userId);
                artNoMove.setUpdateBy(userId);
                // 插入时间戳
                artNoMove.setCreateTime(System.currentTimeMillis());
                artNoMove.setUpdateTime(System.currentTimeMillis());
                artNoMove.setIsDel(0L);
                artNoMoveMapper.insert(artNoMove);
            } catch (Exception e) {
                log.error("批量移动商品位置异常，商品ID：{}", id, e);
                failItems.append(id).append("(").append(e.getMessage()).append("),");
            }
        }

        if (successCount == itemIds.size()) {
            return "成功移动" + successCount + "件商品";
        } else {
            return "成功移动" + successCount + "件商品，失败" + (itemIds.size() - successCount) + "件：" + failItems;
        }
    }

    @Override
    public int updateByArtNoPrefix(String isJoinDistribution,String artNoPrefix,Long userId, Long limitNum){
        return baseMapper.updateByArtNoPrefix(isJoinDistribution,artNoPrefix,userId,limitNum);
    }

    @Override
    public int batchUpdateCargo(BatchUpdateCargoBo bo) {
        //分别获取bo.getAres中的三个货区Id
        Long deId = bo.getAreas().get(0);
        Long shId = bo.getAreas().get(1);
        Long frId = bo.getAreas().get(2);
        String beartNo = baseMapper.getSelectArtNo(deId, shId, frId, bo.getUserId());
        Integer flag = baseMapper.batchUpdateartNo(deId, beartNo, bo.getIds());
        return flag;
    }

    @Override
    public void createShopGoodsList(BatchGoodsRequest request) {
        System.out.println("zhuxiaodong=================== createShopGoodsList");
        Long shopId = request.getShopId();
        ShopVo shopVo = shopService.queryById(shopId);
        System.out.println("zhuxiaodong=================== createShopGoodsList"+request.getBatchData());
        new Thread(() -> {

            createShopGoodsList(shopVo, request);
        }).start();
        System.out.println("zhuxiaodong=================== Thread"+Thread.currentThread().getId());

    }

    @Override
    public void deleteTaskDataByShopId(Long shopId) {
        int checkMark = runningTaskByShopService.checkTableExists("t_running_task_" + shopId);
        if (checkMark == 1) {
            runningTaskByShopService.deleteAll("t_running_task_" + shopId);
        }
    }

    private void createShopGoodsList(ShopVo shopVo, BatchGoodsRequest request) {
        log.info("任务开始:" + DateUtils.dateTimeNow(FormatsType.YYYY_MM_DD_HH_MM_SS)+request.getBatchData());
        System.out.println("zhuxiaodong===================");
        System.out.println("任务开始:" + DateUtils.dateTimeNow(FormatsType.YYYY_MM_DD_HH_MM_SS)+request.getBatchData());
        System.out.println("zhuxiaodong===================");
        // 根据shopId查询数据表是否存在
        int checkMark = runningTaskByShopService.checkTableExists("t_running_task_" + shopVo.getId());
        if (checkMark == 0) {
            // 不存在则创建表
            runningTaskByShopService.createTable("t_running_task_" + shopVo.getId());
        }
        List<ZhishuShopGoodsRequest> dataList = request.getBatchData();

        if (dataList.isEmpty()) {
            return;
        }

        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

        transactionTemplate.execute(status -> {
            try {
                // 批量检查存在性（在事务内）
                Map<String, Boolean> existsMap = runningTaskByShopService
                        .batchCheckGoodsIdExists("t_running_task_" + shopVo.getId(),
                                dataList.stream()
                                        .map(ZhishuShopGoodsRequest::getItemNumber)
                                        .collect(Collectors.toList()));

                // 过滤并构建数据
                List<RunningTask> runningTaskList = dataList.stream()
                        .filter(item -> !existsMap.getOrDefault(item.getItemNumber(), false))
                        .map(item -> buildRunningTask(shopVo, request, item))
                        .collect(Collectors.toList());

                log.info("过滤后需要插入的数据量: {}，跳过重复数据: {}",
                        runningTaskList.size(), dataList.size() - runningTaskList.size());

                // 批量插入
                if (!runningTaskList.isEmpty()) {
                    runningTaskByShopService.batchInsert("t_running_task_" + shopVo.getId(), runningTaskList);
                    runningTaskByShopService.updateStatus("t_running_task_" + shopVo.getId());
                }

                return null;
            } catch (Exception e) {
                status.setRollbackOnly();
                log.error("批量插入商品数据失败: {}", e.getMessage(), e);
                throw e;
            }
        });

        if (request.getIsLastBatch()) {
            RedisUtils.setCacheObject("lastGoodsSynTime_" + shopVo.getId(),
                    DateUtilsUtils.getNowDate());
        }


        // 添加数据
        // if (dataList.size() > 0) {
           // List<RunningTask> runningTaskList = new ArrayList<>();
            // for (ZhishuShopGoodsRequest map : dataList) {
            //
            //
            //
            //     // 构建 JSON 对象
            //     JSONObject json = new JSONObject();
            //     // 平台的商品id
            //     json.put("trilateralId", map.getItemNumber());
            //     json.put("author", map.getAuthor());
            //     json.put("publisher", map.getPublisher());
            //     json.put("publisherTime", map.getPublisherTime());
            //     json.put("format", map.getFormat());
            //     json.put("wordage", map.getWordage());
            //     json.put("unifiedIsbn", map.getUnifiedIsbn());
            //     json.put("img", map.getBookPic());
            //     // 当前时间
            //     json.put("finishTime", DateUtilsUtils.getNowDate());
            //     json.put("imageSelect", "2");
            //     // 商品价格单位分
            //     json.put("totalPrice", map.getPrice());
            //     // 书号
            //     json.put("isbn", map.getIsbn());
            //     // 权重不用管
            //     json.put("priority", "3");
            //     // 不用填,上传的实拍图
            //     json.put("imageBigUrl", "");
            //     // 商品标题
            //     json.put("title", map.getGoodsName());
            //     json.put("quality", map.getConditionCode());
            //     json.put("shopType", shopVo.getShopType());
            //     json.put("artNo", map.getArtNo());
            //     // 库存
            //     json.put("stock", map.getInventory());
            //     json.put("isOnSale", "1");
            //     json.put("skuCode", "");
            //     json.put("skuId", "");
            //     // json.put("isOnSale", map.get("is_onsale").toString());
            //     // json.put("isMoreSku", map.get("is_more_sku").toString());
            //     String jsonString = json.toString();
            //
            //     RunningTask runningTask = new RunningTask();
            //     runningTask.setTaskId(request.getTaskId());
            //     runningTask.setShopId(shopVo.getId());
            //     runningTask.setGoodsId(Long.valueOf(map.getItemNumber()));
            //     runningTask.setRandomNum(System.currentTimeMillis());
            //     runningTask.setTaskName("拉取孔网商品任务");
            //     runningTask.setPriority(255L);
            //     runningTask.setData("");
            //     runningTask.setStatus("2");
            //     runningTask.setTaskType("GET_KW_SHOP_GOODS");
            //     runningTask.setSuccessData(jsonString);
            //     runningTask.setCallBackData("拉取成功");
            //     runningTaskList.add(runningTask);
            // }
            // if (ObjectUtil.isNotEmpty(runningTaskList)) {
            //     runningTaskByShopService.batchInsert("t_running_task_" + shopVo.getId(), runningTaskList);
            //     runningTaskByShopService.updateStatus("t_running_task_" + shopVo.getId());
            // }
            // if (request.getIsLastBatch()) {
            //     RedisUtils.setCacheObject("lastGoodsSynTime_" + shopVo.getId(), DateUtilsUtils.getNowDate());
            // }
        // }
    }


    private RunningTask buildRunningTask(ShopVo shopVo, BatchGoodsRequest request,
                                         ZhishuShopGoodsRequest map) {
        JSONObject json = buildGoodsJson(shopVo, map);

        RunningTask runningTask = new RunningTask();
        runningTask.setTaskId(request.getTaskId());
        runningTask.setShopId(shopVo.getId());
        runningTask.setGoodsId(Long.valueOf(map.getItemNumber()));
        runningTask.setRandomNum(System.currentTimeMillis());
        runningTask.setTaskName("拉取孔网商品任务");
        runningTask.setPriority(255L);
        runningTask.setData("");
        runningTask.setStatus("2");
        runningTask.setTaskType("GET_KW_SHOP_GOODS");
        runningTask.setSuccessData(json.toString());
        runningTask.setCallBackData("拉取成功");

        return runningTask;
    }

    private JSONObject buildGoodsJson(ShopVo shopVo, ZhishuShopGoodsRequest map) {
        JSONObject json = new JSONObject();
        json.put("trilateralId", map.getItemNumber());
        json.put("author", map.getAuthor());
        json.put("publisher", map.getPublisher());
        json.put("publisherTime", map.getPublisherTime());
        json.put("format", map.getFormat());
        json.put("wordage", map.getWordage());
        json.put("unifiedIsbn", map.getUnifiedIsbn());
        json.put("img", map.getBookPic());
        json.put("finishTime", DateUtilsUtils.getNowDate());
        json.put("imageSelect", "11");
        json.put("totalPrice", map.getPrice());
        json.put("isbn", map.getIsbn());
        json.put("priority", "3");
        json.put("imageBigUrl", "");
        json.put("title", map.getGoodsName());
        json.put("quality", map.getConditionCode());
        json.put("shopType", shopVo.getShopType());
        json.put("artNo", map.getArtNo());
        json.put("stock", map.getInventory());
        json.put("isOnSale", "1");
        json.put("skuCode", "");
        json.put("skuId", "");
        return json;
    }



    @Override
    public void syncRunningTaskToShopGoods(Long shopId, Long freightId,Long userId,TaskBo taskBo) {
        /**
         * 查询货号
         */
        Map freightMap = TFreightMapper.selectByFreightId(freightId);
        Long pageSize = 100L;
        Long page = 1L;

        RunningTaskShopGoodsDto runningTaskShopGoodsDto = new RunningTaskShopGoodsDto();
        runningTaskShopGoodsDto.setTableName("t_running_task_"+shopId);
        runningTaskShopGoodsDto.setTaskId(taskBo.getRelationId());
        runningTaskShopGoodsDto.setPageSize(pageSize);
        while(true){
            /**
             * 循环开始查询店铺商品数据进行同步自营书品操作
             */
            Long pageNum = (long) ((page - 1) * pageSize);
            runningTaskShopGoodsDto.setPageNum(pageNum);
            List<Map> shopGoodsMapList = runningTaskByShopService.selectGetShopGoodsListByDto(runningTaskShopGoodsDto);
            if(shopGoodsMapList.isEmpty()){
                break;
            }
            for (Map shopGoodsMap : shopGoodsMapList){
                Map successData =  JsonUtil.transferToObj(shopGoodsMap.get("success_data").toString(),Map.class);
                String artNo = successData.get("artNo") == null ? "" : successData.get("artNo").toString();
                String trilateralId = successData.get("trilateralId") == null ? "" : successData.get("trilateralId").toString();
                String isbn = successData.get("isbn") == null ? "" : successData.get("isbn").toString();
                if(StringUtils.isEmpty(isbn)){
                    isbn = generate13DigitId();
                }
                /**
                 * 定义任务日志对象
                 */
                String callBackData = "";

                RunningTask runningTask = new RunningTask();
                runningTask.setTaskId(taskBo.getId());
                runningTask.setShopId(Long.valueOf(shopId));
                runningTask.setGoodsId(0L);
                runningTask.setRandomNum(System.currentTimeMillis());
                runningTask.setTaskName("同步至自营书品任务");
                runningTask.setPriority(255L);
                runningTask.setTaskType("SYNCHRONIZE_TO_ERP");
                runningTask.setStatus("3");

                try{
                    //校验货号是否符合规则
//                    Boolean artNoIsOk = ArtNoUtil.validateArtNo(artNo);
                    ZhishuShopGoodsVo zhishuShopGoodsVo = baseMapper.selectShopGoodsByProductId(trilateralId,userId);

                    if(zhishuShopGoodsVo == null){
                        //若根据货号未查询到则根据店铺id和平台id查询商品
                        zhishuShopGoodsVo = baseMapper.selectShopGoodsByShopIdAndPlatformId(shopId.toString(),trilateralId);
                    }
                    if(zhishuShopGoodsVo != null){
                        /**
                         * 当前商品在自营书品中存在 则执行修改操作
                         */
                        ZhishuShopGoods zhishuShopGoods = new ZhishuShopGoods();
                        zhishuShopGoods.setId(zhishuShopGoodsVo.getId());
                        //获取库存
                        if(successData.get("stock") != null){
                            Long stock = Long.parseLong(successData.get("stock").toString());
                            //比较新旧库存是否一致
                            if(Long.parseLong(zhishuShopGoodsVo.getInventory()) != stock){
                                //库存不一致，则进行修改操作
                                zhishuShopGoods.setInventory(stock);
                                //记录旧库存
                                successData.put("oldStock", zhishuShopGoodsVo.getInventory());
                            }
                        }
                        if (successData.get("totalPrice") != null){
                            Long price = Long.parseLong(successData.get("totalPrice").toString());
                            //比较新旧价格是否一致
                            Long oldPrice = zhishuShopGoodsVo.getPrice().longValue();
                            if (!oldPrice.equals(price)) {
                                //价格不一致，则进行修改操作
                                zhishuShopGoods.setPrice(price);
                                //记录旧价格
                                successData.put("oldPrice", oldPrice);
                            }
                        }
                        //进行修改库存
                        if(zhishuShopGoods.getInventory() != null || zhishuShopGoods.getPrice() != null){
                            int updateMark = baseMapper.updateById(zhishuShopGoods);
                            if(zhishuShopGoods.getInventory() != null && updateMark >= 1){
                                StockChangeLog stockChangeLog = new StockChangeLog();
                                stockChangeLog.setShopGoodsId(Long.parseLong(zhishuShopGoodsVo.getId()));
                                stockChangeLog.setType(5);
                                stockChangeLog.setBeforeInv(Long.parseLong(zhishuShopGoodsVo.getInventory()));    //初始库存
                                stockChangeLog.setAfterInv(Long.parseLong(successData.get("stock").toString()));
                                stockChangeLog.setCreateBy(zhishuShopGoodsVo.getUserId());
                                stockChangeLog.setUpdateBy(zhishuShopGoodsVo.getUserId());
                                stockChangeLog.setCreateTime(DateUtils.getNowDate());
                                stockChangeLog.setUpdateTime(DateUtils.getNowDate());
                                stockChangeLog.setDelFlag("0");
                                stockChangeLogMapper.insert(stockChangeLog);

                                //记录日志
                                callBackData += "修改库存成功;";
                            }
                            if(zhishuShopGoods.getPrice() != null && updateMark > 1){
                                callBackData += "修改价格成功;";
                            }

                            if(updateMark == 0){
                                callBackData += "修改自营商品失败;";
                            }
                        }
                        //查看是否存在已发布商品记录
                        ShopGoodsPublishedVo shopGoodsPublishedVo = shopGoodsPublishedService.queryByPlatformId(shopId.toString(),trilateralId);
                        if (shopGoodsPublishedVo == null || !shopGoodsPublishedVo.getPlatformId().equals(trilateralId)){
                            //不存在,或者三方平台对不上的情况则新增已发布商品记录
                            ShopGoodsPublishedBo shopGoodsPublishedBo = new ShopGoodsPublishedBo();
                            shopGoodsPublishedBo.setShopId(shopId+"");
                            shopGoodsPublishedBo.setShopGoodsId(zhishuShopGoodsVo.getId());
                            shopGoodsPublishedBo.setPlatformId(trilateralId);
                            shopGoodsPublishedBo.setCreateBy(zhishuShopGoodsVo.getUserId());
                            shopGoodsPublishedBo.setCreateTime(DateUtils.getNowDate());
                            shopGoodsPublishedService.insertByBo(shopGoodsPublishedBo);
                            //记录日志
                            callBackData += "新增已发布记录成功;";
                        }
                    }else{
                        //不存在，则执行新增操作
                        //新增标记为空，代表需要进行新增操作
                        ZhishuShopGoods zhishuShopGoods = new ZhishuShopGoods();
                        zhishuShopGoods.setUserId(userId);
                        zhishuShopGoods.setProductId(trilateralId);
                        zhishuShopGoods.setIsJoinDistribution(freightMap.get("allow_distribution") == null ? 0 : Integer.parseInt(freightMap.get("allow_distribution").toString()));
                        zhishuShopGoods.setDepotId(Long.parseLong(freightMap.get("did").toString()));
                        zhishuShopGoods.setGoodsName((String) successData.get("title"));
                        zhishuShopGoods.setIsbn(isbn);
                        zhishuShopGoods.setPrice(Long.parseLong(successData.get("totalPrice").toString()));
                        // successData.get("quality")

                        Double quality = new BigDecimal(successData.get("quality").toString()).divide(new BigDecimal(10)).setScale(1, RoundingMode.HALF_UP).stripTrailingZeros().doubleValue();
                        zhishuShopGoods.setConditionCode(successData.get("quality") == null ? "K" : CODE_MAP.get(quality));
                        zhishuShopGoods.setInventory(Long.parseLong(successData.get("stock").toString()));
                        zhishuShopGoods.setBookPic((String) successData.get("img"));
                        zhishuShopGoods.setOriginalArtNo((String) successData.get("artNo"));
                        zhishuShopGoods.setIsArtNoConversion(1);
                        zhishuShopGoods.setCreateBy(userId);
                        zhishuShopGoods.setUpdateBy(userId);
                        zhishuShopGoods.setCreateTime(DateUtils.getNowDate());
                        zhishuShopGoods.setUpdateTime(DateUtils.getNowDate());
                        Double s = 85.0;
                        try{
                            s = convertChineseToCode(successData.get("quality").toString());
                        }catch (Exception e){
                            s = Double.parseDouble(successData.get("quality").toString());
                            System.out.println("获取品相异常："+e.getMessage()+";更改赋值："+s);
                        }
                        s = s / 10;
                        artNo = cnumberUtils.getArtNo(s, userId, successData.get("isbn").toString(), Long.parseLong(freightMap.get("did").toString()), Long.parseLong(freightMap.get("sid").toString()), Long.parseLong(freightMap.get("fid").toString()), null);
                        zhishuShopGoods.setArtNo(artNo);
                        boolean flag = baseMapper.insert(zhishuShopGoods) > 0;
                        if(flag){
                            //记录日志
                            callBackData += "同步成功;";
                            /**
                             * 新增成功后，增加 库存操作记录、已发布商品记录、商品实拍图。
                             * 若是无效isbn则需要增加书籍信息
                             */
                            //新增库存操作记录
                            StockChangeLog stockChangeLog = new StockChangeLog();
                            stockChangeLog.setShopGoodsId(Long.parseLong(zhishuShopGoods.getId()));
                            stockChangeLog.setType(5);
                            stockChangeLog.setBeforeInv(0L);    //初始库存
                            stockChangeLog.setAfterInv(Long.parseLong(successData.get("stock").toString()));
                            stockChangeLog.setCreateBy(zhishuShopGoods.getUserId());
                            stockChangeLog.setUpdateBy(zhishuShopGoods.getUserId());
                            stockChangeLog.setCreateTime(DateUtils.getNowDate());
                            stockChangeLog.setUpdateTime(DateUtils.getNowDate());
                            stockChangeLog.setDelFlag("0");
                            stockChangeLogMapper.insert(stockChangeLog);
                            //已发布商品记录
                            ShopGoodsPublishedBo shopGoodsPublishedBo = new ShopGoodsPublishedBo();
                            shopGoodsPublishedBo.setShopId(shopId+"");
                            shopGoodsPublishedBo.setShopGoodsId(zhishuShopGoods.getId());
                            shopGoodsPublishedBo.setPlatformId(trilateralId);
                            shopGoodsPublishedBo.setCreateBy(zhishuShopGoods.getUserId());
                            shopGoodsPublishedBo.setUpdateBy(zhishuShopGoods.getUserId());
                            shopGoodsPublishedBo.setCreateTime(DateUtils.getNowDate());
                            shopGoodsPublishedBo.setUpdateTime(DateUtils.getNowDate());
                            shopGoodsPublishedService.insertByBo(shopGoodsPublishedBo);
                            //商品实拍图
                            if (successData.get("img") != null){
                                ZhishuShopImagesBo zhishuShopImagesBo = new ZhishuShopImagesBo();
                                zhishuShopImagesBo.setGoodsId(zhishuShopGoods.getId());
                                zhishuShopImagesBo.setPath((String) successData.get("img"));
                                zhishuShopImagesService.insertByBo(zhishuShopImagesBo);
                            }
                            //书籍信息 判断isbn首个字符是不是6
                            if(isbn.substring(0,1).equals("6")){
                                ZhishuShopGoodsDetailBo zhishuShopGoodsDetailBo = new ZhishuShopGoodsDetailBo();
                                zhishuShopGoodsDetailBo.setPid(Long.parseLong(zhishuShopGoods.getId()));
                                zhishuShopGoodsDetailBo.setAuthor(successData.get("author") == null ? "" : successData.get("author").toString());
                                zhishuShopGoodsDetailBo.setPublisher(successData.get("publisher") == null ? "" : successData.get("publisher").toString());
                                zhishuShopGoodsDetailBo.setPublishertime(successData.get("publisherTime") == null ? "" : successData.get("publisherTime").toString());
                                zhishuShopGoodsDetailBo.setFormat(successData.get("format") == null ? "" : successData.get("format").toString());
                                zhishuShopGoodsDetailBo.setWordage(successData.get("wordage") == null ? "" : successData.get("wordage").toString());
                                zhishuShopGoodsDetailService.insertByBo(zhishuShopGoodsDetailBo);
                            }
                        }
                    }
                    if(StringUtils.isEmpty(callBackData)){
                        callBackData = "商品已存在并且库存价格一致，不做处理";
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    callBackData += "同步失败;";
                }
                //记录数据日志
                runningTask.setSuccessData(JsonUtil.transferToJson(successData));
                runningTask.setCallBackData(callBackData);
                runningTaskService.insert(runningTask);
            }
            //进行下100条数据
            page++;
        }
    }

    @Override
    public void synchronousTask(ShopVo shopVo, TaskBo taskBo){

        shopGoodsPublishedService.deleteByShopId(shopVo.getId());
        Long pageSize = 100L;
        Long page = 1L;
        RunningTaskShopGoodsDto runningTaskShopGoodsDto = new RunningTaskShopGoodsDto();
        runningTaskShopGoodsDto.setTableName("t_running_task_"+shopVo.getId());
        runningTaskShopGoodsDto.setTaskId(taskBo.getRelationId());
        runningTaskShopGoodsDto.setPageSize(pageSize);
        while(true){
            Long pageNum = (long) ((page - 1) * pageSize);
            runningTaskShopGoodsDto.setPageNum(pageNum);
            List<Map> shopGoodsMapList = runningTaskByShopService.selectGetShopGoodsListByDto(runningTaskShopGoodsDto);
            if(shopGoodsMapList.isEmpty()){
                break;
            }


            for (Map shopGoodsMap : shopGoodsMapList){


                Map successData =  JsonUtil.transferToObj(shopGoodsMap.get("success_data").toString(),Map.class);

                RunningTask runningTask = new RunningTask();
                runningTask.setTaskId(taskBo.getId());
                runningTask.setShopId(shopVo.getId());
                runningTask.setGoodsId(0L);
                runningTask.setRandomNum(System.currentTimeMillis());
                runningTask.setTaskName("同步至自营书品任务");
                runningTask.setPriority(255L);
                runningTask.setTaskType("SYNCHRONOUS_TASK");
                runningTask.setStatus("3");
                runningTask.setSuccessData(JsonUtil.transferToJson(successData));

                String artNo = successData.get("skuCode") == null ? "" : successData.get("skuCode").toString();
                if (StringUtils.isEmpty(artNo)){
                    runningTask.setCallBackData("规格编码为空");
                }else{
                    String trilateralId = successData.get("trilateralId") == null ? "" : successData.get("trilateralId").toString();
                    ZhishuShopGoodsVo zhishuShopGoodsVo = baseMapper.selectShopGoodsByArtNoAndUserId(artNo,shopVo.getCreateBy());

                    if (zhishuShopGoodsVo != null){
                        // 存在数据，查询是否存在已发布商品
                        //查看是否存在已发布商品记录
                        ShopGoodsPublishedVo shopGoodsPublishedVo = shopGoodsPublishedService.queryByPlatformId(shopVo.getId().toString(),trilateralId);
                        if (shopGoodsPublishedVo == null || !shopGoodsPublishedVo.getPlatformId().equals(trilateralId)){
                            //不存在,或者三方平台对不上的情况则新增已发布商品记录
                            ShopGoodsPublishedBo shopGoodsPublishedBo = new ShopGoodsPublishedBo();
                            shopGoodsPublishedBo.setShopId(shopVo.getId().toString());
                            shopGoodsPublishedBo.setShopGoodsId(zhishuShopGoodsVo.getId());
                            shopGoodsPublishedBo.setPlatformId(trilateralId);
                            shopGoodsPublishedBo.setCreateBy(zhishuShopGoodsVo.getUserId());
                            shopGoodsPublishedBo.setCreateTime(DateUtils.getNowDate());
                            shopGoodsPublishedService.insertByBo(shopGoodsPublishedBo);
                            //记录日志
                            runningTask.setCallBackData("商品对应成功");
                        }else{
                            runningTask.setCallBackData("已存在商品");
                        }
                    }else{
                        runningTask.setCallBackData("未对应到自营商品");
                    }
                }
                runningTaskService.insert(runningTask);
            }
            page++;
        }
    }

    /**
     * 生成13位ID：6 + 秒级时间戳 + 随机数
     * 格式：6 + 秒级时间戳(10位) + 随机数(2位) = 13位
     */
    public static String generate13DigitId() {
        // 获取秒级时间戳（10位）
        long timestamp = Instant.now().getEpochSecond();

        // 生成2位随机数（00-99）
        int randomNum = ThreadLocalRandom.current().nextInt(0, 100);

        // 格式化为2位数字，不足补0
        String randomPart = String.format("%02d", randomNum);

        // 拼接：6 + 时间戳 + 随机数
        return "6" + timestamp + randomPart;
    }

    public Map uploadImg1(MultipartFile file ,String accessToken) {

        org.springframework.core.io.Resource fileResource = null;
        try {
            fileResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Map pddMap = new HashMap();
        pddMap.put("token", accessToken);
        pddMap.put("file", fileResource);

        Map map = InterfaceUtils.postFormObject(getUploadImgUrl(), "/upload", pddMap);
        // Map map = InterfaceUtils.postFormObject("http://10.206.0.10:8069", "/upload", pddMap);

        if (map.get("message").toString().contains("上传成功")) {
            String imageUrl = map.get("image_url").toString();
            String serviceUrl = map.get("service_url").toString();
            if (serviceUrl.contains("https://")) {
                map.put("url", serviceUrl);
            } else if (imageUrl.contains("https://")) {
                String pddImage = InterfaceUtils.getInterface(getImgResultUrl(), "/upload?token=" + accessToken + "&imageURL=" + imageUrl);
                // String pddImage = InterfaceUtils.getInterface("http://10.206.0.10:8070", "/upload?token=" + accessToken + "&imageURL=" + imageUrl);
                //调用pdd图片上传接口
                map.put("url", pddImage);
            } else {
                map.put("message", "图片上传失败");
            }
        }

        return map;
    }

    @Override
    public Map uploadImg(MultipartFile file) {
        String accessToken = configService.selectConfigByKey("image.token");
        Map<String,Object> map =  PddUtils.pddImageUpload(file,accessToken);
        System.out.println("图片上传"+ map);
        return map;
    }

    @Override
    public void synShopImg(Long userId) {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        // 获取该店铺下的所有商品
        List<ZhishuShopGoodsVo> zhishuShopGoodsVoList = baseMapper.selectShopGoodsByUser(userId);
        List<ZhishuShopImages> zhishuShopImagesList = Collections.synchronizedList(new ArrayList<>());
        List<ZhishuShopGoods> zhishuShopGoodsList = Collections.synchronizedList(new ArrayList<>());

        // 创建CountDownLatch等待所有任务完成
        CountDownLatch latch = new CountDownLatch(zhishuShopGoodsVoList.size());

        for (ZhishuShopGoodsVo bo : zhishuShopGoodsVoList) {
            executorService.submit(() -> {
                try {
                    ZhishuShopGoods add = MapstructUtils.convert(bo, ZhishuShopGoods.class);
                    add.setConditionCode(CHINESE_TO_CODE_MAP1.get(add.getConditionCode()));
                    Map map = new HashMap<String, Object>();
                    // 修剪孔网图片url
                    map.put("filepath", add.getBookPic());
                    map.put("goodsName", add.getGoodsName());
                    map.put("isbn", add.getIsbn());
                    map.put("isKW", true);
                    map.put("isNet", true);
                    InterfaceUtils.processImage(JSONObject.toJSONString(map));

                    String bookPic = fullBookPic(add);
                    add.setBookPic(bookPic);
                    try {
                        MultipartFile multipartFile = new UrlMultipartFile(bookPic, "book_cover.jpg");
                        Map pddImg = uploadImg(multipartFile);
                        String pddImgUrl = (String) pddImg.get("url");

                        baseMapper.updateById(add);

                        if (pddImgUrl != null) {
                            ZhishuShopImages zhishuShopImages = new ZhishuShopImages();
                            zhishuShopImages.setGoodsId(add.getId());
                            zhishuShopImages.setPath(pddImgUrl);
                            zhishuShopImages.setCreateBy(add.getUserId());
                            zhishuShopImages.setUpdateBy(add.getUserId());
                            zhishuShopImages.setCreateTime(DateUtils.getNowDate());
                            zhishuShopImages.setUpdateTime(DateUtils.getNowDate());
                            zhishuShopImages.setDelFlag("0");
                            zhishuShopImagesList.add(zhishuShopImages);
                        }
                    } catch (IOException e) {
                        log.error("上传图片失败", e);
                    }
                } finally {
                    latch.countDown();
                }
            });
        }
        /*try {
            latch.await(); // 等待所有任务完成
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }*/

        // baseMapper.updateBatchById(zhishuShopGoodsList);
        zhishuShopImagesMapper.insertBatch(zhishuShopImagesList);
    }

    @Override
    public void synPddShopImg(Long userId) {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        // 获取该店铺下的所有商品
        List<ZhishuShopGoodsVo> zhishuShopGoodsVoList = baseMapper.selectShopGoodsByUser(userId);

        for (ZhishuShopGoodsVo bo : zhishuShopGoodsVoList) {
            executorService.submit(() -> {

                ZhishuShopGoods add = MapstructUtils.convert(bo, ZhishuShopGoods.class);

                try {
                    MultipartFile multipartFile = new UrlMultipartFile(bo.getBookPic(), "book_cover.jpg");
                    Map pddImg = uploadImg(multipartFile);
                    String pddImgUrl = (String) pddImg.get("url");

                    if (pddImgUrl != null) {
                        ZhishuShopImages zhishuShopImages = new ZhishuShopImages();
                        zhishuShopImages.setGoodsId(add.getId());
                        zhishuShopImages.setPath(pddImgUrl);
                        zhishuShopImages.setCreateBy(add.getUserId());
                        zhishuShopImages.setUpdateBy(add.getUserId());
                        zhishuShopImages.setCreateTime(DateUtils.getNowDate());
                        zhishuShopImages.setUpdateTime(DateUtils.getNowDate());
                        zhishuShopImages.setDelFlag("0");
                        zhishuShopImagesMapper.insert(zhishuShopImages);
                    }
                } catch (IOException e) {
                    log.error("上传图片失败", e);
                }
            });
        }
    }

    @Override
    public Long getTaskDataNum(Long taskId) {
        return this.baseMapper.getTaskDataNum(taskId);
    }


    /**
     * 解析shipmentId，获取一、二、三级货区号
     * @param shipmentId 货号
     */
    private Integer parseShipmentId(String userId, String shipmentId) {
        if (shipmentId != null && shipmentId.length() == 5) {
            // 一级货区：前2位
            String firstLevel = shipmentId.substring(0, 2);

            char thirdChar = shipmentId.charAt(2);
            String secondLevel;
            String thirdLevel;

            if (Character.isDigit(thirdChar)) {
                // 第三位是数字：第三位是二级货区，第四五位是三级货区
                secondLevel = shipmentId.substring(2, 3);
                thirdLevel = shipmentId.substring(3, 5);
            } else {
                // 第三位是字母：第三四位是二级货区，第五位是三级货区
                secondLevel = shipmentId.substring(2, 4);
                thirdLevel = shipmentId.substring(4, 5);
            }

//            return waveDetailMapper.getIsJoinDistribution(userId, firstLevel, secondLevel, thirdLevel);
        }
        return null;
    }
}




