package org.dromara.zhishu.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.pdd.pop.sdk.common.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.domain.R;
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.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.service.ISysConfigService;
import org.dromara.zhishu.domain.RunningTask;
import org.dromara.zhishu.domain.bo.ShopBo;
import org.dromara.zhishu.domain.bo.TaskBo;
import org.dromara.zhishu.domain.dto.BookPriceInfoDto;
import org.dromara.zhishu.domain.dto.SuccessDataItemDto;
import org.dromara.zhishu.domain.dto.request.AddTaskLogRequest;
import org.dromara.zhishu.domain.dto.request.BatchSetSoldOutRequest;
import org.dromara.zhishu.domain.dto.request.DeleteSaleOutGoodsBatchRequest;
import org.dromara.zhishu.domain.dto.request.GoodsSaleStatusSetRequest;
import org.dromara.zhishu.domain.dto.response.AddTaskLogResponse;
import org.dromara.zhishu.domain.dto.response.GetBookByISBNResponse;
import org.dromara.zhishu.domain.vo.ShopDetailVo;
import org.dromara.zhishu.domain.vo.ShopVo;
import org.dromara.zhishu.domain.vo.TaskVo;
import org.dromara.zhishu.mapper.ShopMapper;
import org.dromara.zhishu.service.*;
import org.dromara.zhishu.service.client.BookCenterClient;
import org.dromara.zhishu.service.client.FileClient;
import org.dromara.zhishu.service.client.LogClient;
import org.dromara.zhishu.service.client.PddClient;
import org.dromara.zhishu.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.dev33.satoken.SaManager.log;

/**
 * 店铺主表Service业务层处理
 *
 * @author yxy
 * @date 2025-03-10
 */
@RequiredArgsConstructor
@Service
public class PddServiceImpl implements IPddService {

    private final ISysConfigService configService;

    private final IShopService shopService;

    private final FileClient fileClient;

    private final TaskServiceImpl taskService;

    private final IRunningTaskService runningTaskService;

    private final IRunningTaskByShopService runningTaskByShopService;

    private final IBookBaseInfoService bookBaseInfoService;

    private final IShopDetailService shopDetailService;

    private final PddClient pddClient;

    private final LogClient logClient;

    private final UrlUtil urlUtil;

    private final BookCenterClient bookCenterClient;

    @Override
    public void createShopGoodsList(ShopVo shopVo, TaskBo taskBo, Integer isOnsale) {
        System.out.println("任务开始:" + DateUtils.dateTimeNow(FormatsType.YYYY_MM_DD_HH_MM_SS));

        // 根据shopId查询数据表是否存在
        int checkMark = runningTaskByShopService.checkTableExists("t_running_task_" + shopVo.getId());
        if (checkMark == 0) {
            // 不存在则创建表
            runningTaskByShopService.createTable("t_running_task_" + shopVo.getId());
        }
        // 根据token获取店铺信息
        String accessToken = shopVo.getToken();
        /**
         *
         */
        Integer page = 1;
        Integer pageSize = 100;
        // 首次调用第一页,获取查询结果总数
        String pddIp = configService.selectConfigByKey("pdd.ip");
        String url = "/api/pdd/auth/getShopGoodsList?" +
                "accessToken=" + accessToken;
        if (isOnsale != null) {
            url += "&isOnsale=" + isOnsale;
        }
        String dataStr = InterfaceUtils.getInterface(pddIp, url + "&page=" + page + "&pageSize=" + pageSize);
        Map dataMap = JsonUtil.transferToObj(dataStr, Map.class);
        // 记录总数据
        List<Map<String, Object>> allList = new ArrayList<>();
        // 结束时间，如果传入的结束时间为空，则使用新的结束时间
        Long startTime = null;
        Long endTime = null;
        // 标记结束
        int endMark = 0;
        // 标记
        int runMark = 0;
        do {
            for (; page <= 100; page++) {
                url = "/api/pdd/auth/getShopGoodsList?" +
                        "accessToken=" + accessToken;
                if (startTime != null) {
                    url += "&createdAtFrom=" + startTime;
                }
                if (endTime != null) {
                    url += "&createdAtEnd=" + endTime;
                }
                if (isOnsale != null) {
                    url += "&isOnsale=" + isOnsale;
                }
                // 继续查询数据
                dataStr = InterfaceUtils.getInterface(pddIp, url + "&page=" + page + "&pageSize=" + pageSize);
                dataMap = JsonUtil.transferToObj(dataStr, Map.class);
                int errorMark = 0;
                while (dataMap == null) {
                    System.out.println("接口异常，正在重试...");
                    dataStr = InterfaceUtils.getInterface(pddIp, url + "&page=" + page + "&pageSize=" + pageSize);
                    dataMap = JsonUtil.transferToObj(dataStr, Map.class);
                    errorMark++;
                    if (errorMark > 10) {
                        break;
                    }
                }
                List<Map<String, Object>> dataList = new ArrayList<>();
                if (dataMap != null) {
                    dataList = (List<Map<String, Object>>) dataMap.get("goods_list");
                }
                if (runMark == 1 && dataList.size() == 0) {
                    endMark = 1;
                }
                if (dataList.size() > 0) {
                    List<RunningTask> runningTaskList = new ArrayList<>();
                    for (Map<String, Object> map : dataList) {
                        List<Map<String, Object>> skuList = (List<Map<String, Object>>) map.get("sku_list");
                        // 构建 JSON 对象
                        JSONObject json = new JSONObject();
                        json.put("trilateralId", map.get("goods_id").toString());
                        json.put("img", map.get("thumb_url").toString());
                        json.put("finishTime", DateUtilsUtils.getNowDate());
                        json.put("imageSelect", "11");
                        json.put("totalPrice", "");
                        json.put("isbn", skuList.get(0).get("outer_goods_id").toString());
                        json.put("priority", "3");
                        json.put("imageBigUrl", "");
                        json.put("title", map.get("goods_name").toString());
                        json.put("quality", "100");
                        json.put("shopType", shopVo.getShopType());
                        json.put("stock", map.get("goods_quantity").toString());
                        json.put("skuCode", "");
                        json.put("skuId", skuList.get(0).get("sku_id").toString());
                        json.put("isOnSale", map.get("is_onsale").toString());
                        json.put("isMoreSku", map.get("is_more_sku").toString());
                        // 如果数据存在则修改，不存在则添加
                        RunningTask runningTask = runningTaskByShopService.selectVoByTrilateralId("t_running_task_" + shopVo.getId(), map.get("goods_id").toString());
                        if (runningTask == null) {
                            String jsonString = json.toString();
                            runningTask = new RunningTask();
                            runningTask.setTaskId(taskBo.getId());
                            runningTask.setShopId(shopVo.getId());
                            runningTask.setGoodsId(Long.parseLong(map.get("goods_id").toString()));
                            runningTask.setRandomNum(System.currentTimeMillis());
                            runningTask.setTaskName(taskBo.getFileName());
                            runningTask.setPriority(255L);
                            runningTask.setData("");
                            runningTask.setStatus("2");
                            runningTask.setTaskType("GET_SHOP_GOODS");
                            runningTask.setSuccessData(jsonString);
                            runningTask.setCallBackData("拉取成功");
                            // 新增
                            runningTaskList.add(runningTask);
                        } else {
                            // 解析价格和上架编码
                            Map successData = JsonUtil.transferToObj(runningTask.getSuccessData(), Map.class);
                            String totalPrice = successData.get("totalPrice").toString();
                            String skuCode = successData.get("skuCode").toString();
                            json.put("totalPrice", totalPrice);
                            json.put("skuCode", skuCode);
                            String jsonString = json.toString();
                            // 修改文件名和状态
                            runningTask.setTaskId(taskBo.getId());
                            runningTask.setTaskName(taskBo.getFileName());
                            runningTask.setStatus("2");
                            runningTask.setSuccessData(jsonString);
                            runningTaskByShopService.update("t_running_task_" + shopVo.getId(), runningTask);
                        }
                    }
                    if (runningTaskList.size() > 0) {
                        runningTaskByShopService.batchInsert("t_running_task_" + shopVo.getId(), runningTaskList);
                    }
                }
                if (page == 100 || dataList.size() == 0) {
                    if (startTime == null && endTime == null && dataList.size() == 0) {
                        runMark = 1;
                        break;
                    }
                    if (dataList.size() == 0) {
                        startTime = endTime;
                    } else {
                        startTime = Long.parseLong(dataList.get(dataList.size() - 1).get("created_at").toString());
                    }
                    Long nowTime = System.currentTimeMillis() / 1000;
                    Long newEndTime = addDaysToTimestamp(startTime, 30);
                    if (newEndTime < nowTime) {
                        endTime = newEndTime;
                    } else {
                        endTime = nowTime;
                        runMark = 1;
                    }
                    page = 1;
                    break;
                }
            }
        } while (endMark == 0);
        //此时状态为3的数据都是为拉取的数据，都删除
        runningTaskByShopService.deleteByStatus("t_running_task_" + shopVo.getId(), "3");
        // 修改状态为完成
        runningTaskByShopService.updateStatus("t_running_task_" + shopVo.getId());
    }


    @Override
    public void createShopGoodsDetailList(ShopVo shopVo, TaskBo taskBo, Integer isOnsale) {
        System.out.println("任务开始:" + DateUtils.dateTimeNow(FormatsType.YYYY_MM_DD_HH_MM_SS));

        // 根据shopId查询数据表是否存在
        int checkMark = runningTaskByShopService.checkTableExists("t_running_task_" + shopVo.getId());
        if (checkMark == 0) {
            // 不存在则创建表
            runningTaskByShopService.createTable("t_running_task_" + shopVo.getId());
        }
        // 根据token获取店铺信息
        String accessToken = shopVo.getToken();
        /**
         *
         */
        Integer page = 1;
        Integer pageSize = 100;
        // 首次调用第一页,获取查询结果总数
        String pddIp = configService.selectConfigByKey("pdd.ip");
        String url = "/api/pdd/auth/getShopGoodsList?" +
                "accessToken=" + accessToken;
        if (isOnsale != null) {
            url += "&isOnsale=" + isOnsale;
        }
        String dataStr = InterfaceUtils.getInterface(pddIp, url + "&page=" + page + "&pageSize=" + pageSize);
        Map dataMap = JsonUtil.transferToObj(dataStr, Map.class);
        // 记录总数据
        List<Map<String, Object>> allList = new ArrayList<>();
        // 结束时间，如果传入的结束时间为空，则使用新的结束时间
        Long startTime = null;
        Long endTime = null;
        // 标记结束
        int endMark = 0;
        // 标记
        int runMark = 0;
        do {
            for (; page <= 100; page++) {
                url = "/api/pdd/auth/getShopGoodsDetailList?" +
                        "accessToken=" + accessToken;
                if (startTime != null) {
                    url += "&createdAtFrom=" + startTime;
                }
                if (endTime != null) {
                    url += "&createdAtEnd=" + endTime;
                }
                if (isOnsale != null) {
                    url += "&isOnsale=" + isOnsale;
                }
                // 继续查询数据
                dataStr = InterfaceUtils.getInterface(pddIp, url + "&page=" + page + "&pageSize=" + pageSize);
                dataMap = JsonUtil.transferToObj(dataStr, Map.class);
                int errorMark = 0;
                while (dataMap == null) {
                    System.out.println("接口异常，正在重试...");
                    dataStr = InterfaceUtils.getInterface(pddIp, url + "&page=" + page + "&pageSize=" + pageSize);
                    dataMap = JsonUtil.transferToObj(dataStr, Map.class);
                    errorMark++;
                    if (errorMark > 10) {
                        break;
                    }
                }
                List<Map<String, Object>> dataList = new ArrayList<>();
                if (dataMap != null) {
                    dataList = (List<Map<String, Object>>) dataMap.get("goods_list");
                }
                if (runMark == 1 && dataList.size() == 0) {
                    endMark = 1;
                }
                if (dataList.size() > 0) {
                    List<RunningTask> runningTaskList = new ArrayList<>();
                    for (Map<String, Object> map : dataList) {
                        List<Map<String, Object>> skuList = (List<Map<String, Object>>) map.get("sku_list");
                        // 构建 JSON 对象
                        JSONObject json = new JSONObject();
                        json.put("trilateralId", map.get("goods_id").toString());
                        json.put("img", map.get("thumb_url").toString());
                        json.put("finishTime", DateUtilsUtils.getNowDate());
                        json.put("imageSelect", "11");
                        json.put("totalPrice", map.get("price") == null ? "" : map.get("price").toString());
                        json.put("isbn", skuList.get(0).get("outer_goods_id").toString());
                        json.put("priority", "3");
                        json.put("imageBigUrl", "");
                        json.put("title", map.get("goods_name").toString());
                        json.put("quality", "100");
                        json.put("shopType", shopVo.getShopType());
                        json.put("stock", map.get("goods_quantity").toString());
                        json.put("skuCode", map.get("skuCode") == null ? "" : map.get("skuCode").toString());
                        json.put("skuId", skuList.get(0).get("sku_id").toString());
                        json.put("isOnSale", map.get("is_onsale").toString());
                        json.put("isMoreSku", map.get("is_more_sku").toString());
                        String jsonString = json.toString();
                        // 如果数据存在则修改，不存在则添加
                        RunningTask runningTask = runningTaskByShopService.selectVoByTrilateralId("t_running_task_" + shopVo.getId(), map.get("goods_id").toString());
                        if (runningTask == null) {

                            runningTask = new RunningTask();
                            runningTask.setTaskId(taskBo.getId());
                            runningTask.setShopId(shopVo.getId());
                            runningTask.setGoodsId(Long.parseLong(map.get("goods_id").toString()));
                            runningTask.setRandomNum(System.currentTimeMillis());
                            runningTask.setTaskName(taskBo.getFileName());
                            runningTask.setPriority(255L);
                            runningTask.setData("");
                            runningTask.setStatus("2");
                            runningTask.setTaskType("GET_SHOP_GOODS");
                            runningTask.setSuccessData(jsonString);
                            runningTask.setCallBackData("拉取成功");
                            // 新增
                            runningTaskList.add(runningTask);
                        } else {
                            // 修改文件名和状态
                            runningTask.setTaskId(taskBo.getId());
                            runningTask.setTaskName(taskBo.getFileName());
                            runningTask.setStatus("2");
                            runningTask.setSuccessData(jsonString);
                            runningTaskByShopService.update("t_running_task_" + shopVo.getId(), runningTask);
                        }
                    }
                    if (runningTaskList.size() > 0) {
                        runningTaskByShopService.batchInsert("t_running_task_" + shopVo.getId(), runningTaskList);
                    }
                }
                if (page == 100 || dataList.size() == 0) {
                    if (startTime == null && endTime == null && dataList.size() == 0) {
                        runMark = 1;
                        break;
                    }
                    if (dataList.size() == 0) {
                        startTime = endTime;
                    } else {
                        startTime = Long.parseLong(dataList.get(dataList.size() - 1).get("created_at").toString());
                    }
                    Long nowTime = System.currentTimeMillis() / 1000;
                    Long newEndTime = addDaysToTimestamp(startTime, 30);
                    if (newEndTime < nowTime) {
                        endTime = newEndTime;
                    } else {
                        endTime = nowTime;
                        runMark = 1;
                    }
                    page = 1;
                    break;
                }
            }
        } while (endMark == 0);
        //此时状态为3的数据都是为拉取的数据，都删除
        runningTaskByShopService.deleteByStatus("t_running_task_" + shopVo.getId(), "3");
        // 修改状态为完成
        runningTaskByShopService.updateStatus("t_running_task_" + shopVo.getId());
    }

    @Override
    public TableDataInfo<Map<String, Object>> getShopGoodsList(String shopId, String isOnsale,String isbn,String priceDown,String priceUp,String startDate,String endDate, Integer page, Integer pageSize,String goodsName,String stockDown,String stockUp,String trilateralId,String goodsCode,String skuCode) {
//        ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));

        String[] shopIds=shopId.split(",");
        Page<Map<String, Object>> result = new Page<>();
        result.setCurrent(page);
        result.setSize(pageSize);
        Long pageNum = (long) ((page - 1) * pageSize);
        int total=0;
        for (String shopIdsingle : shopIds){
            int checkMark = runningTaskByShopService.checkTableExists("t_running_task_" + shopIdsingle);
            if (checkMark == 0) {
                result.setTotal(0);
                result.setRecords(new ArrayList<>());
            } else {
                List<Map> mapList = runningTaskByShopService.selectGetShopGoodsList("t_running_task_" + shopIdsingle, isOnsale,isbn,priceDown,priceUp,startDate,endDate,pageNum, Long.parseLong(pageSize.toString()), goodsName, stockDown, stockUp, trilateralId, goodsCode, skuCode);

                List<Map<String, Object>> mapList2 = new ArrayList<>();

                for (Map map : mapList) {
                    Map successData = JsonUtil.transferToObj((String) map.get("success_data"), Map.class);

                    Map map2 = new HashMap();
                    map2.put("shopId",map.get("shop_id"));
                    map2.put("Title", successData.get("title"));
                    map2.put("TrilateralId", successData.get("trilateralId"));
                    map2.put("SkuCode", successData.get("skuCode") == null ? (successData.get("artNo") == null ?  "": successData.get("artNo")) : successData.get("skuCode"));
                    map2.put("SkuId", successData.get("skuId"));
                    map2.put("ISBN", successData.get("isbn"));
                    map2.put("GoodsCode", successData.get("goodsCode"));



                    // 获取img值并进行类型判断
                    Object imgObj = successData.get("img");
                    boolean isImgString = (imgObj instanceof String);
                    if (isImgString){
                        map2.put("Img", imgObj);  // 保持原有值
                    }else{
                        Map imgMap = (Map) imgObj;
                        List carouselUrlArray = (List) imgMap.get("carousel_url_array");
                        if (!carouselUrlArray.isEmpty()){
                            map2.put("Img",carouselUrlArray.get(0));
                        }else{
                            map2.put("Img", "");
                        }
                    }



                    map2.put("ImgBigUrl", "");
                    map2.put("TotalPrice", successData.get("totalPrice"));
                    map2.put("Stock", successData.get("stock"));
                    map2.put("FinishTime", successData.get("finishTime"));
                    map2.put("IsOnSale", successData.get("isOnSale"));
                    map2.put("IsMoreSku", "");
                    mapList2.add(map2);
                }

                result.setRecords(mapList2);
                total  =total+  runningTaskByShopService.selectGetShopGoodsNum("t_running_task_" + shopIdsingle, isOnsale,isbn,priceDown,priceUp,startDate,endDate, goodsName, stockDown, stockUp, trilateralId, goodsCode, skuCode);
            }
        }

        result.setTotal(total);


        return TableDataInfo.build(result);


    }

    @Override
    public List<Map> emport(String shopId, String isOnsale) {
        int checkMark = runningTaskByShopService.checkTableExists("t_running_task_" + shopId);
        if (checkMark == 0) {
            return new ArrayList<>();
        } else {
            return runningTaskByShopService.selectGetShopGoodsList("t_running_task_" + shopId, isOnsale,null,"","",null,null, 0L, 9999999L,null,null,null,null,null,null);
        }
    }

    /**
     * 给定一个 10 位秒级时间戳，增加指定的天数（如 30 天），并返回新的秒级时间戳
     *
     * @param timestampSeconds 10 位时间戳（秒）
     * @param daysToAdd        要增加的天数（如 30 表示加 30 天）
     * @return 新的秒级时间戳
     */
    public static long addDaysToTimestamp(long timestampSeconds, int daysToAdd) {
        LocalDateTime dateTime = LocalDateTime.ofInstant(
                Instant.ofEpochSecond(timestampSeconds),
                ZoneId.systemDefault()
        );

        // 增加指定天数
        LocalDateTime newDateTime = dateTime.plusDays(daysToAdd);

        // 返回秒级时间戳
        return newDateTime.atZone(ZoneId.systemDefault()).toEpochSecond();
    }


    /**
     * 下架重复
     * @param shopId 店铺ID
     */
    @Override
    public void batchSetSoldOut(Long shopId) {
        ShopVo shopVo = shopService.queryById(shopId);
        // 判断token是否不为空
        String token = shopVo.getToken();
        if (ObjectUtil.isEmpty(token)) {
            throw new ServiceException("店铺未授权，无法批量下架商品");
        }
        List<SuccessDataItemDto> items = runningTaskByShopService.selectRepeatNoPage("t_running_task_" + shopId);
        if (!items.isEmpty()) {

            // 创建下架任务
            TaskBo taskBo = new TaskBo();
            taskBo.setTaskType("EDIT_ISONSALE_GOODS");
            taskBo.setFileName("下架重复商品任务");
            taskBo.setShopIds(shopId.toString());
            taskBo.setShopNames(shopVo.getShopName());
            taskBo.setDataNum((long) items.size());
            taskBo.setTaskStatus("0");
            taskBo.setStatus("0");
            taskService.insertByBo(taskBo);
            //开启线程
            Thread thread  = new Thread(() -> {
                for(SuccessDataItemDto item : items){
                    //调用接口
                    Map<String,String> mapData = new HashMap();
                    mapData.put("priority","4");
                    mapData.put("retry_count","3");
                    mapData.put("taskId",taskBo.getId().toString());
                    mapData.put("shopId",shopId.toString());
                    mapData.put("token",shopVo.getToken());
                    mapData.put("isOnsale","1");
                    mapData.put("serviceName","EDIT_ISONSALE_GOODS");
                    mapData.put("trilateralId", item.getTrilateralId());
                    mapData.put("shopType",shopVo.getShopType());
                    if(shopVo.getShopType().equals("5")){
                        //咸鱼
                        mapData.put("appId", shopVo.getMallId().toString());
                        mapData.put("shopKey",shopVo.getShopKey());
                    }
                    /**
                     * 创建运行任务对象
                     */
                    RunningTask runningTaskDate = new RunningTask();
                    runningTaskDate.setTaskId(taskBo.getId());
                    runningTaskDate.setShopId(shopVo.getId());
                    runningTaskDate.setGoodsId(0L);
                    runningTaskDate.setRandomNum(System.currentTimeMillis());
                    runningTaskDate.setTaskName(taskBo.getFileName());
                    runningTaskDate.setPriority(255L);
                    runningTaskDate.setData(JsonUtil.transferToJson(mapData));
                    runningTaskDate.setStatus("0");
                    runningTaskDate.setTaskType("EDIT_ISONSALE_GOODS");
                    runningTaskService.insert(runningTaskDate);
                }
            });
            thread.start();

        }else{
            throw new ServiceException("该店铺下没有需要下架的商品");
        }

    }

    @Override
    public void editShopGoodsAllByIsOnSale(ShopVo shopVo, TaskBo taskBo, String isOnSale, String isbn, String priceDown, String priceUp, String startDate, String endDate,String goodsName,String stockDown,String stockUp,String trilateralId,String goodsCode,String skuCode) {
        String isOnSaleNum = isOnSale.equals("0") ? "1" : "0";

        int count = runningTaskByShopService.selectGetShopGoodsListCount("t_running_task_" + shopVo.getId(), isOnSaleNum, isbn, priceDown, priceUp, startDate, endDate,goodsName,stockDown,stockUp,trilateralId,goodsCode,skuCode);

        Long pageSize = 100L;
        // 计算总页数
        Long totalPages = (count + pageSize - 1) / pageSize;

        // 从最后一页开始往前执行
        int runNum = 0;
        List<Map<String,Object>> bodyList = new ArrayList<>();
        Map setTaskBodyMap = new HashMap();
        setTaskBodyMap.put("task_id",taskBo.getId());

        Long usageCount = shopService.checkUsageCount(shopVo);

        for (Long pageNum = totalPages; pageNum >= 1; pageNum--) {
            Long page = (pageNum - 1) * pageSize;
            List<Map> dataMap = runningTaskByShopService.selectGetShopGoodsList("t_running_task_" + shopVo.getId(), isOnSaleNum, isbn, priceDown, priceUp, startDate, endDate, page, pageSize,goodsName,stockDown,stockUp,trilateralId,goodsCode,skuCode);

            if (dataMap.size() == 0) {
                continue;
            }

            for (Map map : dataMap) {
                runNum++;
                Map successData = JsonUtil.transferToObj((String) map.get("success_data"), Map.class);
                Map body = new HashMap();
                Map bookInfo = new HashMap();
                bookInfo.put("isbn",successData.get("isbn").toString());
                bookInfo.put("trilateralId",successData.get("trilateralId").toString());
                bookInfo.put("goodsCode","");
                body.put("book_info",bookInfo);
                Map detail = new HashMap();
                // 1 上架  2 下架
                detail.put("status",isOnSale.equals("0") ? 2 : 1);
                body.put("detail",detail);
                bodyList.add(body);

                if (bodyList.size() % 500 == 0 || runNum == count){
                    NewTaskUtils.newTaskPost(taskBo.getId().toString(),shopVo.getId().toString(),bodyList);
                    // 清空列表，准备下一批
                    bodyList.clear();
                }

                usageCount--;
                if (usageCount == 0){
                    break;
                }
            }
            if (usageCount == 0){
                break;
            }
        }
        // 处理剩余数据
        if (!bodyList.isEmpty()) {
            NewTaskUtils.newTaskPost(taskBo.getId().toString(),shopVo.getId().toString(),bodyList);
            System.out.println("新发布任务发布结束："+bodyList.size()+"条");
        }
        // 更新使用次数
        shopService.updateUsageCount(shopVo,usageCount);
    }

    /**
     * 通过csv批量翻新商品上架拼多多
     *
     * @param file
     * @param taskBo
     * @param shopVo
     */
    @Async
    @Override
    public void batchRenovateOnSaleByCsv(MultipartFile file, TaskBo taskBo, ShopVo shopVo) {
        try {
            String defaultStock = "0";
            ShopDetailVo shopDetailVo = shopDetailService.queryByShopId(shopVo.getId());
            if (shopDetailVo != null) defaultStock = String.valueOf(shopDetailVo.getStockDeff());
            // 读取CSV文件
            List<BookPriceInfoDto> dataList = readCsvData(file);

            // 分批处理数据
            int batchSize = 1000;
            int totalBatches = (int) Math.ceil((double) dataList.size() / batchSize);

            // 处理每个批次
            for (int batchNum = 0; batchNum < totalBatches; batchNum++) {
                int fromIndex = batchNum * batchSize;
                int toIndex = Math.min((batchNum + 1) * batchSize, dataList.size());
                List<BookPriceInfoDto> batchList = dataList.subList(fromIndex, toIndex);

                // 计算当前批次需要的线程数 (最多10个)
                int threadCount = Math.min(10, batchList.size());

                // 使用CountDownLatch等待所有线程完成
                CountDownLatch latch = new CountDownLatch(threadCount);

                // 分配每个线程处理的数据量
                int perThreadSize = (int) Math.ceil((double) batchList.size() / threadCount);

                for (int i = 0; i < threadCount; i++) {
                    int threadFrom = i * perThreadSize;
                    int threadTo = Math.min((i + 1) * perThreadSize, batchList.size());
                    List<BookPriceInfoDto> batchData = batchList.subList(threadFrom, threadTo);

                    String finalDefaultStock = defaultStock;
                    ThreadPoolUtils.execute(() -> {
                        try {
                            for (BookPriceInfoDto data : batchData) {
                                // 调用单条数据处理逻辑
                                processSingleData(data, shopVo, taskBo.getId(), taskBo.getFileName(), finalDefaultStock, "0", "1");
                            }
                        } finally {
                            latch.countDown();
                        }
                    });
                }

                // 等待当前批次所有线程完成
                latch.await();
            }
        } catch (Exception e) {
            throw new ServiceException("批量处理CSV文件失败:" + e.getMessage());
        }
    }

    // 读取CSV文件
    private List<BookPriceInfoDto> readCsvData(MultipartFile file) throws IOException {
        try (Reader reader = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8)) {
            CsvToBean<BookPriceInfoDto> csvToBean = new CsvToBeanBuilder<BookPriceInfoDto>(reader)
                    .withType(BookPriceInfoDto.class)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();
            return csvToBean.parse();
        }
    }

    // 单条数据处理方法
    public Boolean processSingleData(BookPriceInfoDto data, ShopVo shopVo, Long taskId, String taskName, String defaultStock, String status, String taskType) {

        // 将字符串转换为BigDecimal以确保精确计算
        BigDecimal fen = new BigDecimal(data.getCorePrice());
        // 分转元：除以100
        BigDecimal yuan = fen.divide(new BigDecimal("100"));
        // 设置小数位数并四舍五入
        DecimalFormat df = new DecimalFormat("0.00");

        Map goMap = new HashMap();
        goMap.put("priority", "3");
        goMap.put("retry_count", "3");
        goMap.put("isbn", data.getIsbn());
        goMap.put("totalPrice", df.format(yuan));
        goMap.put("stock", defaultStock);
        goMap.put("bookName", data.getBookName());
        goMap.put("code", data.getIsbn());
        goMap.put("imgBigUrl", "");
        goMap.put("artNo", data.getIsbn());
        goMap.put("taskId", taskId.toString());
        goMap.put("shopId", shopVo.getId().toString());
        goMap.put("imageSelect", "12");
        goMap.put("way", "2");

        RunningTask runningTask = new RunningTask();
        runningTask.setTaskId(taskId);
        runningTask.setShopId(shopVo.getId());
        runningTask.setGoodsId(Long.valueOf(data.getPlatformId()));
        runningTask.setRandomNum(System.currentTimeMillis());
        runningTask.setTaskName(taskName);
        runningTask.setPriority(255L);
        runningTask.setData(JsonUtil.transferToJson(goMap));
        runningTask.setStatus(status);
        runningTask.setTaskType(taskType);

        // 删除pdd商品
        DeleteSaleOutGoodsBatchRequest deleteSaleOutGoodsBatchRequest = new DeleteSaleOutGoodsBatchRequest();
        deleteSaleOutGoodsBatchRequest.setToken(shopVo.getToken());
        List<Long> goodsIds = List.of(Long.valueOf(data.getPlatformId()));
        deleteSaleOutGoodsBatchRequest.setGoodsIds(goodsIds);
        R<Boolean> deleteSaleOutGoodsBatchR = pddClient.deleteSaleOutGoodsBatch(UrlUtil.getPddServiceUrl(), deleteSaleOutGoodsBatchRequest);
        if (!R.isError(deleteSaleOutGoodsBatchR)) {
            // 同步删除数据库商品
            runningTaskByShopService.deleteByGoodsId("t_running_task_" + shopVo.getId(), data.getPlatformId());
        }

        // 无论是否删除成功都要重新发布上架商品
        runningTaskService.insert(runningTask);
        return Boolean.TRUE;
    }

    // 翻新数据处理方法
    @Async
    @Override
    public void renovateOnSale(BookPriceInfoDto data, String shopId, String taskId) {
        // 获取店铺信息
        ShopVo shopVo = shopService.queryById(Long.valueOf(shopId));

        // 获取任务详情
        TaskVo taskVo = taskService.queryById(Long.valueOf(taskId));

        // 获取默认库存
        String defaultStock = "0";
        ShopDetailVo shopDetailVo = shopDetailService.queryByShopId(Long.valueOf(shopId));
        if (shopDetailVo != null) defaultStock = String.valueOf(shopDetailVo.getStockDeff());
        processSingleData(data, shopVo, taskVo.getId(), taskVo.getFileName(), defaultStock, "0", "UPDATE_GOODS_PRICE");

    }

    public String getSaleTemplateIdByShopId(Long shopId) {
        // 直接调用Mapper查询价格模板ID
        return shopDetailService.selectSaleTemplateIdByShopId(shopId);
    }

    @Override
    public void sendPddGoodsToTargetShop(String shopId, String targetShopId, TaskBo taskBo, ShopVo shopVo) {
         //查询出搬家数据
        Long pageNum = 1L;
        Long pageSize = 100L;
        Long maxPages = 5L; // 防止死循环
        String taskId=taskBo.getId().toString();
        try {
            while (pageNum <= maxPages) {
                Long offset = (pageNum - 1) * pageSize;
                List<Map> dataMap = runningTaskByShopService.selectGetShopGoodsListAll(
                        "t_running_task_" + shopId, // 假设商品表名格式
                        "1",
                        offset,
                        pageSize);
                if (dataMap == null || dataMap.isEmpty()) {
                    break;
                }
                List<RunningTask> runningTaskList = new ArrayList<>();
                List<RunningTask> runningTaskList1 = new ArrayList<>();
                for (Map map : dataMap) {

                    try {
                        // 关键字段非空检查
                        if (map.get("goods_id") == null) {
                            log.warn("商品ID为空，跳过处理");
                            continue;
                        }

                        // 获取原始 success_data
                        Object dataObj = map.get("data");
                        Map<String, Object> dataMaptable = null;

                        Object successDataObj = map.get("success_data");
                        Map<String, Object> successDataObjMaptable = null;
                        Map<String, Object> jsonmap = new HashMap<>();

                        if (dataObj != null && StringUtils.isNotBlank(dataObj.toString())) {
                            try {
                                // 尝试解析为 Map
                                dataMaptable = JsonUtil.transferToObj(dataObj.toString(), Map.class);
                            } catch (Exception e) {
                                log.warn("解析 success_data 失败: {}, 原始数据: {}", e.getMessage(), dataObj);
                                dataMaptable = new HashMap<>();
                                dataMaptable.put("originalData", dataObj.toString());
                            }
                        }
                        if (dataMaptable == null) {
                            dataMaptable = new HashMap<>();
                        }

                        if (successDataObj != null && StringUtils.isNotBlank(successDataObj.toString())) {
                            try {
                                // 尝试解析为 Map
                                successDataObjMaptable = JsonUtil.transferToObj(successDataObj.toString(), Map.class);
                            } catch (Exception e) {
                                log.warn("解析 success_data 失败: {}, 原始数据: {}", e.getMessage(), successDataObj);
                                dataMaptable = new HashMap<>();
                                dataMaptable.put("originalData", successDataObj.toString());
                            }
                        }
                        if (successDataObjMaptable == null) {
                            successDataObjMaptable = new HashMap<>();
                        }

                        // 添加 isMove 属性
                        dataMaptable.put("isMove", "1");
                        dataMaptable.put("shopId", targetShopId);
                        dataMaptable.put("taskId", taskId);
                        jsonmap.put("retry_count", "3");
                        jsonmap.put("priority", "3");
                        jsonmap.put("isbn", successDataObjMaptable.get("isbn"));

                        // 从Map中获取totalPrice的值
                        Object totalPriceObj = successDataObjMaptable.get("totalPrice");
                        if (totalPriceObj != null) {
                            // 将分转换为元
                            double totalPriceYuan;

                            if (totalPriceObj instanceof Number) {
                                // 如果是数值类型
                                totalPriceYuan = ((Number) totalPriceObj).doubleValue() / 100.0;
                            } else {
                                // 如果是字符串或其他类型
                                try {
                                    totalPriceYuan = Double.parseDouble(totalPriceObj.toString()) / 100.0;
                                } catch (NumberFormatException e) {
                                    // 处理转换异常
                                    totalPriceYuan = 0.0;
                                }
                            }

                            // 将转换后的元单位价格存入jsonmap
                            jsonmap.put("totalPrice", totalPriceYuan);
                        } else {
                            // 如果totalPrice为null，可以设置默认值或处理异常
                            jsonmap.put("totalPrice", 1000);
                        }

                        jsonmap.put("stock",successDataObjMaptable.get("stock"));
                        jsonmap.put("taskId", taskId);
                        jsonmap.put("shopId",targetShopId);
                        jsonmap.put("imageSelect", map.get("imageSelect"));
                        jsonmap.put("imageChoice", map.get("imageChoice"));
                        jsonmap.put("way",map.get("way"));
                        jsonmap.put("isMove", "1");
                        jsonmap.put("imgBigUrl", successDataObjMaptable.get("img"));


                        RunningTask runningTask = new RunningTask();
                        runningTask.setTaskId(Long.parseLong(taskId));
                        runningTask.setShopId(Long.parseLong(targetShopId)); // 目标店铺
                        runningTask.setGoodsId(Long.parseLong(map.get("goods_id").toString()));
                        runningTask.setRandomNum(System.currentTimeMillis());
                        runningTask.setStatus("3");
                        runningTask.setCallBackData("搬家成功");
                        runningTask.setPriority(255L);
                        runningTask.setData("");
                        runningTask.setTaskType("GET_SHOP_GOODS");

                        // success_data 可能为空
                        RunningTask runningTask1 = new RunningTask();
                        runningTask1.setTaskId(Long.parseLong(taskId));
                        runningTask1.setShopId(Long.parseLong(targetShopId)); // 目标店铺
                        runningTask1.setGoodsId(Long.parseLong(map.get("goods_id").toString()));
                        runningTask1.setRandomNum(System.currentTimeMillis());
                        runningTask1.setStatus("0");
                        runningTask1.setPriority(255L);
                        runningTask1.setData("");
                        runningTask1.setTaskType("GET_MOVE_GOODS");


                        // 序列化并设置
                        String successDataJson = JsonUtil.transferToJson(dataMaptable);
                        String jsonmapDataJson = JsonUtil.transferToJson(jsonmap);

                        runningTask.setData(successDataJson);
                        runningTask1.setData(jsonmapDataJson);

                        runningTaskList.add(runningTask);
                        runningTaskList1.add(runningTask1);
                    } catch (Exception e) {
                        // 记录具体错误信息
                        log.error("处理商品数据时出错: {}, 数据: {}",
                                e.getMessage(), map, e);
                    }
                }

                // 批量插入到目标店铺的任务表
                if (!runningTaskList.isEmpty()) {
                    // 注意：这里应该是目标店铺的任务表
                    runningTaskByShopService.batchInsert(
                            "t_running_task_" + targetShopId, // 关键修改
                            runningTaskList);

                    log.info("成功插入 {} 条任务到店铺 {}",
                            runningTaskList.size(), targetShopId);
                }
                if (!runningTaskList1.isEmpty()) {
                    System.out.println(runningTaskList1);
                    //插入任务表中
                    runningTaskByShopService.batchInsert("t_running_task",runningTaskList1);
                    log.info("任务到店铺", runningTaskList1.size());
                }



                pageNum++;
                // 如果返回的数据少于 pageSize，说明是最后一页
                if (dataMap.size() < pageSize) {
                    break;
                }


            }


        }catch (Exception e){
            log.error("sendPddGoodsToTargetShop 执行失败: ", e);
            throw new RuntimeException("商品搬家任务执行失败", e);
        }


    }

    @Override
    public Boolean clearRedisBuffer(String shopId) {
        try {
            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("key", shopId);

            // 调用接口
            String ip = "http://36.212.12.92:30180";
            String url = "/deleteRedisKey";
            String responseStr = InterfaceUtils.getInterfaceGetWithParams(ip, url, params);

            // 解析响应
            Map<String, Object> responseMap = JsonUtil.transferToObj(responseStr, Map.class);
            if (responseMap != null && responseMap.containsKey("success")) {
                return (Boolean) responseMap.get("success");
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
