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

import cn.hutool.core.date.DateUtil;
import com.slodon.b2b2c.aop.OperationLogger;
import com.slodon.b2b2c.business.dto.OrderProductDTO;
import com.slodon.b2b2c.core.constant.GoodsCategoryConst;
import com.slodon.b2b2c.core.constant.GoodsConst;
import com.slodon.b2b2c.core.constant.GoodsRankConst;
import com.slodon.b2b2c.core.controller.BaseController;
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.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.goods.dto.GoodsCommentDTO;
import com.slodon.b2b2c.goods.dto.GoodsRankDTO;
import com.slodon.b2b2c.goods.dto.RankConditionDTO;
import com.slodon.b2b2c.goods.example.GoodsBindRankExample;
import com.slodon.b2b2c.goods.example.GoodsCommentExample;
import com.slodon.b2b2c.goods.example.GoodsExample;
import com.slodon.b2b2c.goods.example.GoodsRankExample;
import com.slodon.b2b2c.goods.pojo.Goods;
import com.slodon.b2b2c.goods.pojo.GoodsBindRank;
import com.slodon.b2b2c.goods.pojo.GoodsCategory;
import com.slodon.b2b2c.goods.pojo.GoodsRank;
import com.slodon.b2b2c.model.goods.GoodsBindRankModel;
import com.slodon.b2b2c.model.goods.GoodsCategoryModel;
import com.slodon.b2b2c.model.goods.GoodsModel;
import com.slodon.b2b2c.model.goods.GoodsRankModel;
import com.slodon.b2b2c.system.pojo.Admin;
import com.slodon.b2b2c.vo.goods.GoodsRankDetailVO;
import com.slodon.b2b2c.vo.goods.GoodsRankVO;
import com.slodon.b2b2c.vo.goods.RankGoodsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

@Api(tags = "admin-榜单列表")
@RestController
@RequestMapping("v3/goods/admin/goods/rank")
public class AdminGoodsRankController extends BaseController {

    @Resource
    private GoodsRankModel goodsRankModel;
    @Resource
    private GoodsBindRankModel goodsBindRankModel;
    @Resource
    private GoodsModel goodsModel;
    @Resource
    private GoodsCategoryModel goodsCategoryModel;

    @ApiOperation("榜单列表(查看榜单)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类id(查看榜单必传)", paramType = "query"),
            @ApiImplicitParam(name = "rankName", value = "榜单名称", paramType = "query"),
            @ApiImplicitParam(name = "rankType", value = "榜单类型：1-畅销榜；2-好评榜；3-新品榜；4-自定义", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<GoodsRankVO>> list(HttpServletRequest request, Integer categoryId, String rankName, Integer rankType) {
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        GoodsRankExample example = new GoodsRankExample();
        example.setCategoryId(categoryId);
        example.setRankNameLike(rankName);
        example.setRankType(rankType);
        List<GoodsRank> list = goodsRankModel.getGoodsRankList(example, pager);
        List<GoodsRankVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(category -> {
                vos.add(new GoodsRankVO(category));
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("榜单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rankId", value = "榜单id", required = true),
    })
    @GetMapping("detail")
    public JsonResult<GoodsRankDetailVO> detail(HttpServletRequest request, Integer rankId) {
        GoodsRank goodsRank = goodsRankModel.getGoodsRankByRankId(rankId);
        AssertUtil.notNull(goodsRank, "榜单不存在");
        GoodsRankDetailVO detailVO = new GoodsRankDetailVO(goodsRank);
        return SldResponse.success(detailVO);
    }

    @ApiOperation("榜单商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rankId", value = "榜单id", required = true),
    })
    @GetMapping("rankGoods")
    public JsonResult<List<RankGoodsVO>> rankGoods(HttpServletRequest request, Integer rankId) {
        GoodsRank goodsRank = goodsRankModel.getGoodsRankByRankId(rankId);
        AssertUtil.notNull(goodsRank, "榜单不存在");
        GoodsBindRankExample example = new GoodsBindRankExample();
        example.setRankId(rankId);
        example.setOrderBy("goods_rank ASC");
        List<GoodsBindRank> list = goodsBindRankModel.getGoodsBindRankList(example, null);
        List<RankGoodsVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            //非自定义榜
            if (goodsRank.getRankType() != GoodsRankConst.RANK_TYPE_4) {
                list.forEach(goodsBindRank -> {
                    Goods goods = goodsModel.getGoodsByGoodsId(goodsBindRank.getGoodsId());
                    AssertUtil.notNull(goods, "商品不存在");
                    vos.add(new RankGoodsVO(goods, goodsBindRank));
                });
            } else {
                //key-商品id，value-商品对象
                Map<Long, Goods> goodsMap = new HashMap<>();
                //key-商品id，value-销售额
                Map<Long, BigDecimal> saleAmountMap = new HashMap<>();
                StringBuilder goodsIds = new StringBuilder();
                list.forEach(goodsBindRank -> {
                    Goods goods = goodsModel.getGoodsByGoodsId(goodsBindRank.getGoodsId());
                    AssertUtil.notNull(goods, "商品不存在");
                    goodsIds.append(",").append(goods.getGoodsId());
                    goodsMap.put(goods.getGoodsId(), goods);
                });
                //查询商品销售额
                List<OrderProductDTO> productList = goodsRankModel.getGoodsSaleList(goodsIds.toString().substring(1));
                productList.forEach(product -> {
                    saleAmountMap.put(product.getGoodsId(), product.getSaleAmount());
                });
                list.forEach(goodsBindRank -> {
                    Goods goods = goodsMap.get(goodsBindRank.getGoodsId());
                    RankGoodsVO vo = new RankGoodsVO(goods, goodsBindRank);
                    vo.setSaleAmount(saleAmountMap.getOrDefault(goodsBindRank.getGoodsId(), BigDecimal.ZERO));
                    vos.add(vo);
                });
            }
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("加载榜单商品")
    @GetMapping("loadRankGoods")
    public JsonResult<PageVO<RankGoodsVO>> loadRankGoods(HttpServletRequest request, RankConditionDTO rankConditionDTO) {
        AssertUtil.notNullOrZero(rankConditionDTO.getRankType(), "请选择榜单类型");

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        List<RankGoodsVO> vos = new ArrayList<>();
        //查询商品列表
        GoodsExample example = new GoodsExample();
        example.setState(GoodsConst.GOODS_STATE_UPPER);
        example.setGoodsNameLike(rankConditionDTO.getGoodsName());
        example.setStoreNameLike(rankConditionDTO.getStoreName());
        //根据榜单类型校验参数
        if (rankConditionDTO.getRankType() != GoodsRankConst.RANK_TYPE_4) {
            AssertUtil.notNullOrZero(rankConditionDTO.getGoodsCategoryId(), "请选择商品分类");
            AssertUtil.notNullOrZero(rankConditionDTO.getStatsTime(), "请选择统计时间");

            GoodsCategory goodsCategory = goodsCategoryModel.getGoodsCategoryByCategoryId(rankConditionDTO.getGoodsCategoryId());
            AssertUtil.notNull(goodsCategory, "获取分类信息为空");
            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());
            }
            //根据统计时间类型确定查询时间范围
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date startTime;
            Date endTime = DateUtil.endOfDay(calendar.getTime());
            if (rankConditionDTO.getStatsTime() == GoodsRankConst.STATS_TIME_2) {
                calendar.add(Calendar.DAY_OF_MONTH, -29);
                startTime = DateUtil.beginOfDay(calendar.getTime());
            } else {
                calendar.add(Calendar.DAY_OF_MONTH, -6);
                startTime = DateUtil.beginOfDay(calendar.getTime());
            }
            if (rankConditionDTO.getRankType() == GoodsRankConst.RANK_TYPE_1) {
                AssertUtil.notNullOrZero(rankConditionDTO.getBestSellerRankRule(), "请选择计算规则");

                List<Goods> list = goodsModel.getGoodsList(example, null);
                if (CollectionUtils.isEmpty(list)) {
                    return SldResponse.success(new PageVO<>(vos, pager));
                }
                //key-商品id，value-商品对象
                Map<Long, Goods> goodsMap = new HashMap<>();
                StringBuilder goodsIds = new StringBuilder();
                list.forEach(goods -> {
                    goodsIds.append(",").append(goods.getGoodsId());
                    goodsMap.put(goods.getGoodsId(), goods);
                });
                //畅销榜
                List<OrderProductDTO> productList = goodsRankModel.getGoodsListByBestSellerRankRule(goodsIds.toString().substring(1),
                        startTime, endTime, rankConditionDTO.getBestSellerRankRule(), pager);
                if (!CollectionUtils.isEmpty(productList)) {
                    productList.forEach(product -> {
                        Goods goods = goodsMap.get(product.getGoodsId());
                        RankGoodsVO vo = new RankGoodsVO(goods, null);
                        vo.setSaleNum(product.getSaleNum());
                        vo.setSaleAmount(product.getSaleAmount());
                        vos.add(vo);
                    });
                }
            } else if (rankConditionDTO.getRankType() == GoodsRankConst.RANK_TYPE_2) {
                AssertUtil.notNullOrZero(rankConditionDTO.getHighCommentNum(), "请输入好评数");
                AssertUtil.notNullOrZero(rankConditionDTO.getHighCommentRate(), "请输入好评率");

                List<Goods> list = goodsModel.getGoodsList(example, null);
                if (CollectionUtils.isEmpty(list)) {
                    return SldResponse.success(new PageVO<>(vos, pager));
                }
                //key-商品id，value-商品对象
                Map<Long, Goods> goodsMap = new HashMap<>();
                StringBuilder goodsIds = new StringBuilder();
                list.forEach(goods -> {
                    goodsIds.append(",").append(goods.getGoodsId());
                    goodsMap.put(goods.getGoodsId(), goods);
                });
                //好评榜
                GoodsCommentExample commentExample = new GoodsCommentExample();
                commentExample.setGoodsIdIn(goodsIds.toString().substring(1));
                commentExample.setCreateTimeAfter(startTime);
                commentExample.setCreateTimeBefore(endTime);
                commentExample.setHighNum(rankConditionDTO.getHighCommentNum());
                commentExample.setHighPercent(new BigDecimal(rankConditionDTO.getHighCommentRate()).divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
                commentExample.setGoodsNameLike(rankConditionDTO.getGoodsName());
                commentExample.setStoreNameLike(rankConditionDTO.getStoreName());
                List<GoodsCommentDTO> commentList = goodsRankModel.getGoodsListByHighRankRule(commentExample, pager);
                if (!CollectionUtils.isEmpty(commentList)) {
                    commentList.forEach(goodsComment -> {
                        Goods goods = goodsMap.get(goodsComment.getGoodsId());
                        RankGoodsVO vo = new RankGoodsVO(goods, null);
                        vo.setHighNum(goodsComment.getHighNum());
                        vo.setHighRate(goodsComment.getHighPercent().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%");
                        vos.add(vo);
                    });
                }
            } else if (rankConditionDTO.getRankType() == GoodsRankConst.RANK_TYPE_3) {
                AssertUtil.notNullOrZero(rankConditionDTO.getNewProductRankRule(), "请选择计算规则");

                example.setCreateTimeAfter(startTime);
                example.setCreateTimeBefore(endTime);
                if (rankConditionDTO.getNewProductRankRule() == GoodsRankConst.NEW_PRODUCT_RANK_RULE_2) {
                    example.setOrderBy("create_time ASC");
                } else {
                    example.setOrderBy("create_time DESC");
                }
                List<Goods> list = goodsModel.getGoodsList(example, pager);
                if (!CollectionUtils.isEmpty(list)) {
                    list.forEach(goods -> {
                        vos.add(new RankGoodsVO(goods, null));
                    });
                }
            }
        } else {
            example.setBrandNameLike(rankConditionDTO.getBrandName());
            if (!StringUtil.isNullOrZero(rankConditionDTO.getGoodsCategoryId())) {
                GoodsCategory goodsCategory = goodsCategoryModel.getGoodsCategoryByCategoryId(rankConditionDTO.getGoodsCategoryId());
                AssertUtil.notNull(goodsCategory, "获取分类信息为空");
                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.setOrderBy("actual_sales DESC");
            List<Goods> list = goodsModel.getGoodsList(example, pager);
            if (!CollectionUtils.isEmpty(list)) {
                //拼接商品id
                StringBuilder goodsIds = new StringBuilder();
                list.forEach(goods -> {
                    goodsIds.append(",").append(goods.getGoodsId());
                });
                //key-商品id，value-销售额
                Map<Long, BigDecimal> saleAmountMap = new HashMap<>();
                List<OrderProductDTO> productList = goodsRankModel.getGoodsSaleList(goodsIds.toString().substring(1));
                productList.forEach(product -> {
                    saleAmountMap.put(product.getGoodsId(), product.getSaleAmount());
                });
                list.forEach(goods -> {
                    RankGoodsVO vo = new RankGoodsVO(goods, null);
                    vo.setSaleAmount(saleAmountMap.getOrDefault(goods.getGoodsId(), BigDecimal.ZERO));
                    vos.add(vo);
                });
            }
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("新建排行榜")
    @OperationLogger(option = "新建排行榜")
    @PostMapping("add")
    public JsonResult addGoodsRank(HttpServletRequest request, @RequestBody GoodsRankDTO goodsRankDTO) {
        AssertUtil.sortCheck(goodsRankDTO.getSort());
        AssertUtil.notNullOrZero(goodsRankDTO.getRankType(), "请选择榜单类型");

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

        //根据榜单类型校验参数
        GoodsRank goodsRank = new GoodsRank();
        if (goodsRankDTO.getRankType() != GoodsRankConst.RANK_TYPE_4) {
            AssertUtil.notNullOrZero(goodsRankDTO.getGoodsCategoryId(), "请选择商品分类");
            AssertUtil.notNullOrZero(goodsRankDTO.getStatsTime(), "请选择统计时间");
            AssertUtil.notNull(goodsRankDTO.getIsAutoUpdate(), "请选择更新方式");
            //拼接榜单描述
            StringBuilder description = new StringBuilder("根据");
            if (goodsRankDTO.getStatsTime() == GoodsRankConst.STATS_TIME_1) {
                description.append("近7日");
            } else {
                description.append("近30日");
            }
            if (goodsRankDTO.getRankType() == GoodsRankConst.RANK_TYPE_1) {
                AssertUtil.notNullOrZero(goodsRankDTO.getBestSellerRankRule(), "请选择计算规则");
                if (goodsRankDTO.getBestSellerRankRule() == GoodsRankConst.BEST_SELLER_RANK_RULE_1) {
                    description.append("销量");
                } else {
                    description.append("销售额");
                }
            } else if (goodsRankDTO.getRankType() == GoodsRankConst.RANK_TYPE_2) {
                AssertUtil.notNullOrZero(goodsRankDTO.getHighCommentNum(), "请输入好评数");
                AssertUtil.notNullOrZero(goodsRankDTO.getHighCommentRate(), "请输入好评率");
                description.append("好评数和好评率");
            } else if (goodsRankDTO.getRankType() == GoodsRankConst.RANK_TYPE_3) {
                AssertUtil.notNullOrZero(goodsRankDTO.getNewProductRankRule(), "请选择计算规则");
                if (goodsRankDTO.getNewProductRankRule() == GoodsRankConst.NEW_PRODUCT_RANK_RULE_1) {
                    description.append("按照商品发布的时间降序");
                } else {
                    description.append("按照商品发布的时间升序");
                }
            }
            description.append("数据计算得出");
            goodsRank.setDescription(description.toString());
            if (goodsRankDTO.getIsAutoUpdate() == GoodsRankConst.IS_AUTO_UPDATE_0) {
                AssertUtil.notEmpty(goodsRankDTO.getGoodsList(), "请选择商品");
            }
        } else {
            AssertUtil.notEmpty(goodsRankDTO.getGoodsList(), "请选择商品");
        }

        //榜单名称不可重复
        GoodsRankExample example = new GoodsRankExample();
        example.setRankName(goodsRankDTO.getRankName());
        List<GoodsRank> list = goodsRankModel.getGoodsRankList(example, null);
        AssertUtil.isTrue(!CollectionUtils.isEmpty(list), "榜单名称不可重复");

        BeanUtils.copyProperties(goodsRankDTO, goodsRank);
        goodsRank.setCreateAdminId(admin.getAdminId());
        goodsRank.setCreateTime(new Date());
        goodsRankModel.saveGoodsRank(goodsRank, goodsRankDTO.getGoodsList());
        return SldResponse.success("操作成功");
    }

    @ApiOperation("编辑排行榜")
    @OperationLogger(option = "编辑排行榜")
    @PostMapping("update")
    public JsonResult updateGoodsRank(HttpServletRequest request, @RequestBody GoodsRankDTO goodsRankDTO) {
        AssertUtil.sortCheck(goodsRankDTO.getSort());
        AssertUtil.notNullOrZero(goodsRankDTO.getRankType(), "请选择榜单类型");

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

        //根据榜单类型校验参数
        GoodsRank goodsRank = new GoodsRank();
        if (goodsRankDTO.getRankType() != GoodsRankConst.RANK_TYPE_4) {
            AssertUtil.notNullOrZero(goodsRankDTO.getGoodsCategoryId(), "请选择商品分类");
            AssertUtil.notNullOrZero(goodsRankDTO.getStatsTime(), "请选择统计时间");
            AssertUtil.notNull(goodsRankDTO.getIsAutoUpdate(), "请选择更新方式");
            //拼接榜单描述
            StringBuilder description = new StringBuilder("根据");
            if (goodsRankDTO.getStatsTime() == GoodsRankConst.STATS_TIME_1) {
                description.append("近7日");
            } else {
                description.append("近30日");
            }
            if (goodsRankDTO.getRankType() == GoodsRankConst.RANK_TYPE_1) {
                AssertUtil.notNullOrZero(goodsRankDTO.getBestSellerRankRule(), "请选择计算规则");
                if (goodsRankDTO.getBestSellerRankRule() == GoodsRankConst.BEST_SELLER_RANK_RULE_1) {
                    description.append("销量");
                } else {
                    description.append("销售额");
                }
            } else if (goodsRankDTO.getRankType() == GoodsRankConst.RANK_TYPE_2) {
                AssertUtil.notNullOrZero(goodsRankDTO.getHighCommentNum(), "请输入好评数");
                AssertUtil.notNullOrZero(goodsRankDTO.getHighCommentRate(), "请输入好评率");
                description.append("好评数和好评率");
            } else if (goodsRankDTO.getRankType() == GoodsRankConst.RANK_TYPE_3) {
                AssertUtil.notNullOrZero(goodsRankDTO.getNewProductRankRule(), "请选择计算规则");
                if (goodsRankDTO.getNewProductRankRule() == GoodsRankConst.NEW_PRODUCT_RANK_RULE_1) {
                    description.append("按照商品发布的时间降序");
                } else {
                    description.append("按照商品发布的时间升序");
                }
            }
            description.append("数据计算得出");
            goodsRank.setDescription(description.toString());
            if (goodsRankDTO.getIsAutoUpdate() == GoodsRankConst.IS_AUTO_UPDATE_0) {
                AssertUtil.notEmpty(goodsRankDTO.getGoodsList(), "请选择商品");
            }
        } else {
            AssertUtil.notEmpty(goodsRankDTO.getGoodsList(), "请选择商品");
        }

        //榜单名称不可重复
        GoodsRankExample example = new GoodsRankExample();
        example.setRankName(goodsRankDTO.getRankName());
        example.setRankIdNotEquals(goodsRankDTO.getRankId());
        List<GoodsRank> list = goodsRankModel.getGoodsRankList(example, null);
        AssertUtil.isTrue(!CollectionUtils.isEmpty(list), "榜单名称不可重复");

        BeanUtils.copyProperties(goodsRankDTO, goodsRank);
        goodsRank.setUpdateAdminId(admin.getAdminId());
        goodsRank.setUpdateTime(new Date());
        goodsRankModel.updateGoodsRank(goodsRank, goodsRankDTO.getGoodsList());
        return SldResponse.success("操作成功");
    }

    @ApiOperation("是否启用榜单")
    @OperationLogger(option = "是否启用榜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rankId", value = "榜单id", required = true),
            @ApiImplicitParam(name = "isEnable", value = "是否启用，false-不启用，true-启用", required = true)
    })
    @PostMapping("isEnable")
    public JsonResult isEnable(HttpServletRequest request, Integer rankId, boolean isEnable) {
        Admin admin = UserUtil.getUser(request, Admin.class);

        GoodsRank goodsRank = new GoodsRank();
        goodsRank.setRankId(rankId);
        if (isEnable) {
            goodsRank.setState(GoodsRankConst.STATE_1);
        } else {
            goodsRank.setState(GoodsRankConst.STATE_0);
        }
        goodsRank.setUpdateAdminId(admin.getAdminId());
        goodsRank.setUpdateTime(new Date());
        goodsRankModel.updateGoodsRank(goodsRank);
        return SldResponse.success("操作成功");
    }

    @ApiOperation("删除榜单")
    @OperationLogger(option = "删除榜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rankId", value = "榜单id", required = true)
    })
    @PostMapping("del")
    public JsonResult delGoodsRank(HttpServletRequest request, Integer rankId) {
        Admin admin = UserUtil.getUser(request, Admin.class);

        goodsRankModel.deleteGoodsRank(rankId);
        return SldResponse.success("删除成功");
    }

    @ApiOperation("移除榜单")
    @OperationLogger(option = "移除榜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rankId", value = "榜单id", required = true)
    })
    @PostMapping("remove")
    public JsonResult removeGoodsRank(HttpServletRequest request, Integer rankId) {
        Admin admin = UserUtil.getUser(request, Admin.class);

        GoodsRank goodsRankDb = goodsRankModel.getGoodsRankByRankId(rankId);
        AssertUtil.notNull(goodsRankDb, "榜单不存在");

        GoodsRank goodsRank = new GoodsRank();
        goodsRank.setRankId(rankId);
        goodsRank.setCategoryId(0);
        goodsRank.setCategoryName("");
        goodsRank.setUpdateAdminId(admin.getAdminId());
        goodsRank.setUpdateTime(new Date());
        goodsRankModel.updateGoodsRank(goodsRank);
        return SldResponse.success("移除成功");
    }

    @ApiOperation("手动刷新榜单商品")
    @OperationLogger(option = "手动刷新榜单商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rankId", value = "榜单id", required = true),
    })
    @GetMapping("refresh")
    public JsonResult refresh(HttpServletRequest request, Integer rankId) {
        Admin admin = UserUtil.getUser(request, Admin.class);

        GoodsRank goodsRank = goodsRankModel.getGoodsRankByRankId(rankId);
        AssertUtil.notNull(goodsRank, "榜单不存在");
        //更新方式是手动刷新并且不是自定义类型的,执行下一步，否则直接返回
        if (goodsRank.getRankType() != GoodsRankConst.RANK_TYPE_4 && goodsRank.getIsAutoUpdate() == GoodsRankConst.IS_AUTO_UPDATE_0) {
            goodsRankModel.refreshRankGoods(goodsRank);

            //更新榜单信息
            GoodsRank goodsRankNew = new GoodsRank();
            goodsRankNew.setRankId(rankId);
            goodsRankNew.setUpdateAdminId(admin.getAdminId());
            goodsRankNew.setUpdateTime(new Date());
            goodsRankModel.updateGoodsRank(goodsRankNew);
        }
        return SldResponse.success("刷新成功");
    }

    @ApiOperation("关闭榜单")
    @OperationLogger(option = "关闭榜单")
    @PostMapping("closeRank")
    public JsonResult closeRank(HttpServletRequest request) {
        Admin admin = UserUtil.getUser(request, Admin.class);

        GoodsRank goodsRank = new GoodsRank();
        goodsRank.setState(GoodsRankConst.STATE_0);
        goodsRank.setUpdateAdminId(admin.getAdminId());
        goodsRank.setUpdateTime(new Date());
        goodsRankModel.closeRank(goodsRank);
        return SldResponse.success("关闭成功");
    }
}
