package com.slodon.b2b2c.model.goods;

import com.alibaba.fastjson.JSON;
import com.slodon.b2b2c.core.constant.*;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.dao.read.goods.GoodsCategoryReadMapper;
import com.slodon.b2b2c.dao.read.goods.GoodsReadMapper;
import com.slodon.b2b2c.dao.read.goods.ProductReadMapper;
import com.slodon.b2b2c.dao.read.seller.StoreBindCategoryReadMapper;
import com.slodon.b2b2c.dao.write.goods.GoodsCategoryWriteMapper;
import com.slodon.b2b2c.enums.SeoTypeConstant;
import com.slodon.b2b2c.goods.dto.GoodsCategoryAddDTO;
import com.slodon.b2b2c.goods.dto.GoodsCategoryUpdateDTO;
import com.slodon.b2b2c.goods.example.GoodsCategoryExample;
import com.slodon.b2b2c.goods.example.GoodsExample;
import com.slodon.b2b2c.goods.example.ProductExample;
import com.slodon.b2b2c.goods.pojo.*;
import com.slodon.b2b2c.model.seller.StoreBindCategoryModel;
import com.slodon.b2b2c.model.seller.StoreModel;
import com.slodon.b2b2c.seller.example.StoreBindCategoryExample;
import com.slodon.b2b2c.seller.pojo.StoreBindCategory;
import com.slodon.b2b2c.system.pojo.Admin;
import com.slodon.b2b2c.system.pojo.SysSeo;
import com.slodon.b2b2c.vo.goods.GoodsCategoryListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class GoodsCategoryModel {

    @Resource
    private GoodsCategoryReadMapper goodsCategoryReadMapper;
    @Resource
    private GoodsCategoryWriteMapper goodsCategoryWriteMapper;
    @Resource
    private GoodsCategoryBindAttributeModel goodsCategoryBindAttributeModel;
    @Resource
    private GoodsCategoryBindBrandModel goodsCategoryBindBrandModel;
    @Resource
    private GoodsReadMapper goodsReadMapper;
    @Resource
    private GoodsBrandModel goodsBrandModel;
    @Resource
    private GoodsCategoryModel goodsCategoryModel;
    @Resource
    private StoreModel storeModel;
    @Resource
    private GoodsModel goodsModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private ProductReadMapper productReadMapper;
    @Resource
    private RedisTemplate<String, Object> objectRedisTemplate;
    @Resource
    private StoreBindCategoryModel storeBindCategoryModel;
    @Resource
    private StoreBindCategoryReadMapper storeBindCategoryReadMapper;

    /**
     * 新增商品分类
     *
     * @param goodsCategory
     * @return
     */
    public Integer saveGoodsCategory(GoodsCategory goodsCategory) {
        int count = goodsCategoryWriteMapper.insert(goodsCategory);
        if (count == 0) {
            throw new MallException("添加商品分类失败，请重试");
        }
        return count;
    }

    /**
     * 查询商品分类数
     *
     * @return
     */
    public Integer getGoodsCategoryListCount(GoodsCategoryExample example) {
        return goodsCategoryReadMapper.countByExample(example);
    }

    /**
     * 新增商品分类
     *
     * @param goodsCategoryAddDTO
     * @param admin
     * @return
     */
    private Integer saveGoodsCategory(Admin admin, GoodsCategoryAddDTO goodsCategoryAddDTO,String seoTitle,String seoDesc,String seoKeyWords) {
        // 验证参数是否为空
        if (goodsCategoryAddDTO == null) {
            throw new MallException("分类信息不能为空，请重试！");
        } else if (goodsCategoryAddDTO.getCategoryName() == null) {
            throw new MallException("分类名称不能为空，请重试！");
        } else if (goodsCategoryAddDTO.getPid() == null) {
            throw new MallException("上级分类不能为空，请重试！");
        } else if (goodsCategoryAddDTO.getSort() == null) {
            throw new MallException("分类排序不能为空，请重试！");
        }
        if (goodsCategoryAddDTO.getPid() != 0) {
            if (goodsCategoryAddDTO.getHomeShow() == null) {
                throw new MallException("首页显示不能为空，请重试！");
            }
        } else {
            goodsCategoryAddDTO.setHomeShow(GoodsCategoryConst.IS_SHOW_PC_1);
        }
        //判断该pid下的子分类中有没有分类名称重复的
        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        goodsCategoryExample.setPid(goodsCategoryAddDTO.getPid());
        goodsCategoryExample.setCategoryAlias(goodsCategoryAddDTO.getCategoryAlias());
        goodsCategoryExample.setCategoryName(goodsCategoryAddDTO.getCategoryName());
        List<GoodsCategory> goodsCategoryList = goodsCategoryReadMapper.listByExample(goodsCategoryExample);
        if (!CollectionUtils.isEmpty(goodsCategoryList)) {
            throw new MallException("分类名称已存在，请重新填写");
        }

        //获取上级分类
        GoodsCategory parentGoodsCategory = getGoodsCategoryByCategoryId(goodsCategoryAddDTO.getPid());

        //插入分类表
        GoodsCategory goodsCategoryInsert = new GoodsCategory();
        goodsCategoryInsert.setCategoryName(goodsCategoryAddDTO.getCategoryName());
        goodsCategoryInsert.setWebSite(goodsCategoryAddDTO.getWebSite());
        goodsCategoryInsert.setPid(goodsCategoryAddDTO.getPid());
        String path;
        Integer grade;
        if (parentGoodsCategory == null) {
            path = "/";
            grade = 1;
        } else {
            path = parentGoodsCategory.getPath();
            if (parentGoodsCategory.getPid() != 0) {
                path += "/";
            }
            path += goodsCategoryAddDTO.getPid();
            grade = parentGoodsCategory.getGrade() + 1;
        }
        goodsCategoryInsert.setPath(path);
        goodsCategoryInsert.setScaling(goodsCategoryAddDTO.getScaling());
        goodsCategoryInsert.setCreateAdminId(admin.getAdminId());
        goodsCategoryInsert.setUpdateAdminId(admin.getAdminId());
        goodsCategoryInsert.setCreateTime(new Date());
        goodsCategoryInsert.setUpdateTime(new Date());
        goodsCategoryInsert.setSort(goodsCategoryAddDTO.getSort());
        goodsCategoryInsert.setState(1);
        goodsCategoryInsert.setGrade(grade);
        goodsCategoryInsert.setMobileImage(goodsCategoryAddDTO.getMobileImage());
        goodsCategoryInsert.setCategoryImage(goodsCategoryAddDTO.getCategoryImage());
        goodsCategoryInsert.setRecommendPicture(goodsCategoryAddDTO.getRecommendPicture());
        goodsCategoryInsert.setHomeShow(goodsCategoryAddDTO.getHomeShow());
        int count;
        count = goodsCategoryWriteMapper.insert(goodsCategoryInsert);


        int seoCount = goodsCategoryModel.addAndUpdateSeoForGoodsCategory(seoTitle,seoDesc,seoKeyWords,admin,goodsCategoryInsert.getCategoryId(),goodsCategoryInsert.getWebSite());
        if(seoCount == 0){
            throw new MallException("添加seo表失败，请重试");
        }

        if (count == 0) {
            throw new MallException("添加分类表失败，请重试");
        }

        return goodsCategoryInsert.getCategoryId();
    }

    /**
     * 新增商品分类 并绑定品牌和属性
     *
     * @param goodsCategoryAddDTO
     * @param admin
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveGoodsCategoryBindAttributeBrand(Admin admin, GoodsCategoryAddDTO goodsCategoryAddDTO,
                String seoTitle,String seoDesc,String seoKeyWords) {

        Integer categoryId = this.saveGoodsCategory(admin, goodsCategoryAddDTO, seoTitle, seoDesc, seoKeyWords);

        //保存绑定的属性
        goodsCategoryBindAttributeModel.saveGoodsCategoryBindAttributeByCategory(categoryId, goodsCategoryAddDTO.getBindAttributes());
        //保存绑定的品牌
        goodsCategoryBindBrandModel.saveGoodsCategoryBindAttributeByCategory(categoryId, goodsCategoryAddDTO.getBindBrands());
    }

    /**
     * 商品分类新增SEO入库
     *
     * @param seoTitle
     * @param seoDesc
     * @param seoKeyWords
     * @param admin
     * @return
     */
    public Integer addAndUpdateSeoForGoodsCategory(String seoTitle, String seoDesc, String seoKeyWords,Admin admin,Integer categoryId,String webSite){
        //以下为新增SEO表
        SysSeo sysSeo = new SysSeo();
        sysSeo.setTenant(0L);
        sysSeo.setWebSite(webSite);
        sysSeo.setType(SeoTypeConstant.SEO_TYPE_GOODS_CATEGORY);
        sysSeo.setName("商品分类SEO");
//        sysSeo.setCode(SeoTypeConstant.SEO_TYPE_GOODS_CATEGORY+"_"+Integer.valueOf(storeInnerLabel.getInnerLabelId()).longValue());
        sysSeo.setTargetId(Integer.valueOf(categoryId).longValue());
        sysSeo.setTitle(seoTitle);
        sysSeo.setRemark(seoDesc);
        sysSeo.setKeywords(seoKeyWords);

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        //判断此条seoId对应的记录是否为空
        SysSeo seoInfo = storeModel.getRecordByTargetIdAndType(sysSeo.getTargetId(),sysSeo.getType());
        int count = 0;
        if(seoInfo !=null){
            sysSeo.setUpdateUid(Integer.valueOf(admin.getAdminId()).longValue());
            sysSeo.setUpdateTime(time);
            count = storeModel.updateSeo(sysSeo,sysSeo.getTargetId(),sysSeo.getType());
        }else{
            sysSeo.setCreateUid(Integer.valueOf(admin.getAdminId()).longValue());
            sysSeo.setCreateTime(time);
            sysSeo.setCode(SeoTypeConstant.SEO_TYPE_GOODS_CATEGORY + "_" + Integer.valueOf(categoryId).longValue());
            count = storeModel.saveSeo(sysSeo);
        }
        if(count == 0){
            log.error("seo内容入库失败");
            throw new MallException("seo内容入库失败,请重试");
        }
        return count;
    }

    /**
     * （重载上一个方法，没办法GoodsCategoryAddDTO和GoodsCategoryUpdateDTO内容不一样）
     * 商品分类编辑SEO入库
     * @param goodsCategoryUpdateDTO
     * @param seoTitle
     * @param seoDesc
     * @param seoKeyWords
     * @param admin
     * @return
     */
    public Integer addAndUpdateSeoForGoodsCategory( GoodsCategoryUpdateDTO goodsCategoryUpdateDTO,
                                                    String seoTitle, String seoDesc, String seoKeyWords,Admin admin){
        //以下为新增SEO表
        SysSeo sysSeo = new SysSeo();
        sysSeo.setTenant(0L);
        sysSeo.setWebSite(goodsCategoryUpdateDTO.getWebSite());
        sysSeo.setType(SeoTypeConstant.SEO_TYPE_GOODS_CATEGORY);
        sysSeo.setName("商品分类SEO");
//        sysSeo.setCode(SeoTypeConstant.SEO_TYPE_GOODS_CATEGORY+"_"+Integer.valueOf(storeInnerLabel.getInnerLabelId()).longValue());
        sysSeo.setTargetId(Integer.valueOf(goodsCategoryUpdateDTO.getCategoryId()).longValue());
        sysSeo.setTitle(seoTitle);
        sysSeo.setRemark(seoDesc);
        sysSeo.setKeywords(seoKeyWords);

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        //判断此条seoId对应的记录是否为空
        SysSeo seoInfo = storeModel.getRecordByTargetIdAndType(sysSeo.getTargetId(),sysSeo.getType());
        int count = 0;
        if(seoInfo !=null){
            sysSeo.setUpdateUid(Integer.valueOf(admin.getAdminId()).longValue());
            sysSeo.setUpdateTime(time);
            count = storeModel.updateSeo(sysSeo,sysSeo.getTargetId(),sysSeo.getType());
        }else{
            sysSeo.setCreateUid(Integer.valueOf(admin.getAdminId()).longValue());
            sysSeo.setCreateTime(time);
            sysSeo.setCode(SeoTypeConstant.SEO_TYPE_GOODS_CATEGORY + "_" + Integer.valueOf(goodsCategoryUpdateDTO.getCategoryId()).longValue());
            count = storeModel.saveSeo(sysSeo);
        }
        if(count == 0){
            log.error("seo内容入库失败");
            throw new MallException("seo内容入库失败,请重试");
        }
        return count;
    }



    /**
     * 根据categoryId删除商品分类
     *
     * @param categoryId categoryId
     * @return
     */
    public Integer deleteGoodsCategory(Integer categoryId) {
        if (StringUtils.isEmpty(categoryId)) {
            throw new MallException("请选择要删除的数据");
        }
        int count = goodsCategoryWriteMapper.deleteByPrimaryKey(categoryId);
        if (count == 0) {
            log.error("根据categoryId：" + categoryId + "删除商品分类失败");
            throw new MallException("删除商品分类失败,请重试");
        }
        return count;
    }

    /**
     * 根据categoryId删除商品分类 同时删除属性，品牌绑定关系
     *
     * @param categoryId categoryId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult deleteGoodsCategoryBindAttributeBrand(Integer categoryId) {
        //判断该分类下是否绑定商品
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setStateNotEquals(GoodsConst.GOODS_STATE_DELETE);
        //先查询该分类分类级别
        GoodsCategory goodsCategoryDB = goodsCategoryReadMapper.getByPrimaryKey(categoryId);
        Integer grade = goodsCategoryDB.getGrade();
        if (grade == GoodsCategoryConst.CATEGORY_GRADE_1) {
            goodsExample.setCategoryId1(goodsCategoryDB.getCategoryId());
        } else if (grade == GoodsCategoryConst.CATEGORY_GRADE_2) {
            goodsExample.setCategoryId2(goodsCategoryDB.getCategoryId());
        } else {
            goodsExample.setCategoryId3(goodsCategoryDB.getCategoryId());
        }
        List<Goods> goodsList = goodsReadMapper.listByExample(goodsExample);
        AssertUtil.isTrue(!CollectionUtils.isEmpty(goodsList), "已绑定商品的分类不能删除");

        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        goodsCategoryExample.setPid(categoryId);
        List<GoodsCategory> goodsCategoryList = getGoodsCategoryList(goodsCategoryExample, null);
        List<GoodsCategoryListVO> vos = new ArrayList<>();
        generateTree(vos, goodsCategoryList, 0);
        deleteCategoryList(vos);
        deleteGoodsCategory(categoryId);
        //删除旧的属性绑定关系
        goodsCategoryBindAttributeModel.deleteGoodsCategoryBindAttributeByCategory(categoryId);
        //删除旧的品牌绑定关系
        goodsCategoryBindBrandModel.deleteGoodsCategoryBindBrandByCategory(categoryId);
        //删除该分类绑定的品牌
        goodsBrandModel.delGoodsBrandByCategoryId(categoryId);
        return SldResponse.success("删除分类成功");
    }

    private void deleteCategoryList(List<GoodsCategoryListVO> vos) {
        for (GoodsCategoryListVO vo : vos) {
            deleteGoodsCategory(vo.getCategoryId());
            //删除旧的属性绑定关系
            goodsCategoryBindAttributeModel.deleteGoodsCategoryBindAttributeByCategory(vo.getCategoryId());
            //删除旧的品牌绑定关系
            goodsCategoryBindBrandModel.deleteGoodsCategoryBindBrandByCategory(vo.getCategoryId());
            if (vo.getChildren().size() > 0) {
                deleteCategoryList(vo.getChildren());
            }
        }
    }

    /**
     * 根据categoryId更新商品分类
     *
     * @param goodsCategory
     * @return
     */
    public Integer updateGoodsCategory(GoodsCategory goodsCategory) {
        if (StringUtils.isEmpty(goodsCategory.getCategoryId())) {
            throw new MallException("请选择要修改的数据");
        }
        int count = goodsCategoryWriteMapper.updateByPrimaryKeySelective(goodsCategory);
        if (count == 0) {
            log.error("根据categoryId：" + goodsCategory.getCategoryId() + "更新商品分类失败");
            throw new MallException("更新商品分类失败,请重试");
        }
        return count;
    }

    /**
     * 根据categoryId更新商品分类
     *
     * @param goodsCategoryUpdateDTO
     * @param admin
     */
    private void updateGoodsCategory(Admin admin, GoodsCategoryUpdateDTO goodsCategoryUpdateDTO) {
        if (!StringUtils.isEmpty(goodsCategoryUpdateDTO.getCategoryName())) {
            AssertUtil.notNull(goodsCategoryUpdateDTO.getPid(), "请选择父分类");

//            //查询商品是否使用
//            GoodsCategory goodsCategory = goodsCategoryReadMapper.getByPrimaryKey(goodsCategoryUpdateDTO.getCategoryId());
//            AssertUtil.notNull(goodsCategory, "获取商品分类信息为空，请重试！");
//            if (!goodsCategory.getCategoryName().equals(goodsCategoryUpdateDTO.getCategoryName())) {
//                GoodsExample example = new GoodsExample();
//                if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_1) {
//                    example.setCategoryId1(goodsCategory.getCategoryId());
//                } else if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_2) {
//                    example.setCategoryId2(goodsCategory.getCategoryId());
//                } else {
//                    example.setCategoryId3(goodsCategory.getCategoryId());
//                }
//                example.setStateNotEquals(GoodsConst.GOODS_STATE_DELETE);
//                int count = goodsReadMapper.countByExample(example);
//                AssertUtil.isTrue(count > 0, "该分类已被商品使用，请不要编辑分类名称");
//            }

            //判断该pid下的子分类中有没有分类名称重复的
            GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
            goodsCategoryExample.setWebSite(goodsCategoryUpdateDTO.getWebSite());
            goodsCategoryExample.setPid(goodsCategoryUpdateDTO.getPid());
            goodsCategoryExample.setCategoryIdNotEquals(goodsCategoryUpdateDTO.getCategoryId());
            goodsCategoryExample.setCategoryName(goodsCategoryUpdateDTO.getCategoryName());
            List<GoodsCategory> goodsCategoryList = goodsCategoryReadMapper.listByExample(goodsCategoryExample);
            if (!CollectionUtils.isEmpty(goodsCategoryList)) {
                throw new MallException("分类名称已存在，请重新填写");
            }
        }

        GoodsCategory goodsCategoryUpdate = new GoodsCategory();
        goodsCategoryUpdate.setCategoryId(goodsCategoryUpdateDTO.getCategoryId());
        goodsCategoryUpdate.setWebSite(goodsCategoryUpdateDTO.getWebSite());
        goodsCategoryUpdate.setCategoryName(goodsCategoryUpdateDTO.getCategoryName());
        goodsCategoryUpdate.setScaling(goodsCategoryUpdateDTO.getScaling());
        goodsCategoryUpdate.setUpdateAdminId(admin.getAdminId());
        goodsCategoryUpdate.setUpdateTime(new Date());
        goodsCategoryUpdate.setSort(goodsCategoryUpdateDTO.getSort());
        goodsCategoryUpdate.setMobileImage(goodsCategoryUpdateDTO.getMobileImage());
        goodsCategoryUpdate.setCategoryImage(goodsCategoryUpdateDTO.getCategoryImage());
        goodsCategoryUpdate.setRecommendPicture(goodsCategoryUpdateDTO.getRecommendPicture());
        goodsCategoryUpdate.setHomeShow(goodsCategoryUpdateDTO.getHomeShow());
        int count = goodsCategoryWriteMapper.updateByPrimaryKeySelective(goodsCategoryUpdate);
        if (count == 0) {
            throw new MallException("编辑分类表失败，请重试");
        }
    }


    /**
     * 根据categoryId更新商品分类 并更新绑定品牌和属性
     *
     * @param goodsCategoryUpdateDTO
     * @param admin
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsCategoryBindAttributeBrand(Admin admin, GoodsCategoryUpdateDTO goodsCategoryUpdateDTO) {
        updateGoodsCategory(admin, goodsCategoryUpdateDTO);
        //删除旧的属性绑定关系
        goodsCategoryBindAttributeModel.deleteGoodsCategoryBindAttributeByCategory(goodsCategoryUpdateDTO.getCategoryId());

        //保存新绑定的属性
        goodsCategoryBindAttributeModel.saveGoodsCategoryBindAttributeByCategory(goodsCategoryUpdateDTO.getCategoryId(), goodsCategoryUpdateDTO.getBindAttributes());

        //删除旧的品牌绑定关系
        goodsCategoryBindBrandModel.deleteGoodsCategoryBindBrandByCategory(goodsCategoryUpdateDTO.getCategoryId());

        //保存绑定的品牌
        goodsCategoryBindBrandModel.saveGoodsCategoryBindAttributeByCategory(goodsCategoryUpdateDTO.getCategoryId(), goodsCategoryUpdateDTO.getBindBrands());
    }

    /**
     * 更新商品表分类数据
     *
     * @param goodsCategoryUpdateDTO
     */
    public void updateGoodsCategoryPathInfo(GoodsCategoryUpdateDTO goodsCategoryUpdateDTO) {
        log.info("******* updateGoodsCategoryPathInfo *******");
        GoodsCategory goodsCategory = goodsCategoryReadMapper.getByPrimaryKey(goodsCategoryUpdateDTO.getCategoryId());
        log.info("------- goodsCategory:{} ----------", JSON.toJSONString(goodsCategory));
        GoodsExample example = new GoodsExample();
        if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_1) {
            example.setCategoryId1(goodsCategory.getCategoryId());
        } else if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_2) {
            example.setCategoryId2(goodsCategory.getCategoryId());
        } else {
            example.setCategoryId3(goodsCategory.getCategoryId());
        }
        example.setStateNotEquals(GoodsConst.GOODS_STATE_DELETE);

        List<Goods> goodsList = goodsReadMapper.listByExample(example);
        log.info("********* goodsList:{} ************", JSON.toJSONString(goodsList));
        if (!CollectionUtils.isEmpty(goodsList)) {
            goodsList.forEach(c -> {
                List<String> oldCategoryPaths = Arrays.asList(c.getCategoryPath().split("->"));
                log.info("oldCategoryPaths:{}",oldCategoryPaths.size());
                log.info("oldCategoryPaths111111:{}", JSON.toJSONString(oldCategoryPaths));
                for (int i = 1; i <= oldCategoryPaths.size(); i++) {
                    log.info("i:{}，goodsCategory.getGrade():{}", i, goodsCategory.getGrade());
                    if (i == goodsCategory.getGrade()) {
                        log.info("****** 开始处理 *********");
                        oldCategoryPaths.set(i-1, goodsCategory.getCategoryName());
                    }
                }
                log.info("oldCategoryPaths22222:{}", JSON.toJSONString(oldCategoryPaths));
                Goods goods = new Goods();
                goods.setGoodsId(c.getGoodsId());
                String newCategoryPath = oldCategoryPaths.stream().map(String::valueOf).collect(Collectors.joining("->"));
                log.info("newCategoryPath:{}", newCategoryPath);
                goods.setCategoryPath(newCategoryPath);
                goodsModel.updateGoods(goods);
            });
        }
    }

    /**
     * 更新商品表特定规格数据
     *
     * @param goodsCategoryUpdateDTO
     */
    public void updateProductCategoryPathInfo(GoodsCategoryUpdateDTO goodsCategoryUpdateDTO) {
        log.info("******* updateProductCategoryPathInfo *******");
        GoodsCategory goodsCategory = goodsCategoryReadMapper.getByPrimaryKey(goodsCategoryUpdateDTO.getCategoryId());
        log.info("------- goodsCategory:{} ----------", JSON.toJSONString(goodsCategory));
        ProductExample example = new ProductExample();
        if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_1) {
            example.setCategoryId1(goodsCategory.getCategoryId());
        } else if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_2) {
            example.setCategoryId2(goodsCategory.getCategoryId());
        } else {
            example.setCategoryId3(goodsCategory.getCategoryId());
        }
        example.setStateNotEquals(GoodsConst.GOODS_STATE_DELETE);

        List<Product> productList = productReadMapper.listByExample(example);
        log.info("********* productList:{} ************", JSON.toJSONString(productList));
        if (!CollectionUtils.isEmpty(productList)) {
            productList.forEach(c -> {
                List<String> oldCategoryPaths = Arrays.asList(c.getCategoryPath().split("->"));
                log.info("oldCategoryPaths111111:{}", JSON.toJSONString(oldCategoryPaths));
                for (int i = 1; i <= oldCategoryPaths.size(); i++) {
                    log.info("i:{}，goodsCategory.getGrade():{}", i, goodsCategory.getGrade());
                    if (i == goodsCategory.getGrade()) {
                        log.info("****** 开始处理 *********");
                        oldCategoryPaths.set(i-1, goodsCategory.getCategoryName());
                    }
                }
                log.info("oldCategoryPaths22222:{}", JSON.toJSONString(oldCategoryPaths));
                Product product = new Product();
                product.setProductId(c.getProductId());
                String newCategoryPath = oldCategoryPaths.stream().map(String::valueOf).collect(Collectors.joining("->"));
                log.info("newCategoryPath:{}", newCategoryPath);
                product.setCategoryPath(newCategoryPath);
                productModel.updateProduct(product);

                //清除商品缓存
                deleteGoodsDetailCacheByProductId(product.getProductId());
            });
        }
    }

    /**
     * 更新店铺申请商品分类路径数据
     * @param goodsCategoryUpdateDTO
     */
    public void updateStoreBindCategoryPathInfo(GoodsCategoryUpdateDTO goodsCategoryUpdateDTO) {
        log.info("******* updateStoreBindCategoryPathInfo *******");
        GoodsCategory goodsCategory = goodsCategoryReadMapper.getByPrimaryKey(goodsCategoryUpdateDTO.getCategoryId());
        log.info("------- goodsCategory:{} ----------", JSON.toJSONString(goodsCategory));
        StoreBindCategoryExample example = new StoreBindCategoryExample();
        if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_1) {
            example.setGoodsCategoryId1(goodsCategory.getCategoryId());
        } else if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_2) {
            example.setGoodsCategoryId2(goodsCategory.getCategoryId());
        } else {
            example.setGoodsCategoryId3(goodsCategory.getCategoryId());
        }

        List<StoreBindCategory> storeBindCategoryList = storeBindCategoryReadMapper.listByExample(example);
        log.info("********* storeBindCategoryList:{} ************", JSON.toJSONString(storeBindCategoryList));
        if (!CollectionUtils.isEmpty(storeBindCategoryList)) {
            storeBindCategoryList.forEach(c -> {
                List<String> oldCategoryPaths = Arrays.asList(c.getGoodsCateName().split(">"));
                log.info("oldCategoryPaths111111:{}", JSON.toJSONString(oldCategoryPaths));
                for (int i = 1; i <= oldCategoryPaths.size(); i++) {
                    log.info("i:{}，goodsCategory.getGrade():{}", i, goodsCategory.getGrade());
                    if (i == goodsCategory.getGrade()) {
                        log.info("****** 开始处理 *********");
                        oldCategoryPaths.set(i-1, goodsCategory.getCategoryName());
                    }
                }
                log.info("oldCategoryPaths22222:{}", JSON.toJSONString(oldCategoryPaths));
                StoreBindCategory storeBindCategory = new StoreBindCategory();
                storeBindCategory.setBindId(c.getBindId());
                String newCategoryPath = oldCategoryPaths.stream().map(String::valueOf).collect(Collectors.joining(">"));
                log.info("newCategoryPath:{}", newCategoryPath);
                storeBindCategory.setGoodsCateName(newCategoryPath);
                storeBindCategoryModel.updateStoreBindCategory(storeBindCategory);
            });
        }
    }

    /**
     * 删除商品缓存数据
     * @param productId
     */
    public void deleteGoodsDetailCacheByProductId(Long productId){
        log.info("deleteGoodsDetailCacheByProductId --- productId:{}", productId);
        Product product = productModel.getProductByProductId(productId);
        if(product == null){
            return;
        }
        Long goodsId = product.getGoodsId();
        objectRedisTemplate.opsForHash().delete(RedisConst.GOODS_DETAIL, String.valueOf(goodsId));
    }

    /**
     * 根据categoryId获取商品分类详情
     *
     * @param categoryId categoryId
     * @return
     */
    public GoodsCategory getGoodsCategoryByCategoryId(Integer categoryId) {
        return goodsCategoryReadMapper.getByPrimaryKey(categoryId);
    }

    /**
     * 根据条件获取商品分类列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<GoodsCategory> getGoodsCategoryList(GoodsCategoryExample example, PagerInfo pager) {
        List<GoodsCategory> goodsCategoryList;
        if (pager != null) {
            pager.setRowsCount(goodsCategoryReadMapper.countByExample(example));
            goodsCategoryList = goodsCategoryReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            goodsCategoryList = goodsCategoryReadMapper.listByExample(example);
        }
        return goodsCategoryList;
    }

    /**
     * 根据 父类ID PID获取商品分类列表
     *
     * @param Pid 查询Pid
     * @return
     */
    public List<GoodsCategory> getGoodsCategoryListByPid(Integer Pid) {
        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        goodsCategoryExample.setPid(Pid);
        return goodsCategoryReadMapper.listByExample(goodsCategoryExample);
    }

    /**
     *分类列表生成树形结构
     */
    /**
     * 递归生成树
     *
     * @param treeList
     * @param data
     * @return
     */
    public List<GoodsCategoryListVO> generateTree(List<GoodsCategoryListVO> treeList, List<GoodsCategory> data, Integer grade) {
        if (grade < 3) {
            for (GoodsCategory goodsCategory : data) {
                GoodsCategoryListVO tree = new GoodsCategoryListVO(goodsCategory);
                tree.setCategoryId(goodsCategory.getCategoryId());
                tree.setPid(goodsCategory.getPid());
                tree.setCategoryName(goodsCategory.getCategoryName());
                tree.setSort(goodsCategory.getSort());
                tree.setScaling(goodsCategory.getScaling());
                tree.setGrade(goodsCategory.getGrade());
                tree.setChildren(generateTree(new ArrayList<>(), this.getGoodsCategoryListByPid(goodsCategory.getCategoryId()), goodsCategory.getGrade()));
                treeList.add(tree);
            }
        }
        return treeList;
    }
}