package com.slodon.b2b2c.controller.goods.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.slodon.b2b2c.aop.OperationLogger;
import com.slodon.b2b2c.core.constant.GoodsCategoryConst;
import com.slodon.b2b2c.core.constant.GoodsConst;
import com.slodon.b2b2c.core.constant.RedisConst;
import com.slodon.b2b2c.core.constant.StoreCateConst;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.*;
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.*;
import com.slodon.b2b2c.goods.pojo.*;
import com.slodon.b2b2c.model.goods.*;
import com.slodon.b2b2c.model.seller.StoreModel;
import com.slodon.b2b2c.seller.example.StoreInnerLabelExample;
import com.slodon.b2b2c.seller.pojo.StoreInnerLabel;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.system.pojo.Admin;
import com.slodon.b2b2c.system.pojo.SysSeo;
import com.slodon.b2b2c.vo.goods.*;
import com.slodon.b2b2c.vo.seller.StoreCategoryTreeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "admin-商品分类管理")
@RestController
@RequestMapping("v3/goods/admin/goodsCategory")
public class GoodsCategoryController {

    @Resource
    private GoodsCategoryModel goodsCategoryModel;
    @Resource
    private GoodsCategoryBindAttributeModel goodsCategoryBindAttributeModel;
    @Resource
    private GoodsCategoryBindBrandModel goodsCategoryBindBrandModel;
    @Resource
    private GoodsAttributeModel goodsAttributeModel;
    @Resource
    private GoodsAttributeValueModel goodsAttributeValueModel;
    @Resource
    private GoodsBrandModel goodsBrandModel;
    @Resource
    private GoodsModel goodsModel;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private StoreModel storeModel;

    @ApiOperation("分类列表,获取当前分类的下级分类，0代表获取所有1级分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类Id", required = true, paramType = "query"),
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query"),
            @ApiImplicitParam(name = "isSort", value = "是否排序：true-排序，false-不显示", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<GoodsCategoryListVO>> getList(HttpServletRequest request, @RequestParam(value = "categoryId") Integer categoryId,
                                                           @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite,
                                                           @RequestParam(value = "isSort", defaultValue = "false", required = false) Boolean isSort) {
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        goodsCategoryExample.setPid(categoryId);
        goodsCategoryExample.setWebSite(webSite);
        if (isSort) {
            goodsCategoryExample.setOrderBy("sort asc, create_time desc");
        }
        List<GoodsCategory> goodsCategoryList = goodsCategoryModel.getGoodsCategoryList(goodsCategoryExample, pager);
        List<GoodsCategoryListVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(goodsCategoryList)) {
            goodsCategoryList.forEach(goodsCategory -> {
                GoodsCategoryListVO vo = new GoodsCategoryListVO(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);
                vo.setTotalGoodsNum(goodsModel.getGoodsCount(example));
                //查询在售商品数
                example.setState(GoodsConst.GOODS_STATE_UPPER);
                vo.setOnSaleGoodsNum(goodsModel.getGoodsCount(example));
                //查询是否有子分类
                goodsCategoryExample.setPid(goodsCategory.getCategoryId());
                vo.setChildren(goodsCategoryModel.getGoodsCategoryListCount(goodsCategoryExample) > 0 ? new ArrayList<>() : null);
                this.dealGoodsCategoryBindBrandAndAttribute(vo);

                SysSeo seoInfo = storeModel.getRecordByTargetIdAndType(Integer.valueOf(vo.getCategoryId()).longValue(), SeoTypeConstant.SEO_TYPE_GOODS_CATEGORY);
                if(seoInfo!=null){
                    vo.setSeoTitle(seoInfo.getTitle());
                    vo.setSeoDesc(seoInfo.getRemark());
                    vo.setSeoKeyWords(seoInfo.getKeywords());
                }

                vos.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("二级商品分类列表")
    @GetMapping("getSecondGoodsCategory")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query")
    })
    public JsonResult<List<FrontGoodsCategoryVO>> getSecondGoodsCategory(HttpServletRequest request, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        goodsCategoryExample.setWebSite(webSite);
        goodsCategoryExample.setGrade(GoodsCategoryConst.CATEGORY_GRADE_2);
        List<GoodsCategory> goodsCategoryList = goodsCategoryModel.getGoodsCategoryList(goodsCategoryExample, null);
        List<FrontGoodsCategoryVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(goodsCategoryList)) {
            goodsCategoryList.forEach(goodsCategory -> {
                GoodsExample example = new GoodsExample();
                example.setCategoryId2(goodsCategory.getCategoryId());
                example.setStateNotEquals(GoodsConst.GOODS_STATE_DELETE);
                int count = goodsModel.getGoodsCount(example);
                if(count > 0){
                    FrontGoodsCategoryVO vo = new FrontGoodsCategoryVO(goodsCategory);
                    vos.add(vo);
                }

            });
        }

        return  SldResponse.success(vos);
    }

    @ApiOperation("商品分类列表")
    @GetMapping("newList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query")
    })
    public JsonResult<List<FrontGoodsCategoryVO>> getNewList(HttpServletRequest request,@RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        goodsCategoryExample.setWebSite(webSite);
        List<GoodsCategory> goodsCategoryList = goodsCategoryModel.getGoodsCategoryList(goodsCategoryExample, null);
        List<FrontGoodsCategoryVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(goodsCategoryList)) {
            goodsCategoryList.forEach(goodsCategory -> {
                FrontGoodsCategoryVO vo = new FrontGoodsCategoryVO(goodsCategory);
                //查询是否有子分类
                goodsCategoryExample.setPid(goodsCategory.getCategoryId());
                vo.setChildren(goodsCategoryModel.getGoodsCategoryListCount(goodsCategoryExample) > 0 ? new ArrayList<>() : null);
                vos.add(vo);
            });
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("获取商品分类树接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query"),
            @ApiImplicitParam(name = "pId", value = "父分类id", paramType = "query", required = true),
            @ApiImplicitParam(name = "grade", value = "查询层数", paramType = "query"),
    })
    @GetMapping("getCateTree")
    public JsonResult<List<GoodsCategoryListVO>> getCateTree(HttpServletRequest request,
                                                             @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite,
                                                             @RequestParam(value = "pId") Integer pId,
                                                             @RequestParam(value = "grade") Integer grade) {
        return SldResponse.success(this.getGoodsCategoryTree(webSite, pId, grade));
    }

    /**
     * 获取商品分类树
     *
     * @param webSite 站点
     * @param pId   父id
     * @param grade 获取级别，比如 pid=0,grade=3时，获取1、2、3级分类；pid=0,grade=2时，获取1、2级分类；pid=0,grade=1时，获取1级分类；
     * @return
     */
    private List<GoodsCategoryListVO> getGoodsCategoryTree(String webSite, Integer pId, Integer grade) {
        if (grade == 0) {
            return null;
        }
        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        goodsCategoryExample.setPid(pId);
        goodsCategoryExample.setWebSite(webSite);
        List<GoodsCategory> goodsCategoryList = goodsCategoryModel.getGoodsCategoryList(goodsCategoryExample, null);
        if (CollectionUtils.isEmpty(goodsCategoryList)) {
            return new ArrayList<>();
        }
        List<GoodsCategoryListVO> vos = new ArrayList<>();
        goodsCategoryList.forEach(goodsCategory -> {
            GoodsCategoryListVO vo = new GoodsCategoryListVO(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);
            vo.setTotalGoodsNum(goodsModel.getGoodsCount(example));
            //查询在售商品数
            example.setState(GoodsConst.GOODS_STATE_UPPER);
            vo.setOnSaleGoodsNum(goodsModel.getGoodsCount(example));
            vo.setChildren(getGoodsCategoryTree(webSite,goodsCategory.getCategoryId(), grade - 1));
            this.dealGoodsCategoryBindBrandAndAttribute(vo);
            vos.add(vo);
        });

        return vos;
    }

    /**
     * 处理三级分类绑定的品牌和属性
     *
     * @param vo
     */
    private void dealGoodsCategoryBindBrandAndAttribute(GoodsCategoryListVO vo) {
        if (vo.getGrade().equals(GoodsCategoryConst.CATEGORY_GRADE_3)) {
            //三级分类，查询绑定的品牌和属性
            GoodsCategoryBindBrandExample bindBrandExample = new GoodsCategoryBindBrandExample();
            bindBrandExample.setCategoryId(vo.getCategoryId());
            bindBrandExample.setOrderBy("bind_id asc");
            List<GoodsCategoryBindBrand> goodsCategoryBindBrandList = goodsCategoryBindBrandModel.getGoodsCategoryBindBrandList(bindBrandExample, null);
            List<GoodsCategoryListVO.GoodsBrandListVO> brandListVOS = new ArrayList<>();
            if (!CollectionUtils.isEmpty(goodsCategoryBindBrandList)) {
                goodsCategoryBindBrandList.forEach(goodsCategoryBindBrand -> {
                    GoodsBrand goodsBrand = goodsBrandModel.getGoodsBrandByBrandId(goodsCategoryBindBrand.getBrandId());
                    brandListVOS.add(new GoodsCategoryListVO.GoodsBrandListVO(goodsBrand));
                });
            }
            vo.setGoodsBrandList(brandListVOS);

            //属性
            GoodsCategoryBindAttributeExample bindAttributeExample = new GoodsCategoryBindAttributeExample();
            bindAttributeExample.setCategoryId(vo.getCategoryId());
            bindAttributeExample.setOrderBy("bind_id asc");
            List<GoodsCategoryBindAttribute> goodsCategoryBindAttributeList = goodsCategoryBindAttributeModel.getGoodsCategoryBindAttributeList(bindAttributeExample, null);
            List<GoodsCategoryListVO.GoodsAttributeListVO> attributeListVOS = new ArrayList<>();
            if (!CollectionUtils.isEmpty(goodsCategoryBindAttributeList)) {
                goodsCategoryBindAttributeList.forEach(goodsCategoryBindAttribute -> {
                    GoodsAttribute goodsAttribute = goodsAttributeModel.getGoodsAttributeByAttributeId(goodsCategoryBindAttribute.getAttributeId());
                    attributeListVOS.add(new GoodsCategoryListVO.GoodsAttributeListVO(goodsAttribute));
                });
            }
            vo.setGoodsAttributeList(attributeListVOS);
        }
    }

    @ApiOperation("分类绑定的属性,品牌列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类Id", required = true),
    })
    @GetMapping("getCategory")
    public JsonResult<GoodsCategoryBindVO> getCategory(HttpServletRequest request, @RequestParam(value = "categoryId") Integer categoryId) {
        AssertUtil.isTrue(categoryId < 1, "分类Id错误");
        GoodsCategoryBindVO goodsCategoryBindVO = new GoodsCategoryBindVO(getBrandList(categoryId), getAttributeList(categoryId));
        return SldResponse.success(goodsCategoryBindVO);
    }

    /**
     * 查询分类绑定的属性列表
     *
     * @param categoryId
     * @return
     */
    private List<GoodsAttributeVO> getAttributeList(Integer categoryId) {
        //查分类绑定的属性表
        GoodsCategoryBindAttributeExample example = new GoodsCategoryBindAttributeExample();
        example.setCategoryId(categoryId);
        List<GoodsCategoryBindAttribute> list = goodsCategoryBindAttributeModel.getGoodsCategoryBindAttributeList(example, null);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }

        StringBuffer attributeIds = new StringBuffer();
        list.forEach(goodsCategoryBindAttribute -> {
            attributeIds.append(",").append(goodsCategoryBindAttribute.getAttributeId());
        });
        //查属性表中的对应属性
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.setAttributeIdIn(attributeIds.toString().substring(1));
        goodsAttributeExample.setIsShow(GoodsConst.IS_ATTRIBUTE_YES);
        goodsAttributeExample.setOrderBy("sort asc, create_time desc");
        List<GoodsAttribute> goodsAttributeList = goodsAttributeModel.getGoodsAttributeList(goodsAttributeExample, null);
        if (CollectionUtils.isEmpty(goodsAttributeList)) {
            return new ArrayList<>();
        }

        List<GoodsAttributeVO> vos = new ArrayList<>();
        goodsAttributeList.forEach(attribute -> {
            //查属性值表
            GoodsAttributeValueExample goodsAttributeValueExample = new GoodsAttributeValueExample();
            goodsAttributeValueExample.setAttributeId(attribute.getAttributeId());
            List<GoodsAttributeValue> goodsAttributeValueList = goodsAttributeValueModel.getGoodsAttributeValueList(goodsAttributeValueExample, null);

            GoodsAttributeVO vo = new GoodsAttributeVO(attribute, goodsAttributeValueList);
            vos.add(vo);
        });
        return vos;
    }

    /**
     * 查询分类绑定的品牌
     *
     * @param categoryId
     * @return
     */
    private List<GoodsBrandVO> getBrandList(Integer categoryId) {
        GoodsCategoryBindBrandExample example = new GoodsCategoryBindBrandExample();
        example.setCategoryId(categoryId);
        List<GoodsCategoryBindBrand> list = goodsCategoryBindBrandModel.getGoodsCategoryBindBrandList(example, null);
        if (CollectionUtils.isEmpty(list)) {
            //未绑定品牌
            return new ArrayList<>();
        }

        StringBuffer brandIds = new StringBuffer();
        list.forEach(goodsCategoryBindBrand -> {
            brandIds.append(",").append(goodsCategoryBindBrand.getBrandId());
        });

        GoodsBrandExample goodsBrandExample = new GoodsBrandExample();
        goodsBrandExample.setBrandIdIn(brandIds.toString().substring(1));
        List<GoodsBrand> brandList = goodsBrandModel.getGoodsBrandList(goodsBrandExample, null);
        List<GoodsBrandVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(brandList)) {
            brandList.forEach(brand -> {
                GoodsBrandVO vo = new GoodsBrandVO(brand);
                vos.add(vo);
            });
        }
        return vos;
    }

    @ApiOperation("新增分类")
    @OperationLogger(option = "新增分类")
    @PostMapping("add")
    public JsonResult<Integer> addCategory(HttpServletRequest request, GoodsCategoryAddDTO goodsCategoryAddDTO,
                                           @RequestParam("seoTitle") String seoTitle,
                                           @RequestParam("seoDesc") String seoDesc,
                                           @RequestParam("seoKeyWords") String seoKeyWords) {
        String logMsg = "分类名称" + goodsCategoryAddDTO.getCategoryName();
        // 验证参数是否为空
        AssertUtil.notEmpty(goodsCategoryAddDTO.getCategoryName(), "分类名称不能为空，请重试！");
        AssertUtil.notNull(goodsCategoryAddDTO.getPid(), "上级分类不能为空，请重试！");
        AssertUtil.notNull(goodsCategoryAddDTO.getSort(), "分类排序不能为空，请重试！");
        if (!StringUtil.isNullOrZero(goodsCategoryAddDTO.getScaling())) {
            AssertUtil.isTrue(goodsCategoryAddDTO.getScaling().compareTo(BigDecimal.ONE) > 0
                    || goodsCategoryAddDTO.getScaling().compareTo(BigDecimal.ZERO) < 0, "请填写0到1之间的数字");
        }

        Admin admin = UserUtil.getUser(request, Admin.class);
        goodsCategoryModel.saveGoodsCategoryBindAttributeBrand(admin, goodsCategoryAddDTO,seoTitle,seoDesc,seoKeyWords);


        return SldResponse.success("添加成功", logMsg);
    }

    @ApiOperation("编辑分类")
    @OperationLogger(option = "编辑分类")
    @PostMapping("edit")
    public JsonResult editCategory(HttpServletRequest request, GoodsCategoryUpdateDTO goodsCategoryUpdateDTO,
                                   @RequestParam("seoTitle") String seoTitle,
                                   @RequestParam("seoDesc") String seoDesc,
                                   @RequestParam("seoKeyWords") String seoKeyWords) {
        String logMsg = "分类id" + goodsCategoryUpdateDTO.getCategoryId();
        // 验证参数是否为空
        AssertUtil.notNullOrZero(goodsCategoryUpdateDTO.getCategoryId(), "分类Id不能为空，请重试！");
        if (!StringUtil.isNullOrZero(goodsCategoryUpdateDTO.getScaling())) {
            AssertUtil.isTrue(goodsCategoryUpdateDTO.getScaling().compareTo(BigDecimal.ONE) > 0
                    || goodsCategoryUpdateDTO.getScaling().compareTo(BigDecimal.ZERO) < 0, "请填写0到1之间的数字");
        }

        Admin admin = UserUtil.getUser(request, Admin.class);
        goodsCategoryModel.updateGoodsCategoryBindAttributeBrand(admin, goodsCategoryUpdateDTO);

        //更新商品公共信息表分类路径数据
        goodsCategoryModel.updateGoodsCategoryPathInfo(goodsCategoryUpdateDTO);

        //更新商品特定规格表分类路径数据
        goodsCategoryModel.updateProductCategoryPathInfo(goodsCategoryUpdateDTO);

        //更新店铺申请商品分类路径数据
        goodsCategoryModel.updateStoreBindCategoryPathInfo(goodsCategoryUpdateDTO);

        int count = goodsCategoryModel.addAndUpdateSeoForGoodsCategory(goodsCategoryUpdateDTO,seoTitle,seoDesc,seoKeyWords,admin);
        if(count == 0){
            return SldResponse.fail("编辑seo表失败");
        }

        return SldResponse.success("编辑成功", logMsg);
    }

    @ApiOperation("删除分类")
    @OperationLogger(option = "删除分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类Id", required = true)
    })
    @PostMapping("del")
    public JsonResult deleteCategory(HttpServletRequest request, @RequestParam("categoryId") Integer categoryId) {
        AssertUtil.notNullOrZero(categoryId, "分类Id不能为空，请重试！");

        goodsCategoryModel.deleteGoodsCategoryBindAttributeBrand(categoryId);
        return SldResponse.success("删除分类成功");
    }

    @ApiOperation("获取商品分类列表接口")
    @GetMapping("categoryList")
    @ApiImplicitParams(@ApiImplicitParam(name = "webSite", value = "站点", paramType = "query"))
    public JsonResult<List<RankGoodsCategoryVO>> getCateTree(HttpServletRequest request,@RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        return SldResponse.success(this.getGoodsCategoryList(webSite, 0, 3));
    }

    /**
     * 获取商品分类树
     *
     * @param pId   父id
     * @param grade 获取级别，比如 pid=0,grade=3时，获取1、2、3级分类；pid=0,grade=2时，获取1、2级分类；pid=0,grade=1时，获取1级分类；
     * @return
     */
    private List<RankGoodsCategoryVO> getGoodsCategoryList(String webSite,Integer pId, Integer grade) {
        List<RankGoodsCategoryVO> vos = new ArrayList<>();
        GoodsCategoryExample example = new GoodsCategoryExample();
        example.setPid(pId);
        example.setWebSite(webSite);
        example.setQueryGrade(grade);
        example.setOrderBy("sort asc, create_time desc");
        List<GoodsCategory> goodsCategoryList = goodsCategoryModel.getGoodsCategoryList(example, null);
        if (CollectionUtils.isEmpty(goodsCategoryList)) {
            return vos;
        }
        goodsCategoryList.forEach(goodsCategory -> {
            RankGoodsCategoryVO vo = new RankGoodsCategoryVO(goodsCategory);
            vo.setChildren(getGoodsCategoryList(webSite,goodsCategory.getCategoryId(), grade - 1));
            vos.add(vo);
        });
        return vos;
    }

    @ApiOperation("初始化分类缓存")
    @OperationLogger(option = "初始化分类缓存")
    @ApiImplicitParams(@ApiImplicitParam(name = "webSite", value = "站点", paramType = "query"))
    @GetMapping("categoryInit")
    public JsonResult categoryInit(HttpServletRequest request, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        Admin admin = UserUtil.getUser(request, Admin.class);

        //缓存一级分类信息
        GoodsCategoryExample example = new GoodsCategoryExample();
        example.setPid(0);
        example.setWebSite(webSite);
        example.setState(GoodsCategoryConst.CATEGORY_STATE_1);
        example.setOrderBy("sort asc, create_time desc");
        List<GoodsCategory> list = goodsCategoryModel.getGoodsCategoryList(example, null);
        if (!CollectionUtils.isEmpty(list)) {
            List<FrontGoodsCategoryVO> vos = new ArrayList<>();
            for (GoodsCategory goodsCategory : list) {
                GoodsExample goodsExample = new GoodsExample();
                goodsExample.setCategoryId1(goodsCategory.getCategoryId());
//                Integer num = goodsModel.getGoodsCount(goodsExample);
//                if (StringUtil.isNullOrZero(num)) {
//                    //一级分类没有绑定商品则不缓存
//                    continue;
//                }
                vos.add(new FrontGoodsCategoryVO(goodsCategory));
            }
            //更新缓存中的数据
            stringRedisTemplate.opsForValue().set(RedisConst.GOODS_CATEGORY + "_" + webSite, JSONArray.toJSONString(vos));
        }

        //缓存全部分类信息
        if (!CollectionUtils.isEmpty(list)) {
            List<FrontGoodsCategoryVO> vos = new ArrayList<>();
            for (GoodsCategory goodsCategory : list) {
                FrontGoodsCategoryVO tree = new FrontGoodsCategoryVO(goodsCategory);
                tree = categoryTree(tree, goodsCategory.getCategoryId());
                if (CollectionUtils.isEmpty(tree.getChildren())) {
                    continue;
                }
                vos.add(tree);
            }
            stringRedisTemplate.opsForValue().set(RedisConst.FRONT_GOODS_CATEGORY + "_" + webSite, JSONArray.toJSONString(vos));
        }
        return SldResponse.success("缓存更新成功");
    }

    /**
     * 构造分类树
     *
     * @param tree
     * @param categoryId
     * @return
     */
    public FrontGoodsCategoryVO categoryTree(FrontGoodsCategoryVO tree, Integer categoryId) {
        //其他一级分类,只展示分类树,不展示其下商品
        //查询其二级
        GoodsCategoryExample example2 = new GoodsCategoryExample();
        example2.setPid(categoryId);
        example2.setState(GoodsCategoryConst.CATEGORY_STATE_1);
        example2.setOrderBy("sort asc, create_time desc");
        List<GoodsCategory> list2 = goodsCategoryModel.getGoodsCategoryList(example2, null);
        //构造二级列表
        List<FrontGoodsCategoryVO> vos2 = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list2)) {
            for (GoodsCategory goodsCategory2 : list2) {
                FrontGoodsCategoryVO tree2 = new FrontGoodsCategoryVO(goodsCategory2);
                //没有图片就用默认图片
                if (StringUtils.isEmpty(goodsCategory2.getCategoryImage())) {
                    tree2.setCategoryImage(FileUrlUtil.getFileUrl(stringRedisTemplate.opsForValue().get("default_goods_cate_grade2_image"), null));
                }
                //查询三级分类列表
                GoodsCategoryExample example3 = new GoodsCategoryExample();
                example3.setPid(goodsCategory2.getCategoryId());
                example3.setState(GoodsCategoryConst.CATEGORY_STATE_1);
                example3.setOrderBy("sort asc, create_time desc");
                List<GoodsCategory> list3 = goodsCategoryModel.getGoodsCategoryList(example3, null);
                //构造每个二级的三级列表
                List<FrontGoodsCategoryVO> vos3 = new ArrayList<>();
                if (!CollectionUtils.isEmpty(list3)) {
                    for (GoodsCategory goodsCategory3 : list3) {
                        GoodsExample goodsExample = new GoodsExample();
                        goodsExample.setCategoryId3(goodsCategory3.getCategoryId());
//                        Integer num = goodsModel.getGoodsCount(goodsExample);
//                        if (StringUtil.isNullOrZero(num)) {
//                            //三级分类没有绑定商品则不缓存
//                            continue;
//                        }
                        FrontGoodsCategoryVO tree3 = new FrontGoodsCategoryVO(goodsCategory3);
                        //没有图片就用默认图片
                        if (StringUtils.isEmpty(goodsCategory3.getCategoryImage())) {
                            tree3.setCategoryImage(FileUrlUtil.getFileUrl(stringRedisTemplate.opsForValue().get("default_goods_cate_grade3_image"), null));
                        }
                        vos3.add(tree3);
                    }
                }
//                if (CollectionUtils.isEmpty(vos3)) {
//                    continue;
//                }
                tree2.setChildren(vos3);
                vos2.add(tree2);
            }
        }
        tree.setChildren(vos2);
        return tree;
    }

    @ApiOperation("根据一级分类id获取二三级分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId1", value = "一级分类Id", required = true),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("bottomCategory")
    public JsonResult<List<FrontGoodsCategoryVO>> bottomCategory(HttpServletRequest request, Integer categoryId1, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        List<FrontGoodsCategoryVO> vos = new ArrayList<>();

        //查询redis缓存
        String dataJson = stringRedisTemplate.opsForValue().get(RedisConst.FRONT_GOODS_CATEGORY + "_" + webSite);
        if (!StringUtils.isEmpty(dataJson)) {
            JSONArray jsonArray = JSONArray.parseArray(dataJson);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Integer categoryId = jsonObject.getInteger("categoryId");
                if (categoryId1.equals(categoryId)) {
                    JSONArray array2 = JSONArray.parseArray(jsonObject.getString("children"));
                    if (!CollectionUtils.isEmpty(array2)) {
                        for (int j = 0; j < array2.size(); j++) {
                            JSONObject object = array2.getJSONObject(j);
                            FrontGoodsCategoryVO categoryVO = new FrontGoodsCategoryVO();
                            categoryVO.setWebSite(object.getString("webSite"));
                            categoryVO.setCategoryId(object.getInteger("categoryId"));
                            categoryVO.setCategoryName(object.getString("categoryName"));
                            categoryVO.setPid(object.getInteger("pid"));
                            categoryVO.setGrade(object.getInteger("grade"));
                            JSONArray array3 = JSONArray.parseArray(object.getString("children"));
                            List<FrontGoodsCategoryVO> children = new ArrayList<>();
                            if (!CollectionUtils.isEmpty(array3)) {
                                for (int k = 0; k < array3.size(); k++) {
                                    JSONObject jsonObject2 = array3.getJSONObject(k);
                                    FrontGoodsCategoryVO goodsCategoryVO = new FrontGoodsCategoryVO();
                                    goodsCategoryVO.setCategoryId(jsonObject2.getInteger("categoryId"));
                                    goodsCategoryVO.setCategoryName(jsonObject2.getString("categoryName"));
                                    goodsCategoryVO.setPid(jsonObject2.getInteger("pid"));
                                    goodsCategoryVO.setGrade(jsonObject2.getInteger("grade"));
                                    children.add(goodsCategoryVO);
                                }
                            }
                            categoryVO.setChildren(children);
                            vos.add(categoryVO);
                        }
                    }
                    break;
                }
            }
        }
        return SldResponse.success(vos);
    }
}
