package org.dromara.zhishu.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.pdd.pop.sdk.common.util.JsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.base.BaseException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.oss.entity.UploadResult;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.SysUser;
import org.dromara.system.service.ISysConfigService;
import org.dromara.zhishu.domain.StockChangeLog;
import org.dromara.zhishu.domain.Task;
import org.dromara.zhishu.domain.ZhishuShopGoods;
import org.dromara.zhishu.domain.bo.BatchUpdateCargoBo;
import org.dromara.zhishu.domain.bo.TaskBo;
import org.dromara.zhishu.domain.bo.ZhishuShopGoodsBo;
import org.dromara.zhishu.domain.bo.ZhishuShopGoodsDetailBo;
import org.dromara.zhishu.domain.dto.SuccessDataItemDto;
import org.dromara.zhishu.domain.dto.request.*;
import org.dromara.zhishu.domain.excel.GoodsExcel;
import org.dromara.zhishu.domain.vo.*;
import org.dromara.zhishu.domain.vo.ProductSubmitResultVo;
import org.dromara.zhishu.service.*;
import org.dromara.zhishu.service.client.KfzClient;
import org.dromara.zhishu.service.factory.ShopGoodsFactory;
import org.dromara.zhishu.service.strategy.ShopGoodsStrategy;
import org.dromara.zhishu.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * 商品信息
 *
 * @author Lion Li
 * @date 2025-03-07
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@Lazy
@RequestMapping("/zhishu/shopGoods")
public class ZhishuShopGoodsController extends BaseController {

    private final IZhishuShopGoodsService zhishuShopGoodsService;
    private final IShopService shopService;
    private final IShopGoodsPublishedService shopGoodsPublishedService;
    private final ITaskService taskService;
    private final IZhishuShopGoodsDetailService zhishuShopGoodsDetailService;
    private final ITFreightService freightService;
    private final ITShelvesService shelvesService;
    private final ITDepotService depotService;;

    @Autowired
    private IRunningTaskByShopService iRunningTaskByShopService;

    @Autowired
    private ISysConfigService configService;


    @Autowired
    private RestTemplate restTemplate;
    /**
     * 查询商品信息列表
     */
    @SaCheckPermission("zhishu:shopGoods:list")
    @GetMapping("/list")
    @SaIgnore
    public TableDataInfo<ZhishuShopGoodsVo> list(ZhishuShopGoodsBo bo, PageQuery pageQuery) {
        return zhishuShopGoodsService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出商品信息列表
     */
    @SaCheckPermission("zhishu:shopGoods:export")
    @Log(title = "商品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ZhishuShopGoodsBo bo, HttpServletResponse response) {
        List<ZhishuShopGoodsVo> list = zhishuShopGoodsService.queryList(bo);
        ExcelUtil.exportExcel(list, "商品信息", ZhishuShopGoodsVo.class, response);
    }

    /**
     * 获取商品信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zhishu:shopGoods:query")
    @GetMapping("/{id}")
    public R<ZhishuShopGoodsVo> getInfo(@NotNull(message = "主键不能为空")
                                        @PathVariable String id) {
        return R.ok(zhishuShopGoodsService.queryById(id));
    }

    /**
     * 根据商品条码查询商品信息
     *
     * @param barcode 商品条码
     * @return 商品信息
     */
    @GetMapping("/info")
    public R<List<ProductVo>> getProductByBarcode(@RequestParam String barcode) {
        return R.ok(zhishuShopGoodsService.getProductByBarcode(barcode));
    }

    /**
     * 提交商品信息
     *
     * @param form 商品信息表单
     * @return 无
     */
    @PostMapping("/submit")
    @SaIgnore
    @RepeatSubmit
    public R<ProductSubmitResultVo> submitProduct(@RequestBody ProductForm form) {
        ProductSubmitResultVo result = zhishuShopGoodsService.submitProduct(form);
        return R.ok(result);
    }


    /**
     * 版权页上传
     *
     * @param form
     * @return
     */
    @PostMapping("/submitFromCopyrightPage")
    @SaIgnore
    @RepeatSubmit
    public R<ProductSubmitResultVo> submitFromCopyrightPage(@RequestBody ProductForm form) {
        return R.ok(zhishuShopGoodsService.submitFromCopyrightPage(form));
    }

    /**
     * 重复书籍
     *
     * @param form
     * @return
     */
    @PostMapping("/repeatBook")
    @SaIgnore
    @RepeatSubmit
    public R<ProductForm> repeatBook(@RequestBody ProductForm form) {
        return R.ok(zhishuShopGoodsService.repeatBook(form));
    }

    /**
     * isbn比价
     */
    @GetMapping("/kongfz/search")
    @SaIgnore
    @RepeatSubmit
    public R<List<KongfzVo>> searchBooks(@RequestParam("keyword") String keyword,  // 同时支持ISBN/书名
                                         @RequestParam(value = "searchType", defaultValue = "category") String searchType,
                                         @RequestParam("sortType") String sortType,
                                         @RequestParam("conditionValue") String conditionValue,
                                         @RequestParam("cookies") String cookies,
                                         @RequestParam(value = "publisher", required = false) String publisher,    // 设置为非必需
                                         @RequestParam(value = "author", required = false) String author) { // 设置为非必需
        List<KongfzVo> products = zhishuShopGoodsService.getProductByKongfz(keyword, searchType, sortType, conditionValue, cookies, publisher, author);
        return R.ok(products);
    }

    /**
     * 根据书名获取作者和出版社信息
     */
    @GetMapping("/getAuthorAndPublisher")
    @SaIgnore
    public R<List<AuthorPressVo>> getAuthorAndPublisher(@RequestParam("keyword") String keyword, @RequestParam("cookies") String cookies) {
        List<AuthorPressVo> products = zhishuShopGoodsService.getAuthorAndPublisher(keyword, cookies);
        return R.ok(products);
    }

    /**
     * python获取商品信息
     */
    @PostMapping("/python/{isbn}")
    @SaIgnore
    @RepeatSubmit
    public R<ProductVo> pythonGetProductByBarcode(@RequestParam String isbn) {
        ProductVo productVo = zhishuShopGoodsService.queryBookByPython(isbn);
        return R.ok(productVo);
    }

    /**
     * xcx上书记录
     *
     * @param
     * @return
     */
    @GetMapping("/xcx/{phoneNumber}")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @SaIgnore
    public R<TableDataInfo<ZhishuShopGoodsVo>> edit(
            @PathVariable String phoneNumber,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String date) {
        TableDataInfo<ZhishuShopGoodsVo> page = zhishuShopGoodsService.selectShopGoodsByPhoneNumber(phoneNumber, pageNum, pageSize, date);
        return R.ok(page);
    }

    /**
     * 查询获取对应商品数据
     */
    @GetMapping("/getGoodsData")
    @SaIgnore
    public R<TableDataInfo<ZhishuShopGoodsVo>> getGoodsData(@RequestParam String code,
                                                            @RequestParam Long userId,
                                                            @RequestParam(defaultValue = "1") int pageNum,
                                                            @RequestParam(defaultValue = "10") int pageSize,
                                                            @RequestParam(required = false) String date) {
        TableDataInfo<ZhishuShopGoodsVo> page = zhishuShopGoodsService.queryGoodListByArtNo(code, userId, pageNum, pageSize, date);
        return R.ok(page);
    }

    /**
     * 修改xcx货号
     */
    @PostMapping("/batchMoveItems")
    @SaIgnore
    public R<String> batchMoveItems(@RequestParam(value = "itemIds") List<String> itemIds,
                                    @RequestParam("warehouse") String warehouse,
                                    @RequestParam("shelf") String shelf,
                                    @RequestParam("freight") String freight,
                                    @RequestParam(value = "userId") Long userId) {
        try {
            String result = zhishuShopGoodsService.batchMoveItems(itemIds, warehouse,shelf, freight, userId);
            return R.ok(result);
        } catch (Exception e) {
            log.error("批量移动商品位置异常", e);
            return R.fail("操作失败：" + e.getMessage());
        }
    }

    /**
     * 新增商品信息
     */
    @SaCheckPermission("zhishu:shopGoods:add")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ZhishuShopGoodsBo bo) {
        return toAjax(zhishuShopGoodsService.insertByBo(bo));
    }

    /**
     * 修改商品信息
     */
    @SaCheckPermission("zhishu:shopGoods:edit")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ZhishuShopGoodsBo bo) {
//        获取当前用户id
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        return toAjax(zhishuShopGoodsService.updateByBo(bo));
    }

    /**
     * 删除商品信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zhishu:shopGoods:remove")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids, Boolean isProSynch) {
        return toAjax(zhishuShopGoodsService.deleteWithValidByIds(List.of(ids), isProSynch));
    }

    /**
     * 上传图片
     */
    @PostMapping("/uploadImages")
    @SaIgnore
    public Map uploadImg(@RequestParam("file") MultipartFile file) {
        return zhishuShopGoodsService.uploadImg(file);
        // 获取token
    }

    /**
     * 上传图片
     */
    @GetMapping("/SynShopImg")
    @SaIgnore
    public R synShopImg(@RequestParam("userId") Long userId) {
        zhishuShopGoodsService.synShopImg(userId);
        return R.ok();
    }
    /**
     * 同步pdd图片
     */
    @GetMapping("/synPddShopImg")
    @SaIgnore
    public R synPddShopImg(@RequestParam("userId") Long userId) {
        zhishuShopGoodsService.synPddShopImg(userId);
        return R.ok();
    }

    /**
     * 导入商品信息
     */
    @PostMapping("/importExcel")
    public R<Void> importExcel(@RequestParam("file") MultipartFile file,
                               @RequestParam("depotId") Long depotId,
                               @RequestParam("firstDepotId") Long firstDepotId,
                               @RequestParam("secondDepotId") Long secondDepotId,
                               @RequestParam("code") String code) {
        ExcelResult<GoodsExcel> list = null;
        try (InputStream inputStream = file.getInputStream()) {
            // 商品信息列表
            list = ExcelUtil.importExcel(inputStream, GoodsExcel.class, true);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String Filename = file.getOriginalFilename();

        TFreightVo tFreightVo = freightService.queryById(depotId);
        String allowDistribution = "0";
        if (tFreightVo == null){
            return R.fail("三级货架不存在");
        }else{
            allowDistribution = tFreightVo.getAllowDistribution();
        }

        // 添加到数据库
        List<ZhishuShopGoodsBo> shopGoodsBoList = new ArrayList<>();
        for (GoodsExcel goodsExcel : list.getList()) {
            System.out.println(JsonUtil.transferToJson(goodsExcel));
            ZhishuShopGoodsBo zhishuShopGoodsBo = new ZhishuShopGoodsBo();
            // 赋值..
//            zhishuShopGoodsBo.setId(UUID.randomUUID().toString());
//            zhishuShopGoodsBo.setItemNumber(goodsExcel.getGoodsNo());
            zhishuShopGoodsBo.setUserId(LoginHelper.getUserId());
            zhishuShopGoodsBo.setGoodsName(goodsExcel.getGoodsName());
            zhishuShopGoodsBo.setArtNo(goodsExcel.getArtNo());
            zhishuShopGoodsBo.setIsbn(goodsExcel.getIsbn());
            zhishuShopGoodsBo.setConditionCode(String.valueOf(goodsExcel.getConditionCode()));
            zhishuShopGoodsBo.setPrice(goodsExcel.getPrice());
            zhishuShopGoodsBo.setInventory(goodsExcel.getInventory());
//            zhishuShopGoodsBo.setFixPrice(goodsExcel.getFixPrice());
//            zhishuShopGoodsBo.setProductId(goodsExcel.getGoodsNo());
//            zhishuShopGoodsBo.setIsArtNoConversion(goodsExcel.getIsArtNoConversion());
            zhishuShopGoodsBo.setDepotId(firstDepotId);
            zhishuShopGoodsBo.setIsJoinDistribution(Integer.parseInt(allowDistribution));
            shopGoodsBoList.add(zhishuShopGoodsBo);
        }
        // 批量导入数据库
        Boolean b = zhishuShopGoodsService.insertListGoodsInfo(shopGoodsBoList, firstDepotId, secondDepotId, depotId, Filename, code,null,"7");

        return toAjax(b);
    }

    @PostMapping("/importApi")
    @SaIgnore
    public R<Void> importApi(Long userId,String goodsName,String artNo,String isbn,String conditionCode,Long price,Long inventory,
                         Long depotId,String code){
        TFreightVo tFreightVo = freightService.queryById(depotId);
        String allowDistribution = "0";
        if (tFreightVo == null){
            return R.fail("三级货架不存在");
        }else{
            allowDistribution = tFreightVo.getAllowDistribution();
        }

        TShelvesVo shelvesVo = shelvesService.queryById(tFreightVo.getShelvesId());
        TDepotVo depotVo = depotService.queryById(Long.parseLong(shelvesVo.getDepotId()));
        Long firstDepotId = depotVo.getId();
        Long secondDepotId = shelvesVo.getId();


        List<ZhishuShopGoodsBo> shopGoodsBoList = new ArrayList<>();
        ZhishuShopGoodsBo zhishuShopGoodsBo = new ZhishuShopGoodsBo();
        zhishuShopGoodsBo.setUserId(userId);
        zhishuShopGoodsBo.setGoodsName(goodsName);
        zhishuShopGoodsBo.setArtNo(artNo);
        zhishuShopGoodsBo.setIsbn(isbn);
        zhishuShopGoodsBo.setConditionCode(conditionCode);
        zhishuShopGoodsBo.setPrice(price);
        zhishuShopGoodsBo.setInventory(inventory);
        zhishuShopGoodsBo.setDepotId(firstDepotId);
        zhishuShopGoodsBo.setIsJoinDistribution(Integer.parseInt(allowDistribution));
        shopGoodsBoList.add(zhishuShopGoodsBo);
        // 获取当前时间秒级时间戳
        Long timestamp = System.currentTimeMillis() / 1000;
        // 批量导入数据库
        Boolean b = zhishuShopGoodsService.insertListGoodsInfo(shopGoodsBoList, firstDepotId, secondDepotId, depotId, "接口调用-"+timestamp, code,userId,"6");
        return toAjax(b);
    }

    @SaCheckPermission("zhishu:shopGoods:goodsAdd")
    @PostMapping("/goodsAdd")
    public R<Void> goodsAdd(@RequestBody Map map, HttpServletRequest request) {
        Map<String, String> headers = PddResultUtil.getPddHeaderMap(request);
        map.put("userId", LoginHelper.getUserId());
        // 调用本地服务
        map.putAll(headers);
        zhishuShopGoodsService.goodsAdd(map);
        return toAjax(1);
    }

    /**
     * 初始化库存
     */
    @GetMapping("/batchInitInventoryToRedis")
    @SaIgnore
    public Boolean batchInitInventoryToRedis() {
        zhishuShopGoodsService.batchInitInventoryToRedis();
        return true;
    }

    /**
     * 查询库存
     */
    @GetMapping("/queryInventory")
    @SaIgnore
    public R<Integer> queryInventory(@NotNull(message = "商品Id不能为空") Long shopGoodsId) {
        Integer inventory = zhishuShopGoodsService.queryInventory(shopGoodsId);
        return R.ok(inventory);
    }


    /**
     * 操作库存
     */
    @PostMapping("/operatingInventory")
    @SaIgnore
    public Boolean operatingInventory(@RequestBody OperatingInventoryVo operatingInventoryVo) {
        System.out.println("接收到操作库存请求：" + JSONObject.toJSONString(operatingInventoryVo));
        // 根据平台类型和平台店铺Id查询出店铺Id
        ShopVo shopVo;
        if(operatingInventoryVo.getShopType() == 5){
            //如果是闲鱼店铺，则mallId存的是店铺id
            shopVo = shopService.queryById(operatingInventoryVo.getMallId());
        }else{
            shopVo = shopService.queryByMailId(operatingInventoryVo.getMallId(), operatingInventoryVo.getShopType());
        }
        Assert.isTrue(ObjectUtil.isNotNull(shopVo), "店铺不存在");
        for (OperatingInventoryVo.GoodsItem goodsItem : operatingInventoryVo.getGoodsItems()) {
            // 根据店铺Id和商品平台Id查询出商品Id
            ShopGoodsPublishedVo shopGoodsPublishedVo = shopGoodsPublishedService.queryByPlatformId(shopVo.getId().toString(), goodsItem.getPlatformId());
            // 根据商品Id进行库存操作
            Assert.isTrue(ObjectUtil.isNotNull(shopGoodsPublishedVo), "商品不存在");
            Boolean result = zhishuShopGoodsService.operatingGoodsInventory(shopVo.getId(), operatingInventoryVo.getShopType(), operatingInventoryVo.getOperationType(), shopGoodsPublishedVo, goodsItem.getCount(), operatingInventoryVo.getOrderSn());
            if (!result) {
                log.error("库存操作失败：操作类型-{}，商品Id-{}，数量-{}", operatingInventoryVo.getOperationType(), shopGoodsPublishedVo.getShopGoodsId(), goodsItem.getCount());
            }
        }
        return true;
    }


    /**
     * 操作库存
     */
    @PostMapping("/goofishoperatingInventory")
    @SaIgnore
    public Boolean goofishoperatingInventory(@RequestBody OperatingInventoryVo operatingInventoryVo) {
        System.out.println("接收到操作库存请求：" + JSONObject.toJSONString(operatingInventoryVo));
        // 根据平台类型和平台店铺Id查询出店铺Id
        ShopVo shopVo = shopService.queryByMailId(operatingInventoryVo.getMallId(), operatingInventoryVo.getShopType());
        Assert.isTrue(ObjectUtil.isNotNull(shopVo), "店铺不存在");
        for (OperatingInventoryVo.GoodsItem goodsItem : operatingInventoryVo.getGoodsItems()) {
            ZhishuShopGoodsVo zhishuShopGoodsVo =  zhishuShopGoodsService.selectShopGoodsByArtNo(goodsItem.getPlatformId());
            // 根据店铺Id和商品平台Id查询出商品Id

            // 根据商品Id进行库存操作
            Assert.isTrue(ObjectUtil.isNotNull(zhishuShopGoodsVo), "商品不存在");
            Boolean result = zhishuShopGoodsService.goofishoperatingGoodsInventory(shopVo.getId(), operatingInventoryVo.getShopType(), operatingInventoryVo.getOperationType(), zhishuShopGoodsVo, goodsItem.getCount(), operatingInventoryVo.getOrderSn());
            if (!result) {
                log.error("库存操作失败：操作类型-{}，商品Id-{}，数量-{}", operatingInventoryVo.getOperationType(), zhishuShopGoodsVo.getId(), goodsItem.getCount());
            }
        }
        return true;
    }




    /**
     * 拉取孔夫子/万里牛商品
     *
     * @param shopId
     * @return
     */
    @SaIgnore
    @GetMapping("/synchronizationGoods")
    public R<Void> synchronizationGoods(@NotNull(message = "店铺Id不能为空") @RequestParam("shopId") Long shopId, Integer shopType) {
        if (ObjectUtil.isNull(shopType)) {
            ShopVo shopVo = shopService.queryById(shopId);
            shopType = Integer.valueOf(shopVo.getShopType());
        }
        try {
            Objects.requireNonNull(ShopGoodsFactory.getStrategy(shopType)).synchronizationGoods(shopId);
            return R.ok("拉取成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 比对存入表格
     */
    @SaIgnore
    @PostMapping("/goodsComparison")
    public Boolean goodsComparison(@RequestBody GoodsComparisonRequest request) {
        zhishuShopGoodsService.goodsComparison(request);
        return true;
    }

    /**
     * 分批比对商品
     */
    @SaIgnore
    @DeleteMapping("/deleteTaskDataByShopId")
    public Boolean deleteTaskDataByShopId(@RequestParam("shopId") Long shopId) {
        zhishuShopGoodsService.deleteTaskDataByShopId(shopId);
        return true;
    }
    /**
     * 拉取孔网数据到erp商品表
     */
    @SaIgnore
    @PostMapping("/batchGoodsComparison")
    public Boolean batchGoodsComparison(@RequestBody BatchGoodsRequest request) {
        System.out.println("接收到批量比对请求：" + JSONObject.toJSONString(request)+"zhuxiaodong");
        zhishuShopGoodsService.createShopGoodsList(request);
        // zhishuShopGoodsService.batchGoodsComparison(request);
        return true;
    }

    /**
     * 根据用户选择货号规则将商品存入数据库
     */
    @SaIgnore
    @PostMapping("/saveShopGoodsInDb")
    public R<Void> saveShopGoodsInDb(@Validated @RequestBody SaveGoodsVo saveGoodsVo) {
        try {
            zhishuShopGoodsService.saveShopGoodsInDb(saveGoodsVo);
            return R.ok("保存成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    /**
     * 随机修改孔夫子货号（仅测试使用）
     */
    @SaIgnore
    @GetMapping("/randomUpdateArtNo")
    public R<Void> randomUpdateArtNo(Long userId, Long shopId) {
        try {
            zhishuShopGoodsService.randomUpdateArtNo(userId, shopId);
            return R.ok("修改");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    // /**
    //  * 导入Excel恢复孔夫子货号（回滚备用）
    //  */
    // @SaIgnore
    // @PostMapping("/rollbackUpdateArtNo")
    // public R<Void> rollbackUpdateArtNo(Long userId,Long shopId) {
    //     try {
    //         zhishuShopGoodsService.randomUpdateArtNo(userId,shopId);
    //         return R.ok("修改");
    //     } catch (Exception e) {
    //         return R.fail(e.getMessage());
    //     }
    // }

    /**
     * 获取商品变更库存数据
     *
     * @param id 主键
     */
    @GetMapping("/stockLog/{id}")
    public R<List<StockChangeLogVo>> getStockLog(@PathVariable String id) {
        List<StockChangeLogVo> list = zhishuShopGoodsService.selectShopStockLog(id);
        return R.ok(list);
    }

    // 通过传入的货号，查询出对应的仓库id,返回仓库id和货架id和货位id
    @GetMapping("/getDepotIds")
    @SaIgnore
    public R<Map> getDepotIds(String artNo, String userId) {
        Map map = zhishuShopGoodsService.selectDepotIds(userId, artNo);
        return R.ok(map);
    }

    @PostMapping("/editShopGoodsPrice")
    @SaIgnore
    public void editShopGoodsPrice(@RequestBody Map map) {
        String artNo = map.get("artNo").toString();
        String price = map.get("price").toString();

        ZhishuShopGoodsVo vo = zhishuShopGoodsService.selectShopGoodsByArtNo(artNo);

        ZhishuShopGoodsBo bo = new ZhishuShopGoodsBo();
        bo.setId(vo.getId());
        bo.setPrice(Long.parseLong(price));
        zhishuShopGoodsService.updateByBo(bo);
    }

    @GetMapping("/getShopGoodsByArtNo")
    @SaIgnore
    public Map getShopGoodsByArtNo(String artNo){
        Map map = new HashMap();
        ZhishuShopGoodsVo vo = zhishuShopGoodsService.selectShopGoodsByArtNo(artNo);
        if(vo != null){
            map.put("code",200);
            map.put("msg","查询成功");
            map.put("data",vo);
        }else{
            map.put("code",500);
            map.put("msg","未查询到商品数据");
        }
        return map;
    }

    /**
     * 通过平台订单Id查询库存操作日志
     */
    @GetMapping("/queryStockChangeLogByOrderSn")
    @SaIgnore
    public R<StockChangeLog> queryStockChangeLogByOrderSn(@NotNull(message = "平台订单编码不能为空") String orderSn, @NotNull(message = "库存操作日志类型不能为空") Integer type) {
        StockChangeLog stockChangeLogVo = zhishuShopGoodsService.queryStockChangeLogByOrderSn(orderSn, type);
        return R.ok(stockChangeLogVo);
    }

    /**
     * 操作下架商品
     */
    @PostMapping("/operatingSoldOut")
    @SaIgnore
    public Boolean operatingSoldOut(@RequestBody OperatingSoldOutRequest request) {
        System.out.println("接收到操作下架商品请求：" + JSONObject.toJSONString(request));
        // 根据平台类型和平台店铺Id查询出店铺Id
        ShopVo shopVo = shopService.queryByMailId(request.getMallId(), request.getPlatformType());
        Assert.isTrue(ObjectUtil.isNotNull(shopVo), "店铺不存在");
        for (OperatingInventoryVo.GoodsItem goodsItem : request.getGoodsItems()) {
            // 根据店铺Id和商品平台Id查询出商品Id
            ShopGoodsPublishedVo shopGoodsPublishedVo = shopGoodsPublishedService.queryByPlatformId(shopVo.getId().toString(), goodsItem.getPlatformId());
            // 根据商品Id进行下架操作
            Assert.isTrue(ObjectUtil.isNotNull(shopGoodsPublishedVo), "商品不存在");
            Boolean result = zhishuShopGoodsService.operatingGoodsSoldOut(shopVo.getId(), request.getPlatformType(), request.getLogType(), request.getOperationType(), shopGoodsPublishedVo, request.getOrderSn());
            if (!result) {
                log.error("下架操作失败：操作类型-{}，商品Id-{}，数量-{}", request.getOperationType(), shopGoodsPublishedVo.getShopGoodsId(), goodsItem.getCount());
            }
        }
        return true;
    }

    /**
     * 通过userId查询对应用户商品表数据条数
     */
    @GetMapping("/queryGoodsCountByUserId")
    @SaIgnore
    public R<Long> queryGoodsCountByUserId(@NotNull(message = "用户ID不能为空") Long userId) {
        Long count = zhishuShopGoodsService.queryGoodsCountByUserId(userId);
        return R.ok(count);
    }

    /**
     * 通过userId查询对应用户
     */
    @GetMapping("/queryUserIdByUserId")
    @SaIgnore
    public R<SysUser> queryUserIdByShopId(@NotNull(message = "店铺ID不能为空") Long userId) {
        SysUser user = zhishuShopGoodsService.queryUserByUserId(userId);
        return R.ok(user);
    }

    /**
     * 批量修改货区
     */
    @SaIgnore
    @PutMapping("/batchUpdateAre")
    public R<Void> editBatchAre(@RequestBody BatchUpdateCargoBo bo) {
        // 获取当前用户id
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        return toAjax(zhishuShopGoodsService.batchUpdateCargo(bo));
    }

    /**
     * 同步至自营书品
     */
    @SaIgnore
    @GetMapping("/syncRunningTaskToShopGoods")
    public R<Void> syncRunningTaskToShopGoods(@NotNull(message = "店铺ID不能为空") String shopId,
                                              @RequestParam("freightId") String freightId,
                                              @RequestParam("id") String id) {
        Long userId = LoginHelper.getUserId();
        ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
        // 判断是2-孔网店铺还是1-拼多多店铺
        TaskBo taskBo = new TaskBo();
        // 存储任务信息
        taskBo.setTaskType("SYNC_MY_GOODS");
        taskBo.setRelationId(Long.valueOf(id));
        taskBo.setFileName("同步至自营书品");
        taskBo.setShopIds(shopId);
        taskBo.setShopNames(shopVo.getShopName());
        taskBo.setDataNum(0L);
        taskBo.setTaskStatus("0");
        taskService.insertByBo(taskBo);
        // 获取当前用户id
        CompletableFuture.runAsync(() -> {
            try {
                zhishuShopGoodsService.syncRunningTaskToShopGoods(Long.valueOf(shopId), Long.valueOf(freightId),userId,taskBo);
            }catch (Exception e) {
                log.error("同步至自营书品失败", e);
            }
        });
        return R.ok("创建同步任务成功,请前往任务列表查看任务进度");
    }

    @PostMapping("/synchronousTask")
    @SaIgnore
    public R<Void> synchronousTask(String shopId){
        ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
        // 拼多多同步任务
        if (shopVo.getShopType().equals("1")){
            TaskBo taskBo = new TaskBo();
            taskBo.setTaskType("SYNC_MY_GOODS");
            taskBo.setFileName("同步任务");
            taskBo.setShopIds(shopId);
            taskBo.setShopNames(shopVo.getShopName());
            taskBo.setDataNum(0L);
            taskBo.setTaskStatus("0");
            taskBo.setCreateBy(shopVo.getCreateBy());
            taskService.insertByBo(taskBo);

            // 获取当前用户id
            CompletableFuture.runAsync(() -> {
                try {
                    zhishuShopGoodsService.synchronousTask(shopVo,taskBo);
                }catch (Exception e) {
                    log.error("同步至自营书品失败", e);
                }
            });
        }

        return R.ok("创建同步任务成功,请前往任务列表查看任务进度");
    }

    /**
     * 批量修改店铺商品下架/改价
     *
     * @return
     */
    @SaIgnore
    @PostMapping("/updateShopGoodsPrice")
    public R<Boolean> updateShopGoodsPrice(@Validated @RequestBody UpdateShopGoodsPriceRequest request) {
        // 查询店铺类型
        ShopVo shopVo = shopService.queryById(request.getShopId());
        Integer shopType = Integer.valueOf(shopVo.getShopType());
        Long mallId = shopVo.getMallId();
        String token = shopVo.getToken();

        if (ObjectUtil.isNull(mallId) || ObjectUtil.isEmpty(token)) {
            return R.fail("当前店铺未授权或授权过期");
        }
        // 根据店铺类型选择不同策略
        ShopGoodsStrategy strategy = Objects.requireNonNull(ShopGoodsFactory.getStrategy(shopType));
        if (ObjectUtil.isNull(strategy)) {
            return R.fail("获取策略失败错误", false);
        }
        Boolean result;
        // 根据操作类型：0-下架 1.改价 做不同操作
        switch (request.getType()) {
            case 0:
                // 0-下架
                result = strategy.setShopGoodsOnSaleStatus(mallId, token, 0, request.getItems());
                break;
            case 1:
                // 1.改价
                result = strategy.updateShopGoodsPrice(mallId, token, request.getItems());
                break;
            default:
                return R.fail("操作类型错误", false);
        }
        return R.ok(result);
    }

    @SaIgnore
    @PostMapping("/updategoodszxd")
    public void updategoodszxd(String shopId, String platformId) {
        System.out.println("shopId："+shopId);
        System.out.println("platformId："+platformId);
        ShopVo shop= shopService.queryById(Long.parseLong(shopId));
        // 再去从库查询skuId 根据店铺Id和商品id
        List<SuccessDataItemDto> successDataItemDtos = iRunningTaskByShopService.selectByGoodsId("t_running_task_" + shop.getId(), platformId);
        Map allData = new HashMap();
        allData.put("shopId", shop.getId());
        allData.put("mallId", successDataItemDtos.get(0).getSkuId());
        allData.put("token", shop.getToken());
        allData.put("goodsId", platformId);
        allData.put("quantity", 0);

        String pddIp = configService.selectConfigByKey("fuwubpdd.ip");
        InterfaceUtils.getInterfacePost(pddIp, "/api/pdd/inventory/inventorySync", allData);
    }

    @SaIgnore
    @PostMapping("/insertGoodsDetails")
    public void insertGoodsDetails(@Validated @RequestBody ZhishuShopGoodsDetailBo bo) {
        zhishuShopGoodsDetailService.insertByBo(bo);
    }
}
