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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.slodon.b2b2c.core.constant.GoodsCategoryConst;
import com.slodon.b2b2c.core.constant.RedisConst;
import com.slodon.b2b2c.core.constant.StoreConst;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.FileUrlUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.goods.example.GoodsCategoryExample;
import com.slodon.b2b2c.goods.pojo.GoodsCategory;
import com.slodon.b2b2c.model.goods.GoodsCategoryModel;
import com.slodon.b2b2c.model.seller.StoreBindCategoryModel;
import com.slodon.b2b2c.seller.example.StoreBindCategoryExample;
import com.slodon.b2b2c.seller.pojo.StoreBindCategory;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.vo.goods.FrontGoodsCategoryVO;
import com.slodon.b2b2c.vo.goods.GoodsCategoryListVO;
import com.slodon.b2b2c.vo.goods.SellerGoodsCategoryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author slodon
 */
@Api(tags = "seller商品分类")
@RestController
@RequestMapping("v3/goods/seller/goodsCategory")
public class GoodsCategorySellerController {

    @Resource
    private GoodsCategoryModel goodsCategoryModel;
    @Resource
    private StoreBindCategoryModel storeBindCategoryModel;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("分类列表,获取当前分类的下级分类，0代表获取所有1级分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "分类Id(一级不传，二三级必传)", paramType = "query"),
            @ApiImplicitParam(name = "grade", value = "分类级别: 1-一级，2-二级，3-三级", defaultValue = "1", required = true)
    })
    @GetMapping("list")
    public JsonResult<List<SellerGoodsCategoryVO>> getList(HttpServletRequest request,
                                                           @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite,
                                                           Integer categoryId,
                                                           @RequestParam(value = "grade", defaultValue = "1") Integer grade) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        List<SellerGoodsCategoryVO> vos = new ArrayList<>();
        //根据店铺类型获取分类
        if (vendor.getStore().getIsOwnStore().equals(StoreConst.IS_OWN_STORE)) {
            //自营店铺，获取所有可用的分类
            GoodsCategoryExample example = new GoodsCategoryExample();
            if (grade == GoodsCategoryConst.CATEGORY_GRADE_1) {
                example.setPid(0);
            } else {
                example.setPid(categoryId);
            }
            example.setState(GoodsCategoryConst.CATEGORY_STATE_1);
            example.setWebSite(webSite);
            example.setOrderBy("sort asc");
            List<GoodsCategory> list = goodsCategoryModel.getGoodsCategoryList(example, null);
            if (!CollectionUtils.isEmpty(list)) {
                list.forEach(goodsCategory -> {
                    vos.add(new SellerGoodsCategoryVO(goodsCategory));
                });
            }
        } else {
            //入驻店铺，获取审核通过的分类
            String fields;
            StoreBindCategoryExample example = new StoreBindCategoryExample();
            example.setStoreId(vendor.getStoreId());
            example.setWebSite(webSite);
            example.setState(StoreConst.STORE_CATEGORY_STATE_PASS);
            if (grade == GoodsCategoryConst.CATEGORY_GRADE_1) {
                fields = "goods_category_id1";
            } else if (grade == GoodsCategoryConst.CATEGORY_GRADE_2) {
                fields = "goods_category_id2";
                example.setGoodsCategoryId1(categoryId);
            } else {
                fields = "goods_category_id3";
                example.setGoodsCategoryId2(categoryId);
            }
            example.setGroupBy(fields);
            example.setOrderBy(fields + " DESC");
            List<StoreBindCategory> list = storeBindCategoryModel.getStoreBindCategoryList(fields, example);
            if (!CollectionUtils.isEmpty(list)) {
                for (StoreBindCategory bindCategory : list) {
                    Integer goodsCategoryId;
                    if (grade == GoodsCategoryConst.CATEGORY_GRADE_1) {
                        goodsCategoryId = bindCategory.getGoodsCategoryId1();
                    } else if (grade == GoodsCategoryConst.CATEGORY_GRADE_2) {
                        goodsCategoryId = bindCategory.getGoodsCategoryId2();
                    } else {
                        goodsCategoryId = bindCategory.getGoodsCategoryId3();
                    }
                    GoodsCategory goodsCategory = goodsCategoryModel.getGoodsCategoryByCategoryId(goodsCategoryId);
                    if (goodsCategory == null) {
                        continue;
                    }
                    vos.add(new SellerGoodsCategoryVO(goodsCategory));
                }
            }
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("逐级获取分类列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类Id", paramType = "query", required = true),
            @ApiImplicitParam(name = "grade", value = "分类级别: 1-一级，2-二级，3-三级", paramType = "query", required = true)
    })
    @GetMapping("listByPId")
    public JsonResult<List<FrontGoodsCategoryVO>> listByPId(HttpServletRequest request,
                                                            @RequestParam(value = "categoryId", defaultValue = "0") Integer categoryId,
                                                            @RequestParam(value = "grade", defaultValue = "1") Integer grade,
                                                            @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);
                if (grade == GoodsCategoryConst.CATEGORY_GRADE_1) {
                    FrontGoodsCategoryVO vo = new FrontGoodsCategoryVO();
                    vo.setCategoryId(jsonObject.getInteger("categoryId"));
                    vo.setCategoryName(jsonObject.getString("categoryName"));
                    vo.setPid(jsonObject.getInteger("pid"));
                    vo.setGrade(jsonObject.getInteger("grade"));
                    JSONArray array = JSONArray.parseArray(jsonObject.getString("children"));
                    vo.setChildren(!CollectionUtils.isEmpty(array) ? new ArrayList<>() : null);
                    vos.add(vo);
                } else if (grade == GoodsCategoryConst.CATEGORY_GRADE_2) {
                    JSONArray array2 = JSONArray.parseArray(jsonObject.getString("children"));
                    if (!CollectionUtils.isEmpty(array2)) {
                        for (int j = 0; j < array2.size(); j++) {
                            JSONObject object = array2.getJSONObject(j);
                            Integer pid = object.getInteger("pid");
                            if (pid.equals(categoryId)) {
                                FrontGoodsCategoryVO vo = new FrontGoodsCategoryVO();
                                vo.setCategoryId(object.getInteger("categoryId"));
                                vo.setCategoryName(object.getString("categoryName"));
                                vo.setPid(object.getInteger("pid"));
                                vo.setGrade(object.getInteger("grade"));
                                JSONArray array3 = JSONArray.parseArray(object.getString("children"));
                                vo.setChildren(!CollectionUtils.isEmpty(array3) ? new ArrayList<>() : null);
                                vos.add(vo);
                            }
                        }
                    }
                } else {
                    JSONArray array2 = JSONArray.parseArray(jsonObject.getString("children"));
                    if (!CollectionUtils.isEmpty(array2)) {
                        for (int j = 0; j < array2.size(); j++) {
                            JSONObject object = array2.getJSONObject(j);
                            Integer categoryId2 = object.getInteger("categoryId");
                            if (categoryId2.equals(categoryId)) {
                                JSONArray array3 = JSONArray.parseArray(object.getString("children"));
                                if (!CollectionUtils.isEmpty(array3)) {
                                    for (int k = 0; k < array3.size(); k++) {
                                        JSONObject jsonObject1 = array3.getJSONObject(k);
                                        FrontGoodsCategoryVO vo = new FrontGoodsCategoryVO();
                                        vo.setCategoryId(jsonObject1.getInteger("categoryId"));
                                        vo.setCategoryName(jsonObject1.getString("categoryName"));
                                        vo.setPid(jsonObject1.getInteger("pid"));
                                        vo.setGrade(jsonObject1.getInteger("grade"));
                                        vo.setChildren(null);
                                        vos.add(vo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("获取分类列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query")
    })
    @GetMapping("getCateList")
    public JsonResult<List<GoodsCategoryListVO>> getCateList(HttpServletRequest request,@RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        //店铺申请经营类目和商户入驻选择经营类目用到此接口
        GoodsCategoryExample example = new GoodsCategoryExample();
        example.setWebSite(webSite);
        example.setState(GoodsCategoryConst.CATEGORY_STATE_1);
        example.setGrade(GoodsCategoryConst.CATEGORY_GRADE_3);
        List<GoodsCategory> list = goodsCategoryModel.getGoodsCategoryList(example, null);
        List<GoodsCategoryListVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            Map<Integer, List<GoodsCategoryListVO>> secondMap = new HashedMap();
            list.forEach(goodsCategory -> {
                List<StoreBindCategory> storeBindCategoryList = new ArrayList<>();
                //店铺id为空，遍历全部有三级的分类（店铺申请入驻-经营类目查询）
                if (!StringUtil.isNullOrZero(vendor.getStoreId())) {
                    StoreBindCategoryExample bindCategoryExample = new StoreBindCategoryExample();
                    bindCategoryExample.setGoodsCategoryId3(goodsCategory.getCategoryId());
                    bindCategoryExample.setStoreId(vendor.getStoreId());
                    bindCategoryExample.setState(StoreConst.STORE_CATEGORY_STATE_PASS);
                    storeBindCategoryList = storeBindCategoryModel.getStoreBindCategoryList(bindCategoryExample, null);
                }
                if (CollectionUtils.isEmpty(storeBindCategoryList)) {
                    if (secondMap.containsKey(goodsCategory.getPid())) {
                        secondMap.get(goodsCategory.getPid()).add(new GoodsCategoryListVO(goodsCategory));
                    } else {
                        List<GoodsCategoryListVO> thirdVos = new ArrayList<>();
                        thirdVos.add(new GoodsCategoryListVO(goodsCategory));
                        secondMap.put(goodsCategory.getPid(), thirdVos);
                    }
                }

            });
            List<GoodsCategoryListVO> secondVos = new ArrayList<>();
            secondMap.forEach((cateId2, cate3List) -> {
                GoodsCategory goodsCategory2 = goodsCategoryModel.getGoodsCategoryByCategoryId(cateId2);
                GoodsCategoryListVO vo = new GoodsCategoryListVO(goodsCategory2);
                vo.setChildren(cate3List);
                secondVos.add(vo);
            });
            //一级id和二级列表
            Map<Integer, List<GoodsCategoryListVO>> thirdMap = new HashedMap();
            secondVos.forEach(categoryListVO -> {
                if (thirdMap.containsKey(categoryListVO.getPid())) {
                    thirdMap.get(categoryListVO.getPid()).add(categoryListVO);
                } else {
                    ArrayList<GoodsCategoryListVO> listVoS = new ArrayList<>();
                    listVoS.add(categoryListVO);
                    thirdMap.put(categoryListVO.getPid(), listVoS);
                }
            });
            thirdMap.forEach((cateId1, cate2List) -> {
                GoodsCategory goodCategory1 = goodsCategoryModel.getGoodsCategoryByCategoryId(cateId1);
                GoodsCategoryListVO vo = new GoodsCategoryListVO(goodCategory1);
                vo.setChildren(cate2List);
                vos.add(vo);
            });
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("根据一级分类id获取二三级分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId1", value = "一级分类Id", required = true)
    })
    @GetMapping("bottomCategory")
    public JsonResult<List<FrontGoodsCategoryVO>> bottomCategory(HttpServletRequest request, Integer categoryId1,String webSite) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        List<FrontGoodsCategoryVO> vos = new ArrayList<>();
        //根据店铺类型获取分类
        if (vendor.getStore().getIsOwnStore().equals(StoreConst.IS_OWN_STORE)) {
            //查询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.setWebSite(jsonObject2.getString("webSite"));
                                        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;
                    }
                }
            }
        } else {
            //入驻店铺，获取审核通过的分类
            StoreBindCategoryExample example = new StoreBindCategoryExample();
            example.setStoreId(vendor.getStoreId());
            example.setGoodsCategoryId1(categoryId1);
            example.setWebSite(webSite);
            example.setState(StoreConst.STORE_CATEGORY_STATE_PASS);
            List<StoreBindCategory> list = storeBindCategoryModel.getStoreBindCategoryList(example, null);
            //key-二级分类id， value-二级分类名称
            Map<Integer, String> map = new HashMap<>(16);
            //三级分类列表
            List<GoodsCategory> thirdList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(list)) {
                list.forEach(storeBindCategory -> {
                    if (!map.containsKey(storeBindCategory.getGoodsCategoryId2())) {
                        //3C数码>电脑整机>服务器
                        String[] goodsCateName = storeBindCategory.getGoodsCateName().split(">");
                        map.put(storeBindCategory.getGoodsCategoryId2(), goodsCateName[1]);
                    }
                    GoodsCategory goodsCategory = goodsCategoryModel.getGoodsCategoryByCategoryId(storeBindCategory.getGoodsCategoryId3());
                    if (goodsCategory != null) {
                        thirdList.add(goodsCategory);
                    }
                });
            }
            if (!CollectionUtils.isEmpty(thirdList)) {
                //key-二级分类id， value-三级分类列表
                Map<Integer, List<FrontGoodsCategoryVO>> secondMap = new LinkedHashMap<>();
                thirdList.forEach(goodsCategory -> {
                    if (secondMap.containsKey(goodsCategory.getPid())) {
                        FrontGoodsCategoryVO categoryVO = new FrontGoodsCategoryVO();
                        categoryVO.setWebSite(webSite);
                        categoryVO.setCategoryId(goodsCategory.getCategoryId());
                        categoryVO.setCategoryName(goodsCategory.getCategoryName());
                        categoryVO.setPid(goodsCategory.getCategoryId());
                        categoryVO.setGrade(goodsCategory.getGrade());
                        secondMap.get(goodsCategory.getPid()).add(categoryVO);
                    } else {
                        List<FrontGoodsCategoryVO> thirdVos = new ArrayList<>();
                        FrontGoodsCategoryVO categoryVO = new FrontGoodsCategoryVO();
                        categoryVO.setWebSite(webSite);
                        categoryVO.setCategoryId(goodsCategory.getCategoryId());
                        categoryVO.setCategoryName(goodsCategory.getCategoryName());
                        categoryVO.setPid(goodsCategory.getCategoryId());
                        categoryVO.setGrade(goodsCategory.getGrade());
                        thirdVos.add(categoryVO);
                        secondMap.put(goodsCategory.getPid(), thirdVos);
                    }
                });
                secondMap.forEach((cateId2, cate3List) -> {
                    FrontGoodsCategoryVO vo = new FrontGoodsCategoryVO();
                    vo.setCategoryId(cateId2);
                    vo.setCategoryName(map.get(cateId2));
                    vo.setPid(categoryId1);
                    vo.setGrade(GoodsCategoryConst.CATEGORY_GRADE_2);
                    vo.setChildren(cate3List);
                    vos.add(vo);
                });
            }
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("获取品牌分类列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query")
    })
    @GetMapping("getStoreCateList")
    public JsonResult<List<FrontGoodsCategoryVO>> getStoreCateList(HttpServletRequest request, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        List<FrontGoodsCategoryVO> vos = new ArrayList<>();
        if (vendor.getStore().getIsOwnStore().equals(StoreConst.IS_OWN_STORE)) {
            //一级分类信息
            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);

            //只获取一级分类，children设置为空集合
            if (!CollectionUtils.isEmpty(list)) {
                for (GoodsCategory goodsCategory : list) {
                    FrontGoodsCategoryVO vo = new FrontGoodsCategoryVO(goodsCategory);
                    // 设置children为空集合而不是null
                    vo.setChildren(new ArrayList<>());
                    vos.add(vo);
                }
            }
        } else {
            //入驻店铺，获取审核通过的分类
            StoreBindCategoryExample example = new StoreBindCategoryExample();
            example.setStoreId(vendor.getStoreId());
            example.setWebSite(webSite);
            example.setState(StoreConst.STORE_CATEGORY_STATE_PASS);
            List<StoreBindCategory> list = storeBindCategoryModel.getStoreBindCategoryList(example, null);

            //只获取一级分类，children设置为空集合
            if (!CollectionUtils.isEmpty(list)) {
                // 提取所有一级分类ID并去重
                Set<Integer> firstLevelIdSet = new HashSet<>();
                for (StoreBindCategory bindCategory : list) {
                    firstLevelIdSet.add(bindCategory.getGoodsCategoryId1());
                }

                // 批量查询一级分类
                StringBuilder firstLevelIdsBuilder = new StringBuilder();
                for (Integer id : firstLevelIdSet) {
                    if (firstLevelIdsBuilder.length() > 0) {
                        firstLevelIdsBuilder.append(",");
                    }
                    firstLevelIdsBuilder.append(id);
                }
                String firstLevelIds = firstLevelIdsBuilder.toString();

                GoodsCategoryExample firstExample = new GoodsCategoryExample();
                firstExample.setCategoryIdIn(firstLevelIds);
                List<GoodsCategory> firstLevelCategories = goodsCategoryModel.getGoodsCategoryList(firstExample, null);

                // 构建返回结果，children设置为空集合
                for (GoodsCategory firstCategory : firstLevelCategories) {
                    FrontGoodsCategoryVO vo = new FrontGoodsCategoryVO(firstCategory);
                    // 设置children为空集合而不是null
                    vo.setChildren(new ArrayList<>());
                    vos.add(vo);
                }
            }
        }

        return SldResponse.success(vos);
    }


}
