package com.yami.shop.service.hb.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yami.shop.bean.dto.hb.HBBaseReq;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.util.hb.HBR;
import com.yami.shop.dao.*;
import com.yami.shop.service.hb.IHBGoodsService;
import com.yami.shop.service.impl.FrontCategoryService;
import com.yami.shop.utils.HBSignUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.yami.shop.common.util.HttpUtil.post;


/**
 * 商品信息管理实现
 *
 * @author fubojin
 * @version 1.0.0
 * @since 2025-09-5
 */
@Slf4j
@Service
@AllArgsConstructor
public class HBGoodsService implements IHBGoodsService {
    private final HBSignUtil hbSignUtil;
    private final ProductMapper productMapper;
    private final SkuMapper skuMapper;
    private final ShopSkuMapper shopSkuMapper;
    private final ShopDetailMapper shopDetailMapper;

    private final FrontCategoryMapper frontCategoryMapper;
    private final ShopCategoryMapper shopCategoryMapper;
    private final CategoryProdHbMapper categoryProdHbMapper;
    private final CategoryProdMapper categoryProdMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HBR addHBGoods(JSONObject hbRequest) {
        String bodyStr = hbRequest.getString("body");
        log.info("商品信息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        JSONArray productList = bodyJson.getJSONArray("productList");

        for (Object product : productList) {
            JSONObject jsonObject = JSON.parseObject(product.toString());
            Long prodId;
            String hbSpuId;
            //判断海博传过来的是单规格还是多规格
            if (ObjectUtil.isEmpty(jsonObject.getString("multiSpec"))) {
                log.info("===================进入普通商品操作===================");
                String goodsInfoStr = selectHBGoodsInfo(jsonObject.getString("outSkuId"));
                JSONObject goodsInfoJson = JSON.parseObject(goodsInfoStr);
                // 2. 逐层解析获取productHostInfoDTOS数组
                JSONObject result = goodsInfoJson.getJSONObject("result");
                JSONObject innerResult = result.getJSONObject("result");
                JSONArray productHostInfoDTOS = innerResult.getJSONArray("productHostInfoDTOS");

                // 3. 遍历获取每个商品信息
                for (int i = 0; i < productHostInfoDTOS.size(); i++) {
                    JSONObject productInfo = productHostInfoDTOS.getJSONObject(i);

                    // 创建并填充Product对象
                    hbSpuId = productInfo.getString("spuId");
                    Product productAdd = createProductFromProductInfo(productInfo);
                    setSpuMapper(productInfo, productAdd);
                    Product productInfoById = productMapper.selectByHbSpuId(hbSpuId);

                    if (ObjectUtil.isNotEmpty(productInfoById)) {
                        prodId = productInfoById.getProdId();
                        log.info("商品spuID={},spuName={}已经存在，修改商品", productInfo.getLong("spuId"), productInfo.getString("spuName"));
                        productAdd.setProdId(productInfoById.getProdId());
                        productMapper.updateById(productAdd);
                    } else {
                        //添加到数据库
                        log.info("创建商品spu: {}", productAdd);
                        productMapper.insert(productAdd);
                        prodId = productAdd.getProdId();
                        log.info("SPU创建成功: prodId={}, hbSpuId={}, spuName={}", productAdd.getProdId(), productAdd.getProdId(), productAdd.getProdName());
                    }

                    try {
                        String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncProductData";
                        String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, productAdd);
                        log.info("推送商品到同步服务器结果: {}", response);
                    } catch (Exception e) {
                        log.error("推送商品到同步服务器失败: {}", e.getMessage(), e);
                    }

                    convertCategoryCodeToId(productInfo.getJSONArray("relationFrontCategories"), productAdd.getProdId()); // 一品多类目


                    Sku skuId = skuMapper.selectByHbSkuId(productInfo.getString("skuId"));
                    // 创建并填充Sku对象
                    Sku sku = createSkuFromProductInfo(productInfo);
                    sku.setProdId(prodId);
                    sku.setHbSpuId(hbSpuId);
                    sku.setProdName(productAdd.getProdName());
                    if (ObjectUtil.isNotEmpty(skuId) && skuId.getIsDelete() == 0) {
                        sku.setSkuId(skuId.getSkuId());
                        skuMapper.updateById(sku);
                        log.info("商品skuId={},skuName={}已经存在，修改数据", productInfo.getString("skuId"), productInfo.getString("skuName"));
                    } else {
                        skuMapper.insert(sku);
                        log.info("SKU创建成功: skuId={}, skuName={}", sku.getSkuId(), sku.getSkuName());
                    }

                    try {
                        String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncSkuData";
                        // 将frontCategory对象作为JSON放入请求体
                        String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, sku);
                        log.info("推送frontCategory到同步服务器结果: {}", response);
                    } catch (Exception e) {
                        log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                    }
                }
            } else {
                log.info("===================进入多规格商品操作===================");
                hbSpuId = jsonObject.getString("spuId");
                String selectHBGoodsSpuInfo = selectHBGoodsSpuInfo(hbSpuId);
                JSONObject goodsInfoJson = JSON.parseObject(selectHBGoodsSpuInfo);
                // 2. 逐层解析获取productHostInfoDTOS数组
                JSONObject result = goodsInfoJson.getJSONObject("result");
                JSONObject innerResult = result.getJSONObject("result");
                JSONArray productHostInfoDTOS = innerResult.getJSONArray("productSpuHostInfoDTOList");

                for (Object productHostInfoDTO : productHostInfoDTOS) {
                    JSONObject productInfo = JSON.parseObject(productHostInfoDTO.toString());
                    // 创建并填充Product对象
                    Product productAdd = createProductFromProductInfo(productInfo);
                    setSpuSpecMapper(productInfo, productAdd);
                    // 创建并填充Product对象
                    Product productInfoById = productMapper.selectByHbSpuId(hbSpuId);
                    if (ObjectUtil.isNotEmpty(productInfoById) && productInfoById.getIsDelete() == 0) {
                        prodId = productInfoById.getProdId();
                        log.info("商品spuID={},spuName={}已经存在，修改商品", productInfo.getLong("spuId"), productInfo.getString("spuName"));
                        productAdd.setProdId(productInfoById.getProdId());
                        productMapper.updateById(productAdd);
                    } else {
                        //添加到数据库
                        productMapper.insert(productAdd);
                        prodId = productAdd.getProdId();
                        log.info("生成的商品ID: {}", productAdd.getProdId());
                    }
                    try {
                        String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncProductData";
                        // 将frontCategory对象作为JSON放入请求体
                        String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, productAdd);
                        log.info("推送frontCategory到同步服务器结果: {}", response);
                    } catch (Exception e) {
                        log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                    }

                    convertCategoryCodeToId(productInfo.getJSONArray("relationFrontCategories"), productAdd.getProdId()); // 一品多类目

                    JSONArray skuList = productInfo.getJSONArray("skuList");
                    for (Object o : skuList) {
                        JSONObject jsonObjectSku = JSON.parseObject(o.toString());
                        Sku sku = createSkuFromProductInfo(jsonObjectSku);
                        sku.setProdId(prodId);
                        sku.setHbSpuId(hbSpuId);
                        sku.setProdName(productAdd.getProdName());
                        Sku skuId = skuMapper.selectByHbSkuId(jsonObjectSku.getString("skuId"));
                        if (ObjectUtil.isNotEmpty(skuId) && skuId.getIsDelete() == 0) {
                            sku.setSkuId(skuId.getSkuId());
                            skuMapper.updateById(sku);
                            log.info("商品skuId={},skuName={}已经存在无需添加，修改", productInfo.getLong("skuId"), productInfo.getString("skuName"));
                        } else {
                            skuMapper.insert(sku);
                        }
                        try {
                            String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncSkuData";
                            String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, sku);
                            log.info("推送商品到同步服务器结果: {}", response);
                        } catch (Exception e) {
                            log.error("推送商品到同步服务器失败: {}", e.getMessage(), e);
                        }
                    }
                }
            }
        }
        return HBR.success();
    }


    @Override
    public HBR updateGoodsStatus(JSONObject hbRequest) {
        try {
            JSONObject bodyStr = hbRequest.getJSONObject("body");
            log.info("商品可售状态，body：{}", bodyStr);

            JSONArray data = bodyStr.getJSONArray("data");// 使用Fastjson的解析方法
            String selfSkuStatus = getSelfSkuStatus(data);
            JSONObject skuInfo = JSON.parseObject(selfSkuStatus);
            JSONArray jsonArray = skuInfo.getJSONObject("result").getJSONObject("result").getJSONArray("stationProductList");
            for (Object datum : jsonArray) {
                JSONObject jsonObject = JSON.parseObject(datum.toString());
                String skuId = jsonObject.getString("skuId");
                String stationId = jsonObject.getString("stationId");
                Integer saleStatus = jsonObject.getInteger("saleStatus");//1 可售，0不可售

                log.info("商品状态变更查询：{}", selfSkuStatus);

                //处理商品状态
                ShopDetail shopDetail = shopDetailMapper.selectOne(new LambdaUpdateWrapper<ShopDetail>()
                        .eq(ShopDetail::getHbStationId, stationId));
                Sku sku = skuMapper.selectByHbSkuId(skuId);
                shopSkuMapper.update(new ShopSku(), new LambdaUpdateWrapper<ShopSku>()
                        .set(ShopSku::getSaleStatus, saleStatus)
                        .eq(ShopSku::getSkuId, sku.getSkuId())
                        .eq(ShopSku::getShopId, shopDetail.getShopId()));

                try {
                    ShopSku shopSku = shopSkuMapper.selectOne(new LambdaUpdateWrapper<ShopSku>()
                            .eq(ShopSku::getSkuId, sku.getSkuId())
                            .eq(ShopSku::getShopId, shopDetail.getShopId()));
                    String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncShopSkuData";
                    String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopSku);
                    log.info("推送商品到同步服务器结果: {}", response);
                } catch (Exception e) {
                    log.error("推送商品到同步服务器失败: {}", e.getMessage(), e);
                }

                //处理门店-分类管理
                List<CategoryProdHb> categoryProds = categoryProdHbMapper.selectList(new LambdaQueryWrapper<CategoryProdHb>()
                        .eq(CategoryProdHb::getProdId, sku.getProdId())
                        .eq(CategoryProdHb::getIsDelete, 0));
                for (CategoryProdHb categoryProd : categoryProds) {
                    FrontCategory frontCategory = frontCategoryMapper.selectOne(new LambdaQueryWrapper<FrontCategory>()
                            .eq(FrontCategory::getCode, categoryProd.getCode()));
                    addShopCategory(frontCategory, categoryProd.getProdId(), shopDetail.getShopId(), shopDetail.getHbStationId());
                }


            }
        } catch (Exception e) {
            log.error("商品失败：{}", e.getMessage(), e);
            return HBR.error("未知异常");

        }
        return HBR.success();
    }

    /**
     * 添加门店分类
     *
     * @param frontCategory 前台分类
     * @param shopId        门店id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void addShopCategory(FrontCategory frontCategory, Long prodId, Long shopId, String hbShopId) {
        log.info("添加门店分类：{}", frontCategory);
        ShopCategory shopCategoryByCode = shopCategoryMapper.selectOne(new LambdaQueryWrapper<ShopCategory>()
                .eq(ShopCategory::getCode, frontCategory.getCode())
                .eq(ShopCategory::getShopId, shopId)
                .eq(ShopCategory::getIsDelete, 0));

        if (shopCategoryByCode == null) {
            ShopCategory shopCategory = new ShopCategory();
            shopCategory.setCode(frontCategory.getCode());
            shopCategory.setName(frontCategory.getName());
            if (frontCategory.getParentCode() == null || frontCategory.getParentCode().equals("0")) {
                shopCategory.setPid(0L);
                shopCategory.setParentCode("0");
            } else {
                ShopCategory shopCategoryByCode1 = shopCategoryMapper.selectOne(new LambdaQueryWrapper<ShopCategory>()
                        .eq(ShopCategory::getCode, frontCategory.getParentCode())
                        .eq(ShopCategory::getShopId, shopId)
                        .eq(ShopCategory::getIsDelete, 0));
                if (shopCategoryByCode1 == null) {
                    //不存在门店分类父类目添加
                    FrontCategory frontCategoryParent = frontCategoryMapper.selectOne(new LambdaQueryWrapper<FrontCategory>()
                            .eq(FrontCategory::getCode, frontCategory.getParentCode())
                            .eq(FrontCategory::getIsDelete, 0));
                    addShopCategory(frontCategoryParent, prodId, shopId, hbShopId);

                    shopCategoryByCode1 = shopCategoryMapper.selectOne(new LambdaQueryWrapper<ShopCategory>()
                            .eq(ShopCategory::getCode, frontCategory.getParentCode())
                            .eq(ShopCategory::getShopId, shopId)
                            .eq(ShopCategory::getIsDelete, 0));
                }
                shopCategory.setPid(shopCategoryByCode1.getId());
                shopCategory.setParentCode(shopCategoryByCode1.getCode());
            }

            shopCategory.setShopId(shopId);
            shopCategory.setHbShopId(hbShopId);
            shopCategory.setLabel(frontCategory.getLabel());
            shopCategory.setIcon(frontCategory.getIcon());
            shopCategory.setPic(frontCategory.getPic());
            shopCategory.setLevel(frontCategory.getLevel());
            shopCategory.setIsDelete(0);
            shopCategory.setOperateUser("admin");
            shopCategory.setNum(frontCategory.getNum());
            shopCategory.setIsLeaves(frontCategory.getIsLeaves());
            shopCategory.setRecTime(new Date());

            shopCategoryMapper.insert(shopCategory);

            try {
                String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncShopCategoryData";
                String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopCategory);
                log.info("推送门店分类到同步服务器结果: {}", response);
            } catch (Exception e) {
                log.error("推送门店分类到同步服务器失败: {}", e.getMessage(), e);
            }

            log.info("门店分类添加成功：{}", shopCategory);
            //二级添加门店-分类绑定商品管理
            addCategoryProd(prodId, shopCategory);
        } else {
            log.info("门店分类已存在，无需添加");
            //二级添加门店-分类绑定商品管理
            addCategoryProd(prodId, shopCategoryByCode);
        }
    }

    /**
     * 添加门店-分类绑定商品管理
     *
     * @param prodId       商品id
     * @param shopCategory 门店分类
     */
    private void addCategoryProd(Long prodId, ShopCategory shopCategory) {
        log.info("添加门店-分类绑定商品管理");
        if (shopCategory.getLevel() == 2) {
            Integer count = categoryProdMapper.selectCount(new LambdaQueryWrapper<CategoryProd>()
                    .eq(CategoryProd::getIsDelete, 0)
                    .eq(CategoryProd::getCode, shopCategory.getCode())
                    .eq(CategoryProd::getProdId, prodId)
                    .eq(CategoryProd::getShopId, shopCategory.getShopId()));

            if (count == 0) {
                CategoryProd categoryProd = new CategoryProd();
                categoryProd.setProdId(prodId);
                categoryProd.setCategoryId(shopCategory.getId());
                categoryProd.setCode(shopCategory.getCode());
                categoryProd.setShopId(shopCategory.getShopId());
                categoryProd.setIsDelete(0);
                categoryProd.setCreateTime(new Date());

                categoryProdMapper.insert(categoryProd);

                try {
                    String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncCategoryProdData";
                    // 将frontCategory对象作为JSON放入请求体
                    String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, categoryProd);
                    log.info("推送frontCategory到同步服务器结果: {}", response);
                } catch (Exception e) {
                    log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HBR updateGoodsPrice(JSONObject hbRequest) {
        try {
            String bodyStr = hbRequest.getString("body");
            log.info("商品，body：{}", bodyStr);
            JSONObject bodyJson = JSON.parseObject(bodyStr);
            JSONArray requestList = bodyJson.getJSONArray("requestList");
            for (Object request : requestList) {
                JSONObject jsonObject = JSON.parseObject(request.toString());
                String skuId = jsonObject.getString("skuId");
                Double currentPrice = jsonObject.getDouble("currentPrice");
                String stationId = jsonObject.getString("stationId");//海博门店编码
                ShopDetail shopDetail = shopDetailMapper.selectByHbStationId(stationId);
                if (ObjectUtil.isEmpty(shopDetail)) {
                    log.error("系统找不到对应的门店（门店编码:{}）信息", stationId);
                    return HBR.error("系统找不到对应的门店（门店编码:" + stationId + "）信息");
                }

                //改变单品价格
                Sku sku = skuMapper.selectByHbSkuId(skuId);
                if (ObjectUtil.isEmpty(sku)) {
                    log.error("更改价格系统找不到对应商品(单品):{}", skuId);
                    return HBR.error("更改价格系统找不到对应商品(单品)：" + skuId);
                }

                ShopSku shopSku = shopSkuMapper.selectByShopAndSku(sku.getSkuId(), shopDetail.getShopId());
                if (ObjectUtil.isEmpty(shopSku)) {
                    ShopSku shopSkuInfo = new ShopSku();
                    shopSkuInfo.setShopId(shopDetail.getShopId());
                    shopSkuInfo.setShopSkuPrice(currentPrice == null ? 0.0 : currentPrice);
                    shopSkuInfo.setSkuId(sku.getSkuId());
                    shopSkuInfo.setSpuId(sku.getProdId());
                    shopSkuInfo.setIsDelete(0);
                    shopSkuInfo.setRecTime(new Date());
                    shopSkuMapper.insert(shopSkuInfo);
                    log.info("门店对应商品系统不存在直接添加");
                    try {
                        String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncShopSkuData";
                        // 将frontCategory对象作为JSON放入请求体
                        String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopSkuInfo);
                        log.info("推送frontCategory到同步服务器结果: {}", response);
                    } catch (Exception e) {
                        log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                    }
                } else {
                    shopSku.setSpuId(sku.getProdId());
                    shopSku.setShopSkuPrice(currentPrice == null ? 0.0 : currentPrice);
                    shopSku.setUpdateTime(new Date());
                    shopSkuMapper.updateById(shopSku);
                    log.info("价格更改成功");
                    try {
                        String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncShopSkuData";
                        // 将frontCategory对象作为JSON放入请求体
                        String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopSku);
                        log.info("推送frontCategory到同步服务器结果: {}", response);
                    } catch (Exception e) {
                        log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("商品失败：{}", e.getMessage(), e);
            return HBR.error("未知异常");

        }
        return HBR.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HBR updateGoodsStock(JSONObject hbRequest) {
        try {
            String bodyStr = hbRequest.getString("body");
            log.info("商品库存变动，body：{}", bodyStr);
            JSONObject bodyJson = JSON.parseObject(bodyStr); // 使用Fastjson的解析方法
            JSONArray requestList = bodyJson.getJSONArray("requestList");
            for (Object request : requestList) {
                JSONObject jsonObject = JSON.parseObject(request.toString());
                String skuId = jsonObject.getString("skuId");
                String stationId = jsonObject.getString("stationId");//海博门店编码
                ShopDetail shopDetail = shopDetailMapper.selectByHbStationId(stationId);
                if (shopDetail == null) {
                    log.error("系统找不到对应的门店信息（门店编码:{}）", stationId);
                    return HBR.error("系统找不到对应的门店信息（门店编码:" + stationId + "）");
                }

                Integer currentStock = jsonObject.getInteger("currentStock");
                //改变单品库存
                Sku sku = skuMapper.selectByHbSkuId(skuId);
                if (ObjectUtil.isEmpty(sku)) {
                    log.error("系统找不到对应商品(单品):{}", skuId);
                    return HBR.error("系统找不到对应商品(单品)：" + skuId);
                }

                ShopSku shopSku = shopSkuMapper.selectByShopAndSku(sku.getSkuId(), shopDetail.getShopId());
                if (ObjectUtil.isEmpty(shopSku)) {
                    ShopSku shopSkuInfo = new ShopSku();
                    shopSkuInfo.setShopId(shopDetail.getShopId());
                    shopSkuInfo.setShopSkuStocks(currentStock);
                    shopSkuInfo.setSkuId(sku.getSkuId());

                    shopSkuInfo.setIsDelete(0);
                    shopSkuInfo.setRecTime(new Date());
                    shopSkuInfo.setUpdateTime(new Date());
                    shopSkuMapper.insert(shopSkuInfo);
                    log.info("库存添加成功");
                    try {
                        String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncShopSkuData";
                        // 将frontCategory对象作为JSON放入请求体
                        String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopSkuInfo);
                        log.info("推送frontCategory到同步服务器结果: {}", response);
                    } catch (Exception e) {
                        log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                    }
                } else {
                    shopSku.setSpuId(sku.getProdId());
                    shopSku.setShopSkuStocks(currentStock);
                    shopSku.setUpdateTime(new Date());
                    shopSkuMapper.updateById(shopSku);
                    log.info("库存更改成功");
                    try {
                        String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncShopSkuData";
                        // 将frontCategory对象作为JSON放入请求体
                        String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopSku);
                        log.info("推送frontCategory到同步服务器结果: {}", response);
                    } catch (Exception e) {
                        log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("商品失败：{}", e.getMessage(), e);
            return HBR.error("未知异常");

        }
        return HBR.success();
    }

    @Override
    public void deleteGoods(JSONObject hbRequest) {
        JSONObject body = hbRequest.getJSONObject("body");
        log.info("商品删除，body：{}", body);

        JSONArray productList = body.getJSONArray("productList");
        for (Object hbProductObject : productList) {
            JSONObject hbProduct = JSON.parseObject(hbProductObject.toString());

            String spuId = hbProduct.getString("spuId");
            String skuId = hbProduct.getString("skuId");
            Product product;
            if (ObjectUtil.isNotEmpty(spuId)) {
                product = productMapper.selectByHbSpuId(spuId);
            } else {
                Sku sku = skuMapper.selectByHbSkuId(skuId);
                product = productMapper.selectByHbSpuId(sku.getHbSpuId());
            }
            if (!ObjectUtil.isEmpty(product)) {
                product.setIsDelete(1);
                productMapper.updateById(product);
                try {
                    String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncProductDel" + product.getHbSpuId();
                    // 将frontCategory对象作为JSON放入请求体
                    String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, product);
                    log.info("推送frontCategory到同步服务器结果: {}", response);
                } catch (Exception e) {
                    log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                }

                skuMapper.deleteByProdId(product.getProdId());
                //删除门店对应商品
                shopSkuMapper.deleteByProdId(product.getProdId());
            }
        }
    }

    @Override
    public String selectHBGoodsInfo(String outSkuId) {

        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        JSONObject skuItem = new JSONObject();
//        skuItem.put("skuId", "1328633");      // 海博商品编码
        skuItem.put("outSkuId", outSkuId);    // 商家商品编码
        // 2. 创建商品列表并添加SKU对象
        List<JSONObject> productList = new ArrayList<>();
        productList.add(skuItem);
        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("productList", productList);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 商品查询请求参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/product/getSku", build);
        log.info("post 商品查询结果：{}", post);
        return post;
    }


    /**
     * 多规格查询
     *
     * @param spuId 海博多规格商品编码
     */
    @Override
    public String selectHBGoodsSpuInfo(String spuId) {

        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        JSONObject skuItem = new JSONObject();
//        skuItem.put("skuId", "1328633");      // 海博商品编码
        skuItem.put("spuId", spuId);    // 商家商品编码
        // 2. 创建商品列表并添加SKU对象
        List<JSONObject> productList = new ArrayList<>();
        productList.add(skuItem);
        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("productList", productList);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 多规格商品查询请求参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/product/getSpus", build);
        log.info("post 多规格商品查询结果：{}", post);
        return post;
    }


    /**
     * 商品-门店品售卖状态查询接口
     *
     * @return 门店品售卖状态信息
     */
    public String getSelfSkuStatus(JSONArray data) {
        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", data);
//        List<JSONObject> onlineProductDTO = new ArrayList();
//        jsonObject.put("skuId", skuId);//海博商品编码
//        jsonObject.put("stationId", stationId);//海博门店编码
//        onlineProductDTO.add(jsonObject);
        build.setBody(JSON.toJSONString(jsonObject));
        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 商品查询请求参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/productStation/getSelfSkuStatus", build);
        log.info("post 商品查询结果：{}", post);
        return post;
    }


    /**
     * 从productInfo创建Product对象
     */
    private Product createProductFromProductInfo(JSONObject productInfo) {
        Product product = new Product();

        log.info("productInfo:{}", productInfo);
        // 直接映射字段
        product.setHbSpuId(productInfo.getLong("spuId"));
        product.setChannelCode(productInfo.getString("channelCode"));
        product.setProdName(productInfo.getString("spuName"));
        product.setBrief(productInfo.getString("sellPoint"));//简要描述,卖点等
        product.setVideo(productInfo.getString(""));//商品视频
        product.setStatus(1);
        product.setVersion(1);
        product.setProdType(0);//(0普通商品 1拼团 2秒杀 3积分)
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());
        product.setPutawayTime(new Date());
        //品牌ID
        product.setBrandId(productInfo.getLong("brandId"));
        //品牌名称
        product.setBrandName(productInfo.getString("brandName"));
        product.setHalfTitle(productInfo.getString("halfTitle"));
        String descText = productInfo.getString("descText");
        if (StringUtils.isEmpty(descText)) {
            product.setContent("<p>暂无商品详情</p>");
        } else {
            product.setContent(descText);
        }
        // 分类转换
        product.setCategoryId(productInfo.getLong("frontCategoryCode"));
        //后台类目平台对应ID
//        product.setHbFrontCategoryId(productInfo.getLong("frontCategoryCode"));
//        product.setPic(productInfo.getString("spuMainImage"));
//        product.setImgs(productInfo.getString("spuImages"));
        // 需要转换或默认值的字段
//        Product.setTotalStocks(productInfo.getString(""));//总库存
//        Product.setDeliveryMode(productInfo.getString(""));//配送方式
//        Product.setDeliveryTemplateId(productInfo.getString(""));//运费模板id

        log.info("商品数据详情{}", product);
        return product;
    }

    /**
     * 海博(普通)商品
     */
    private void setSpuMapper(JSONObject productInfo, Product product) {
        product.setPic(productInfo.getString("mainImage"));//商品主图
        product.setHbStatus(1);//海博商品类型（1-普通商品，2-多规格商品）
        product.setImgs(productInfo.getString("images"));//商品图片，以,分割
    }

    /**
     * 海博(多规格)商品
     */
    private void setSpuSpecMapper(JSONObject productInfo, Product product) {

        product.setPic(productInfo.getString("spuMainImage"));//商品主图
        product.setHbStatus(2);//海博商品类型（1-普通商品，2-多规格商品）
        product.setImgs(productInfo.getString("spuImages"));//商品图片，以,分割

    }

    /**
     * 从productInfo创建Sku对象
     */
    private Sku createSkuFromProductInfo(JSONObject productInfo) {
        log.info("创建Sku对象数据==========={}===========", productInfo);
        Sku sku = new Sku();
        // 直接映射字段
        sku.setHbSkuId(productInfo.getString("skuId"));//单品id - 关联海博同步
        sku.setSkuName(productInfo.getString("skuName"));//单品名称
        sku.setProdName(productInfo.getString("spuName"));//商品名称
        sku.setModelId(productInfo.getString("upc")); // 商品条码
        sku.setPartyCode(productInfo.getString("outSkuId"));//商家商品编码
        sku.setSkuCode(productInfo.getString("outSkuId"));//商家商品编码
        sku.setSpec(productInfo.getString("spec"));//规格
//        sku.setPic(productInfo.getString("skuImages"));//sku图片
//        Sku.setVolume(productInfo.getString(""));//体积
        sku.setStatus(1);
        sku.setIsDelete(0);
        sku.setVersion(0);
//        String images = StringUtils.isEmpty(productInfo.getString("images")) ? productInfo.getString("skuMainImage") : productInfo.getString("images");
        sku.setPic(productInfo.getString("mainImage"));//sku图片
        sku.setWeightUnit(productInfo.getString("unit"));//单位
        // 商品原价
        sku.setOriPrice(productInfo.getDouble("basicPrice") != null ?
                productInfo.getDouble("basicPrice") : 0);
        //实际库存
        sku.setActualStocks(productInfo.getInteger("initStock") == null ? 0 :
                productInfo.getInteger("initStock"));

        sku.setRecTime(new Date());
        sku.setUpdateTime(new Date());

        // 重量
        Double weightStr = productInfo.getDouble("weight");
        sku.setWeight(weightStr == null ? 0.0 : weightStr);

        //体积
        sku.setVolume(0.0);
        sku.setStatus(1); // 状态默认正常
        log.info("单品数据详情{}", sku);
        return sku;
    }

    /**
     * 分类处理
     */
    private void convertCategoryCodeToId(JSONArray categoryCode, Long spuId) {
        log.info("新增商品分类处理{}", categoryCode);
        List<String> list = new ArrayList<>();
        for (Object o : categoryCode) {
            JSONObject jsonObject = JSON.parseObject(o.toString());

            String ztFrontCategoryCodeLevel = jsonObject.getString("ztFrontCategoryCodeLevel2");
            if (StringUtils.isEmpty(ztFrontCategoryCodeLevel)) {
                ztFrontCategoryCodeLevel = jsonObject.getString("ztFrontCategoryCode");
            }
            list.add(ztFrontCategoryCodeLevel);
            addCategoryProdHb(spuId, ztFrontCategoryCodeLevel);
        }

        //删除多余的 分类绑定商品数据
        log.info("删除多余的 分类绑定商品数据{}", list);
        List<CategoryProdHb> categoryProdsHb = categoryProdHbMapper.selectList(new LambdaQueryWrapper<CategoryProdHb>()
                .eq(CategoryProdHb::getProdId, spuId)
                .notIn(CategoryProdHb::getCode, list)
                .eq(CategoryProdHb::getIsDelete, 0));
        for (CategoryProdHb categoryProdHb : categoryProdsHb) {
            categoryProdHb.setIsDelete(1);
            categoryProdHbMapper.updateById(categoryProdHb);
            categoryProdMapper.deleteByCodeAndProdId(categoryProdHb.getCode(), spuId);

            try {
                String syncUrl = "http://192.168.1.101:8080/smqjh-pms/api/v1/sync/syncCategoryProdData";
                // 将frontCategory对象作为JSON放入请求体
                List<CategoryProd> categoryProds = categoryProdMapper.selectList(new LambdaQueryWrapper<CategoryProd>().eq(CategoryProd::getCode, categoryProdHb.getCode()));
                for (CategoryProd categoryProd : categoryProds) {
                    String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, categoryProd);
                    log.info("推送frontCategory到同步服务器结果: {}", response);
                }
            } catch (Exception e) {
                log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
            }

        }

    }

    private void addCategoryProdHb(Long spuId, String ztFrontCategoryCodeLevel) {
        CategoryProdHb categoryProd = new CategoryProdHb();
        categoryProd.setCode(ztFrontCategoryCodeLevel);
        categoryProd.setProdId(spuId);
        categoryProd.setIsDelete(0);
        categoryProd.setCreateTime(new Date());
        CategoryProdHb integer = categoryProdHbMapper.selectOne(new LambdaQueryWrapper<CategoryProdHb>()
                .eq(CategoryProdHb::getProdId, spuId)
                .eq(CategoryProdHb::getIsDelete, 0)
                .eq(CategoryProdHb::getCode, ztFrontCategoryCodeLevel));
        if (integer == null) {
            categoryProdHbMapper.insert(categoryProd);
        }
        //门店分类处理
        List<ShopSku> shopCategoryList = shopSkuMapper.selectList(new LambdaQueryWrapper<ShopSku>()
                .eq(ShopSku::getSpuId, spuId)
                .eq(ShopSku::getIsDelete, 0));

        for (ShopSku shopSku : shopCategoryList) {
            FrontCategory frontCategory = frontCategoryMapper.selectOne(new LambdaQueryWrapper<FrontCategory>()
                    .eq(FrontCategory::getCode, ztFrontCategoryCodeLevel));
            ShopDetail shopDetail = shopDetailMapper.selectById(shopSku.getShopId());

            addShopCategory(frontCategory, spuId, shopSku.getShopId(), shopDetail.getHbStationId());
        }

    }


}
