package com.slodon.b2b2c.model.goods;

import cn.hutool.core.date.DateUtil;
import com.slodon.b2b2c.business.dto.OrderProductDTO;
import com.slodon.b2b2c.business.example.OrderExample;
import com.slodon.b2b2c.business.example.OrderProductExample;
import com.slodon.b2b2c.business.pojo.Order;
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.constant.OrderConst;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.dao.read.business.OrderProductReadMapper;
import com.slodon.b2b2c.dao.read.business.OrderReadMapper;
import com.slodon.b2b2c.dao.read.goods.*;
import com.slodon.b2b2c.dao.write.goods.GoodsBindRankWriteMapper;
import com.slodon.b2b2c.dao.write.goods.GoodsRankWriteMapper;
import com.slodon.b2b2c.dao.write.goods.GoodsWriteMapper;
import com.slodon.b2b2c.goods.dto.GoodsCommentDTO;
import com.slodon.b2b2c.goods.dto.GoodsRankDTO;
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.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 排行榜model
 */
@Component
@Slf4j
public class GoodsRankModel {

    @Resource
    private GoodsRankReadMapper goodsRankReadMapper;
    @Resource
    private GoodsRankWriteMapper goodsRankWriteMapper;
    @Resource
    private GoodsBindRankReadMapper goodsBindRankReadMapper;
    @Resource
    private GoodsBindRankWriteMapper goodsBindRankWriteMapper;
    @Resource
    private GoodsRankCategoryReadMapper goodsRankCategoryReadMapper;
    @Resource
    private GoodsReadMapper goodsReadMapper;
    @Resource
    private GoodsWriteMapper goodsWriteMapper;
    @Resource
    private GoodsCategoryReadMapper goodsCategoryReadMapper;
    @Resource
    private GoodsCommentReadMapper goodsCommentReadMapper;
    @Resource
    private OrderReadMapper orderReadMapper;
    @Resource
    private OrderProductReadMapper orderProductReadMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 新增排行榜
     *
     * @param goodsRank
     * @return
     */
    public Integer saveGoodsRank(GoodsRank goodsRank) {
        int count = goodsRankWriteMapper.insert(goodsRank);
        if (count == 0) {
            throw new MallException("添加排行榜失败，请重试");
        }
        return goodsRank.getRankId();
    }

    /**
     * 新建排行榜
     *
     * @param goodsRank
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer saveGoodsRank(GoodsRank goodsRank, List<GoodsRankDTO.RankGoodsInfo> goodsList) {
        //查询榜单分类
        GoodsRankCategory goodsRankCategory = goodsRankCategoryReadMapper.getByPrimaryKey(goodsRank.getCategoryId());
        AssertUtil.notNull(goodsRankCategory, "榜单分类不存在");
        goodsRank.setCategoryName(goodsRankCategory.getCategoryName());

        GoodsCategory goodsCategory = null;
        //自定义榜不需要商品分类id信息
        if (goodsRank.getRankType() != GoodsRankConst.RANK_TYPE_4) {
            //查询商品分类
            goodsCategory = goodsCategoryReadMapper.getByPrimaryKey(goodsRank.getGoodsCategoryId());
            AssertUtil.notNull(goodsCategory, "分类信息有误");
            goodsRank.setGoodsCategoryName(goodsCategory.getCategoryName());
        }

        Integer rankId = this.saveGoodsRank(goodsRank);
        goodsRank.setRankId(rankId);
        //自定义榜单
        if (goodsRank.getRankType() == GoodsRankConst.RANK_TYPE_4) {
            insertRankBindGoods(goodsRank.getRankType(), rankId, goodsList);
        } else {
            //畅销榜、好评榜和新品榜三个榜单选择手动更新时直接插入
            if (goodsRank.getIsAutoUpdate() == GoodsRankConst.IS_AUTO_UPDATE_0) {
                insertRankBindGoods(goodsRank.getRankType(), rankId, goodsList);
            } else {
                //畅销榜、好评榜和新品榜三个榜单选择自动更新时查询满足条件
                insertRankBindGoodsByType(goodsRank, goodsCategory);
            }
        }
        return rankId;
    }

    /**
     * 根据榜单类型保存榜单绑定商品
     *
     * @param goodsRank
     * @param goodsCategory
     */
    public void insertRankBindGoodsByType(GoodsRank goodsRank, GoodsCategory goodsCategory) {
        //查询榜单最大可添加商品数
        String maxAddGoodsNum = stringRedisTemplate.opsForValue().get("rank_max_add_goods_num");
        int goodsNum = StringUtil.isEmpty(maxAddGoodsNum) ? 20 : Integer.parseInt(maxAddGoodsNum);
        PagerInfo pager = new PagerInfo(goodsNum, 1);
        //查询商品列表
        GoodsExample example = new GoodsExample();
        example.setState(GoodsConst.GOODS_STATE_UPPER);
        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 (goodsRank.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());
        }
        //拼接商品id
        StringBuilder goodsIds = new StringBuilder();
        if (goodsRank.getRankType() == GoodsRankConst.RANK_TYPE_1) {
            List<Goods> list = goodsReadMapper.listByExample(example);
            //没有满足条件的商品直接返回
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            //畅销榜
            List<OrderProductDTO> productList = getGoodsListByBestSellerRankRule(getGoodsIds(list), startTime, endTime, goodsRank.getBestSellerRankRule(), pager);
            if (CollectionUtils.isEmpty(productList)) {
                return;
            }
            int i = 1;
            for (OrderProductDTO goodsInfo : productList) {
                GoodsBindRank goodsBindRank = new GoodsBindRank();
                goodsBindRank.setRankId(goodsRank.getRankId());
                goodsBindRank.setGoodsId(goodsInfo.getGoodsId());
                goodsBindRank.setGoodsRank(i);
                goodsBindRank.setSaleNum(goodsInfo.getSaleNum());
                goodsBindRank.setSaleAmount(goodsInfo.getSaleAmount());
                goodsBindRank.setCreateTime(new Date());
                int count = goodsBindRankWriteMapper.insert(goodsBindRank);
                AssertUtil.isTrue(count == 0, "添加榜单与商品绑定关系表失败，请重试");
                i++;

                goodsIds.append(",").append(goodsInfo.getGoodsId());
            }
        } else if (goodsRank.getRankType() == GoodsRankConst.RANK_TYPE_2) {
            List<Goods> list = goodsReadMapper.listByExample(example);
            //没有满足条件的商品直接返回
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            //好评榜
            GoodsCommentExample commentExample = new GoodsCommentExample();
            commentExample.setGoodsIdIn(getGoodsIds(list));
            commentExample.setCreateTimeAfter(startTime);
            commentExample.setCreateTimeBefore(endTime);
            commentExample.setHighNum(goodsRank.getHighCommentNum());
            commentExample.setHighPercent(new BigDecimal(goodsRank.getHighCommentRate()).divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
            List<GoodsCommentDTO> commentList = getGoodsListByHighRankRule(commentExample, pager);
            if (CollectionUtils.isEmpty(commentList)) {
                return;
            }
            int i = 1;
            for (GoodsCommentDTO goodsInfo : commentList) {
                GoodsBindRank goodsBindRank = new GoodsBindRank();
                goodsBindRank.setRankId(goodsRank.getRankId());
                goodsBindRank.setGoodsId(goodsInfo.getGoodsId());
                goodsBindRank.setGoodsRank(i);
                goodsBindRank.setHighNum(goodsInfo.getHighNum());
                goodsBindRank.setHighRate(goodsInfo.getHighPercent().multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%");
                goodsBindRank.setCreateTime(new Date());
                int count = goodsBindRankWriteMapper.insert(goodsBindRank);
                AssertUtil.isTrue(count == 0, "添加榜单与商品绑定关系表失败，请重试");
                i++;

                goodsIds.append(",").append(goodsInfo.getGoodsId());
            }
        } else if (goodsRank.getRankType() == GoodsRankConst.RANK_TYPE_3) {
            example.setCreateTimeAfter(startTime);
            example.setCreateTimeBefore(endTime);
            if (goodsRank.getNewProductRankRule() == GoodsRankConst.NEW_PRODUCT_RANK_RULE_2) {
                example.setOrderBy("create_time ASC");
            } else {
                example.setOrderBy("create_time DESC");
            }
            pager.setRowsCount(goodsReadMapper.countByExample(example));
            List<Goods> list = goodsReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
            //没有满足条件的商品直接返回
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            //新品榜
            int i = 1;
            for (Goods goods : list) {
                GoodsBindRank goodsBindRank = new GoodsBindRank();
                goodsBindRank.setRankId(goodsRank.getRankId());
                goodsBindRank.setGoodsId(goods.getGoodsId());
                goodsBindRank.setGoodsRank(i);
                goodsBindRank.setCreateTime(new Date());
                int count = goodsBindRankWriteMapper.insert(goodsBindRank);
                AssertUtil.isTrue(count == 0, "添加榜单与商品绑定关系表失败，请重试");
                i++;

                goodsIds.append(",").append(goods.getGoodsId());
            }
        }
        //修改商品更新时间
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setGoodsIdIn(goodsIds.toString().substring(1));
        Goods goods = new Goods();
        goods.setUpdateTime(new Date());
        goodsWriteMapper.updateByExampleSelective(goods, goodsExample);
    }

    /**
     * 保存榜单绑定商品
     *
     * @param rankType  榜单类型
     * @param rankId    榜单id
     * @param goodsList 商品列表
     */
    public void insertRankBindGoods(Integer rankType, Integer rankId, List<GoodsRankDTO.RankGoodsInfo> goodsList) {
        //拼接商品id
        StringBuilder goodsIds = new StringBuilder();
        for (GoodsRankDTO.RankGoodsInfo goodsInfo : goodsList) {
            AssertUtil.isTrue(rankType == GoodsRankConst.RANK_TYPE_4 && StringUtil.isEmpty(goodsInfo.getRankReason()), "请输入上榜理由");
            GoodsBindRank goodsBindRank = new GoodsBindRank();
            goodsBindRank.setRankId(rankId);
            goodsBindRank.setGoodsId(goodsInfo.getGoodsId());
            goodsBindRank.setGoodsRank(goodsInfo.getGoodsRank());
            goodsBindRank.setRankReason(goodsInfo.getRankReason());
            goodsBindRank.setCreateTime(new Date());
            int count = goodsBindRankWriteMapper.insert(goodsBindRank);
            AssertUtil.isTrue(count == 0, "添加榜单与商品绑定关系表失败，请重试");

            goodsIds.append(",").append(goodsInfo.getGoodsId());
        }
        //修改商品更新时间
        GoodsExample example = new GoodsExample();
        example.setGoodsIdIn(goodsIds.toString().substring(1));
        Goods goods = new Goods();
        goods.setUpdateTime(new Date());
        goodsWriteMapper.updateByExampleSelective(goods, example);
    }

    /**
     * 根据畅销榜规则查询并保存榜单绑定商品
     *
     * @param goodsIds           商品ids
     * @param startTime          开始时间
     * @param endTime            结束时间
     * @param bestSellerRankRule 畅销榜规则
     * @param pager              分页信息
     */
    public List<OrderProductDTO> getGoodsListByBestSellerRankRule(String goodsIds, Date startTime, Date endTime,
                                                                  Integer bestSellerRankRule, PagerInfo pager) {
        List<OrderProductDTO> productList = new ArrayList<>();
        //查询订单列表
        OrderExample orderExample = new OrderExample();
        //按销售额排行过滤订单状态
        if (bestSellerRankRule == GoodsRankConst.BEST_SELLER_RANK_RULE_2) {
            orderExample.setOrderStateIn(OrderConst.ORDER_STATE_20 + "," + OrderConst.ORDER_STATE_30 + "," + OrderConst.ORDER_STATE_40);
        }
        orderExample.setCreateTimeAfter(startTime);
        orderExample.setCreateTimeBefore(endTime);
        List<Order> orderList = orderReadMapper.listByExample(orderExample);
        //没有满足条件的订单直接返回
        if (CollectionUtils.isEmpty(orderList)) {
            return productList;
        }
        //拼接订单号
        StringBuilder orderSns = new StringBuilder();
        orderList.forEach(order -> {
            orderSns.append(",'").append(order.getOrderSn()).append("'");
        });
        //查询订单货品列表
        OrderProductExample orderProductExample = new OrderProductExample();
        orderProductExample.setGoodsIdIn(goodsIds);
        orderProductExample.setOrderSnIn(orderSns.toString().substring(1));
        if (bestSellerRankRule == GoodsRankConst.BEST_SELLER_RANK_RULE_1) {
            orderProductExample.setOrderBy("saleNum DESC");
        }
        pager.setRowsCount(orderProductReadMapper.getOrderProductCount(orderProductExample));
        return orderProductReadMapper.getOrderProductDtoListPage(orderProductExample, pager.getStart(), pager.getPageSize());
    }

    /**
     * 查询自定义榜单商品销售情况
     *
     * @param goodsIds 商品ids
     */
    public List<OrderProductDTO> getGoodsSaleList(String goodsIds) {
        List<OrderProductDTO> productList = new ArrayList<>();
        //查询订单列表
        OrderExample orderExample = new OrderExample();
        //按销售额排行过滤订单状态
        orderExample.setOrderStateIn(OrderConst.ORDER_STATE_20 + "," + OrderConst.ORDER_STATE_30 + "," + OrderConst.ORDER_STATE_40);
        List<Order> orderList = orderReadMapper.listByExample(orderExample);
        //没有满足条件的订单直接返回
        if (CollectionUtils.isEmpty(orderList)) {
            return productList;
        }
        //拼接订单号
        StringBuilder orderSns = new StringBuilder();
        orderList.forEach(order -> {
            orderSns.append(",'").append(order.getOrderSn()).append("'");
        });
        //查询订单货品列表
        OrderProductExample orderProductExample = new OrderProductExample();
        orderProductExample.setGoodsIdIn(goodsIds);
        orderProductExample.setOrderSnIn(orderSns.toString().substring(1));
        return orderProductReadMapper.getOrderProductDtoList(orderProductExample);
    }

    /**
     * 根据好评榜规则查询并保存榜单绑定商品
     *
     * @param example 查询条件
     * @param pager   分页信息
     */
    public List<GoodsCommentDTO> getGoodsListByHighRankRule(GoodsCommentExample example, PagerInfo pager) {
        pager.setRowsCount(goodsCommentReadMapper.getGoodsCommentCount(example));
        return goodsCommentReadMapper.getGoodsCommentDtoList(example, pager.getStart(), pager.getPageSize());
    }

    /**
     * 拼接商品id
     *
     * @param list
     * @return
     */
    public String getGoodsIds(List<Goods> list) {
        StringBuilder goodsIds = new StringBuilder();
        list.forEach(goods -> {
            goodsIds.append(",").append(goods.getGoodsId());
        });
        return goodsIds.toString().substring(1);
    }

    /**
     * 根据rankId删除排行榜
     *
     * @param rankId rankId
     * @return
     */
    public Integer deleteGoodsRank(Integer rankId) {
        if (StringUtils.isEmpty(rankId)) {
            throw new MallException("请选择要删除的数据");
        }
        int count = goodsRankWriteMapper.deleteByPrimaryKey(rankId);
        if (count == 0) {
            log.error("根据rankId：" + rankId + "删除排行榜失败");
            throw new MallException("删除排行榜失败,请重试");
        }
        //删除榜单绑定的商品
        GoodsBindRankExample example = new GoodsBindRankExample();
        example.setRankId(rankId);
        List<GoodsBindRank> list = goodsBindRankReadMapper.listByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            goodsBindRankWriteMapper.deleteByExample(example);

            //拼接商品id
            StringBuilder goodsIds = new StringBuilder();
            list.forEach(goodsBindRank -> {
                goodsIds.append(",").append(goodsBindRank.getGoodsId());
            });
            //修改商品更新时间
            GoodsExample goodsExample = new GoodsExample();
            goodsExample.setGoodsIdIn(goodsIds.toString().substring(1));
            Goods goods = new Goods();
            goods.setUpdateTime(new Date());
            goodsWriteMapper.updateByExampleSelective(goods, goodsExample);
        }
        return count;
    }

    /**
     * 根据rankId更新排行榜
     *
     * @param goodsRank
     * @return
     */
    public Integer updateGoodsRank(GoodsRank goodsRank) {
        if (StringUtils.isEmpty(goodsRank.getRankId())) {
            throw new MallException("请选择要修改的数据");
        }
        int count = goodsRankWriteMapper.updateByPrimaryKeySelective(goodsRank);
        if (count == 0) {
            log.error("根据rankId：" + goodsRank.getRankId() + "更新排行榜失败");
            throw new MallException("更新排行榜失败,请重试");
        }
        //榜单关闭，修改榜单商品更新时间
        if (!StringUtils.isEmpty(goodsRank.getState()) && goodsRank.getState() == GoodsRankConst.STATE_0) {
            GoodsBindRankExample example = new GoodsBindRankExample();
            example.setRankId(goodsRank.getRankId());
            List<GoodsBindRank> list = goodsBindRankReadMapper.listByExample(example);
            if (!CollectionUtils.isEmpty(list)) {
                //拼接商品id
                StringBuilder goodsIds = new StringBuilder();
                list.forEach(goods -> {
                    goodsIds.append(",").append(goods.getGoodsId());
                });
                //更新商品更新时间
                GoodsExample goodsExample = new GoodsExample();
                goodsExample.setGoodsIdIn(goodsIds.toString().substring(1));
                Goods goods = new Goods();
                goods.setUpdateTime(new Date());
                goodsWriteMapper.updateByExampleSelective(goods, goodsExample);
            }
        }
        return count;
    }

    /**
     * 关闭榜单
     */
    public void closeRank(GoodsRank goodsRank) {
        //查询启用中的榜单
        GoodsRankExample example = new GoodsRankExample();
        example.setState(GoodsRankConst.STATE_1);
        List<GoodsRank> list = goodsRankReadMapper.listByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        goodsRankWriteMapper.updateByExampleSelective(goodsRank, example);

        //拼接榜单id
        StringBuilder rankIds = new StringBuilder();
        list.forEach(rank -> {
            rankIds.append(",").append(rank.getRankId());
        });
        //查询榜单商品
        GoodsBindRankExample bindRankExample = new GoodsBindRankExample();
        bindRankExample.setRankIdIn(rankIds.toString().substring(1));
        List<GoodsBindRank> bindRankList = goodsBindRankReadMapper.listByExample(bindRankExample);
        if (!CollectionUtils.isEmpty(bindRankList)) {
            //拼接商品id
            StringBuilder goodsIds = new StringBuilder();
            bindRankList.forEach(goods -> {
                goodsIds.append(",").append(goods.getGoodsId());
            });
            //更新商品更新时间
            GoodsExample goodsExample = new GoodsExample();
            goodsExample.setGoodsIdIn(goodsIds.toString().substring(1));
            Goods goods = new Goods();
            goods.setUpdateTime(new Date());
            goodsWriteMapper.updateByExampleSelective(goods, goodsExample);
        }
    }

    /**
     * 编辑排行榜
     *
     * @param goodsRank
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer updateGoodsRank(GoodsRank goodsRank, List<GoodsRankDTO.RankGoodsInfo> goodsList) {
        GoodsRank goodsRankDb = this.getGoodsRankByRankId(goodsRank.getRankId());
        AssertUtil.notNull(goodsRankDb, "榜单不存在");

        if (!StringUtil.isNullOrZero(goodsRankDb.getCategoryId()) && !goodsRankDb.getCategoryId().equals(goodsRank.getCategoryId())) {
            //查询榜单分类
            GoodsRankCategory goodsRankCategory = goodsRankCategoryReadMapper.getByPrimaryKey(goodsRank.getCategoryId());
            AssertUtil.notNull(goodsRankCategory, "榜单分类不存在");
            goodsRank.setCategoryName(goodsRankCategory.getCategoryName());
        }
        GoodsCategory goodsCategory = null;
        //自定义榜不需要商品分类id信息
        if (goodsRank.getRankType() != GoodsRankConst.RANK_TYPE_4) {
            //查询商品分类
            goodsCategory = goodsCategoryReadMapper.getByPrimaryKey(goodsRank.getGoodsCategoryId());
            AssertUtil.notNull(goodsCategory, "分类信息有误");
            goodsRank.setGoodsCategoryName(goodsCategory.getCategoryName());
        }

        Integer count = this.updateGoodsRank(goodsRank);

        //删除之前绑定的商品，重新插入数据
        GoodsBindRankExample example = new GoodsBindRankExample();
        example.setRankId(goodsRank.getRankId());
        List<GoodsBindRank> list = goodsBindRankReadMapper.listByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            goodsBindRankWriteMapper.deleteByExample(example);

            //拼接商品id
            StringBuilder goodsIds = new StringBuilder();
            list.forEach(goodsBindRank -> {
                goodsIds.append(",").append(goodsBindRank.getGoodsId());
            });
            //修改商品更新时间
            GoodsExample goodsExample = new GoodsExample();
            goodsExample.setGoodsIdIn(goodsIds.toString().substring(1));
            Goods goods = new Goods();
            goods.setUpdateTime(new Date());
            goodsWriteMapper.updateByExampleSelective(goods, goodsExample);
        }

        //自定义榜单
        if (goodsRank.getRankType() == GoodsRankConst.RANK_TYPE_4) {
            insertRankBindGoods(goodsRank.getRankType(), goodsRank.getRankId(), goodsList);
        } else {
            //畅销榜、好评榜和新品榜三个榜单选择手动更新时直接插入
            if (goodsRank.getIsAutoUpdate() == GoodsRankConst.IS_AUTO_UPDATE_0) {
                insertRankBindGoods(goodsRank.getRankType(), goodsRank.getRankId(), goodsList);
            } else {
                //畅销榜、好评榜和新品榜三个榜单选择自动更新时查询满足条件
                insertRankBindGoodsByType(goodsRank, goodsCategory);
            }
        }
        return count;
    }

    /**
     * 根据rankId获取排行榜详情
     *
     * @param rankId rankId
     * @return
     */
    public GoodsRank getGoodsRankByRankId(Integer rankId) {
        return goodsRankReadMapper.getByPrimaryKey(rankId);
    }

    /**
     * 根据条件获取排行榜列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<GoodsRank> getGoodsRankList(GoodsRankExample example, PagerInfo pager) {
        List<GoodsRank> goodsRankList;
        if (pager != null) {
            pager.setRowsCount(goodsRankReadMapper.countByExample(example));
            goodsRankList = goodsRankReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            goodsRankList = goodsRankReadMapper.listByExample(example);
        }
        return goodsRankList;
    }

    /**
     * 根据条件获取排行榜列表
     *
     * @param fields  查询字段，字段用逗号分隔
     * @param example 查询条件信息
     * @return
     */
    public List<GoodsRank> getGoodsRankListFields(String fields, GoodsRankExample example) {
        return goodsRankReadMapper.listFieldsByExample(fields, example);
    }

    /**
     * 根据条件获取排行榜数量
     *
     * @param example 查询条件信息
     * @return
     */
    public Integer getGoodsRankCount(GoodsRankExample example) {
        return goodsRankReadMapper.countByExample(example);
    }

    /**
     * 刷新排行榜商品
     *
     * @param goodsRank
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void refreshRankGoods(GoodsRank goodsRank) {
        //查询分类
        GoodsCategory goodsCategory = goodsCategoryReadMapper.getByPrimaryKey(goodsRank.getGoodsCategoryId());
        AssertUtil.notNull(goodsCategory, "分类信息有误");

        //删除之前绑定的商品，重新插入数据
        GoodsBindRankExample example = new GoodsBindRankExample();
        example.setRankId(goodsRank.getRankId());
        List<GoodsBindRank> list = goodsBindRankReadMapper.listByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            goodsBindRankWriteMapper.deleteByExample(example);

            //拼接商品id
            StringBuilder goodsIds = new StringBuilder();
            list.forEach(goodsBindRank -> {
                goodsIds.append(",").append(goodsBindRank.getGoodsId());
            });
            //修改商品更新时间
            GoodsExample goodsExample = new GoodsExample();
            goodsExample.setGoodsIdIn(goodsIds.toString().substring(1));
            Goods goods = new Goods();
            goods.setUpdateTime(new Date());
            goodsWriteMapper.updateByExampleSelective(goods, goodsExample);
        }

        insertRankBindGoodsByType(goodsRank, goodsCategory);
    }

    /**
     * 定时更新排行榜商品数据
     *
     * @return
     */
    public boolean jobUpdateRankGoods() {
        GoodsRankExample example = new GoodsRankExample();
        example.setIsAutoUpdate(GoodsRankConst.IS_AUTO_UPDATE_1);
        example.setState(GoodsRankConst.STATE_1);
        List<GoodsRank> list = goodsRankReadMapper.listByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return true;
        }
        //拼接榜单id
        StringBuilder rankIds = new StringBuilder();
        list.forEach(goodsRank -> {
            rankIds.append(",").append(goodsRank.getRankId());
            GoodsRank goodsRankDb = goodsRankReadMapper.getByPrimaryKey(goodsRank.getRankId());
            refreshRankGoods(goodsRankDb);
        });
        //更新榜单更新时间
        GoodsRankExample rankExample = new GoodsRankExample();
        rankExample.setRankIdIn(rankIds.toString().substring(1));
        GoodsRank goodsRank = new GoodsRank();
        goodsRank.setUpdateAdminId(0);
        goodsRank.setUpdateTime(new Date());
        goodsRankWriteMapper.updateByExampleSelective(goodsRank, rankExample);
        return true;
    }
}