
package com.tmerclub.cloud.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.tmerclub.cloud.api.feign.SearchOrderRefundFeignClient;
import com.tmerclub.cloud.api.feign.SearchSpuFeignClient;
import com.tmerclub.cloud.api.product.feign.ProductFeignClient;
import com.tmerclub.cloud.api.product.feign.SpuFeignClient;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.i18n.I18nMessage;
import com.tmerclub.cloud.common.order.dto.OrderRefundSearchDTO;
import com.tmerclub.cloud.common.order.vo.EsOrderRefundVO;
import com.tmerclub.cloud.common.order.vo.OrderCountVO;
import com.tmerclub.cloud.common.product.constant.SupplierSpuType;
import com.tmerclub.cloud.common.product.vo.SpuVO;
import com.tmerclub.cloud.common.product.vo.search.SpuSearchVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.Arith;
import com.tmerclub.cloud.common.util.DateUtils;
import com.tmerclub.cloud.order.manager.MongoOrderManager;
import com.tmerclub.cloud.order.manager.MongoOrderRefundManager;
import com.tmerclub.cloud.order.mapper.OrderMapper;
import com.tmerclub.cloud.order.mapper.OrderRefundMapper;
import com.tmerclub.cloud.order.service.SupplierOrderStatisticsService;
import com.tmerclub.cloud.order.vo.HotProductVO;
import com.tmerclub.cloud.order.vo.OrderOverviewVO;
import com.tmerclub.cloud.order.vo.OrderRefundStatisticsVO;
import com.tmerclub.cloud.order.vo.SupplierOrderOverviewVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lth
 */
@Service
public class SupplierOrderStatisticsServiceImpl implements SupplierOrderStatisticsService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MongoOrderManager mongoOrderManager;
    @Autowired
    private MongoOrderRefundManager mongoOrderRefundManager;
    @Autowired
    private OrderRefundMapper orderRefundMapper;
    @DubboReference
    private SearchSpuFeignClient searchSpuFeignClient;
    @DubboReference
    private SpuFeignClient spuFeignClient;
    @DubboReference
    private ProductFeignClient productFeignClient;
    @DubboReference
    private SearchOrderRefundFeignClient searchOrderRefundFeignClient;
    private static final Integer NUM = 15;

    public static final Logger log = LoggerFactory.getLogger(SupplierOrderStatisticsServiceImpl.class);

    @Override
    public OrderCountVO getOrderCountOfStatusBySupplierId(Long supplierId) {
        OrderCountVO orderCount = mongoOrderManager.getOrderCountOfStatusBySupplierId(supplierId);
        // 暂时使用es统计退款单总数数据
        OrderRefundSearchDTO searchDTO = new OrderRefundSearchDTO();
        searchDTO.setSupplierId(supplierId);
        searchDTO.setSysType(AuthUserContext.get().getSysType());
        searchDTO.setReturnMoneySts(1);
        EsPageVO<EsOrderRefundVO> data = searchOrderRefundFeignClient.pageOrderRefund(searchDTO).getData();
        orderCount.setRefund(Integer.valueOf(String.valueOf(data.getTotal())));
        return orderCount;
    }

    @Override
    public SupplierOrderOverviewVO getTodayInfoByHour(Long supplierId, Date startTime, Date endTime) {
        SupplierOrderOverviewVO supplierOrderOverviewVO = this.getOrderStatisticsByShopIdAndDateRange(supplierId, startTime, endTime);
        List<Integer> todayProdSoldCountList = this.listProdSoldCountByHour(supplierId, startTime, endTime);
        supplierOrderOverviewVO.setTodayProdSoldCountList(todayProdSoldCountList);

        List<Integer> yesterdayProdSoldCountList = this.listProdSoldCountByHour(supplierId, DateUtil.offsetDay(startTime, -1), DateUtil.offsetDay(endTime, -1));
        supplierOrderOverviewVO.setYesterdayProdSoldCountList(yesterdayProdSoldCountList);

        Integer todayShopNewUserCount = mongoOrderManager.getShopNewUsersBySupplierId(supplierId, startTime, null);
        supplierOrderOverviewVO.setTodayNewUserCount(todayShopNewUserCount);
        Integer yesterdayShopNewUserCount = mongoOrderManager.getShopNewUsersBySupplierId(supplierId, DateUtil.offsetDay(startTime, -1), DateUtil.offsetDay(endTime, -1));
        supplierOrderOverviewVO.setYesterdayNewUserCount(yesterdayShopNewUserCount);
        // 获取店铺近半个月的每天支付金额
        this.listPayActualAmount(supplierId, endTime, supplierOrderOverviewVO);

        ServerResponseEntity<List<SpuVO>> spuListResponse = productFeignClient.listSpuIdsBySupplierIdAndSupplierSpuType(supplierId, null, SupplierSpuType.YES.value());
        if (!spuListResponse.isSuccess()) {
            throw new LuckException(spuListResponse.getMsg());
        }
        if (CollUtil.isEmpty(spuListResponse.getData())) {
            supplierOrderOverviewVO.setTodayProdSoldNums(0);
        } else {
            supplierOrderOverviewVO.setTodayProdSoldNums(spuListResponse.getData().size());
        }
        // 今天上架的spuId
        ServerResponseEntity<List<SpuVO>> todaySpuListResponse = productFeignClient.listSpuIdsBySupplierIdAndSupplierSpuType(supplierId, DateUtil.format(DateUtil.beginOfDay(DateUtil.date()), "yyyy-MM-dd"), SupplierSpuType.YES.value());
        if (!todaySpuListResponse.isSuccess()) {
            throw new LuckException(todaySpuListResponse.getMsg());
        }
        if (CollUtil.isEmpty(todaySpuListResponse.getData())) {
            supplierOrderOverviewVO.setYesterdayProdSoldNums(supplierOrderOverviewVO.getTodayProdSoldNums());
            return supplierOrderOverviewVO;
        }
        // 昨天在售商品数量 = 今天在售商品数量 - 今天上架商品数量
        supplierOrderOverviewVO.setYesterdayProdSoldNums(supplierOrderOverviewVO.getTodayProdSoldNums() - todaySpuListResponse.getData().size());
        return supplierOrderOverviewVO;
    }

    @Override
    public List<HotProductVO> listProdRankingByPayActual(Long supplierId, Integer dayCount, Integer limit) {
        Date endTime = DateUtil.endOfDay(DateUtil.date());
        Date startTime = this.getStartTime(endTime, dayCount);
        List<HotProductVO> hotProductVOList = mongoOrderManager.listHotProdRanking(supplierId, startTime, endTime, I18nMessage.getLang());
        if (CollectionUtil.isEmpty(hotProductVOList)) {
            return hotProductVOList;
        }
        Map<Long, HotProductVO> hotProductMap = hotProductVOList.stream().collect(Collectors.toMap(HotProductVO::getSpuId, hotProductVO -> hotProductVO));

        // 先查询商家端独立发布的商品详情，用于后续获取对应的供应商商品信息 （此处不用es是因为es无法搜索已删除的商品，存在这样一种情况，商家端商品已删除，但其代销的供应商商品处于正常状态）
        ServerResponseEntity<List<SpuVO>> merchantSpuListResponse = productFeignClient.listSpuBySpuIds(new ArrayList<>(hotProductMap.keySet()));
        if (!merchantSpuListResponse.isSuccess()) {
            throw new LuckException(merchantSpuListResponse.getMsg());
        }
        List<SpuVO> merchantSpuVOList = merchantSpuListResponse.getData();
        if (CollectionUtil.isEmpty(merchantSpuVOList)) {
            return hotProductVOList;
        }
        // 过滤出SupplierSpuId不为null的数据
        merchantSpuVOList = merchantSpuVOList.stream().filter(x -> !Objects.isNull(x.getSupplierSpuId())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(merchantSpuVOList)) {
            return hotProductVOList;
        }
        Map<Long, List<SpuVO>> consignmentProductMap = merchantSpuVOList.stream().collect(Collectors.groupingBy(SpuVO::getSupplierSpuId));

        // 根据被代销的供应商商品Id查询商品详情
        ServerResponseEntity<List<SpuSearchVO>> supplierSpuResponse = searchSpuFeignClient.listSpuBySpuIds(new ArrayList<>(consignmentProductMap.keySet()));
        if (!supplierSpuResponse.isSuccess()) {
            throw new LuckException(supplierSpuResponse.getMsg());
        }
        List<SpuSearchVO> supplierSpuVOList = supplierSpuResponse.getData();

        List<HotProductVO> resultProdRankingList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (SpuSearchVO supplierSpu : supplierSpuVOList) {
            Long supplierSpuId = supplierSpu.getSpuId();
            HotProductVO hotProductVO = new HotProductVO();
            hotProductVO.setSpuId(supplierSpuId);
            hotProductVO.setPayAmount(0.0);
            hotProductVO.setOrderNums(0);
            hotProductVO.setProductNums(0);
            List<SpuVO> merchantSpuList = consignmentProductMap.get(supplierSpuId);
            if (CollUtil.isEmpty(merchantSpuList)) {
                continue;
            }
            for (SpuVO merchantSpu : merchantSpuList) {
                hotProductVO.setPayAmount(hotProductVO.getPayAmount() + hotProductMap.get(merchantSpu.getSpuId()).getPayAmount());
                hotProductVO.setOrderNums(hotProductVO.getOrderNums() + hotProductMap.get(merchantSpu.getSpuId()).getOrderNums());
                hotProductVO.setProductNums(hotProductVO.getProductNums() + hotProductMap.get(merchantSpu.getSpuId()).getProductNums());
            }
            hotProductVO.setSpuName(supplierSpu.getSpuName());
            hotProductVO.setSpuImg(supplierSpu.getMainImgUrl());
            resultProdRankingList.add(hotProductVO);
        }
        List<HotProductVO> resultProdList = resultProdRankingList.stream().sorted(Comparator.comparing(HotProductVO::getPayAmount).reversed()).limit(limit).collect(Collectors.toList());
        resultProdList.forEach(item -> item.setPayAmount(Arith.div(item.getPayAmount(), 100, 2)));
        return resultProdList;
    }

    /**
     * 根据spuId列表， 获取spu列表信息
     *
     * @param spuIds 商品id列表
     * @return 商品列表
     */
    private List<SpuSearchVO> listSpuInfoByIds(List<Long> spuIds) {
        ServerResponseEntity<List<SpuSearchVO>> supplierSpuResponse = searchSpuFeignClient.listSpuBySpuIds(spuIds);
        if (!supplierSpuResponse.isSuccess()) {
            throw new LuckException(supplierSpuResponse.getMsg());
        }
        return supplierSpuResponse.getData();
    }

    /**
     * 根据店铺Id与时间范围获取订单概况信息
     *
     * @param supplierId
     * @param startTime
     * @param endTime
     * @return
     */
    private SupplierOrderOverviewVO getOrderStatisticsByShopIdAndDateRange(Long supplierId, Date startTime, Date endTime) {
        OrderOverviewVO todayOrderOverviewVO = mongoOrderManager.getOrderOverviewInfoBySupplierId(supplierId, startTime, endTime);
        OrderOverviewVO yesterdayOrderOverviewVO = mongoOrderManager.getOrderOverviewInfoBySupplierId(supplierId, DateUtil.offsetDay(startTime, -1), DateUtil.offsetDay(endTime, -1));
        OrderRefundStatisticsVO todayOrderRefundStatisticsVO = mongoOrderRefundManager.getOrderRefundInfoBySupplierId(supplierId, startTime, endTime);
        OrderRefundStatisticsVO yesterdayOrderRefundStatisticsVO = mongoOrderRefundManager.getOrderRefundInfoBySupplierId(supplierId, DateUtil.offsetDay(startTime, -1), DateUtil.offsetDay(endTime, -1));

        SupplierOrderOverviewVO supplierOrderOverviewVO = new SupplierOrderOverviewVO();
        supplierOrderOverviewVO.setTodayPayActual(todayOrderOverviewVO.getPayActual());
        supplierOrderOverviewVO.setYesterdayPayActual(yesterdayOrderOverviewVO.getPayActual());
        supplierOrderOverviewVO.setTodayPayUserCount(todayOrderOverviewVO.getPayUserCount());
        supplierOrderOverviewVO.setYesterdayPayUserCount(yesterdayOrderOverviewVO.getPayUserCount());
        supplierOrderOverviewVO.setTodayRefundAmount(todayOrderRefundStatisticsVO.getPayActualTotal());
        supplierOrderOverviewVO.setYesterdayRefundAmount(yesterdayOrderRefundStatisticsVO.getPayActualTotal());
        return supplierOrderOverviewVO;
    }

    /**
     * 根据供应商Id与时间范围按小时分段获取已出售商品数量列表
     *
     * @param supplierId
     * @param startTime
     * @param endTime
     */
    private List<Integer> listProdSoldCountByHour(Long supplierId, Date startTime, Date endTime) {
        List<SupplierOrderOverviewVO> supplierOrderOverviewVOList = mongoOrderManager.listProdSoldCountByHour(supplierId, startTime, endTime);
        Map<Integer, Integer> prodSoldCountMap = new HashMap<>(25);
        for (SupplierOrderOverviewVO supplierOrderOverviewVO : supplierOrderOverviewVOList) {
            prodSoldCountMap.put(Integer.parseInt(supplierOrderOverviewVO.getTimeData()) + 8, supplierOrderOverviewVO.getTodayProdSoldNums());
        }
        List<Integer> todayProdSoldCountList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (int i = 0; i < Constant.MAX_HOUR_NUM_BY_DAY; i++) {
            todayProdSoldCountList.add(prodSoldCountMap.getOrDefault(i, 0));
        }
        return todayProdSoldCountList;
    }

    /*
      根据店铺Id与时间范围按小时分段获取数据支付金额列表

      @param shopId
     * @param startTime
     * @param endTime
     */

    /**
     * 根据店铺Id与时间范围按日期（以天为单位）分段获取数据支付金额列表
     *
     * @param supplierId
     * @param endTime
     * @param supplierOrderOverviewVO
     */
    private void listPayActualAmount(Long supplierId, Date endTime, SupplierOrderOverviewVO supplierOrderOverviewVO) {
        Date startTime = this.getStartTime(endTime, 15);
        List<OrderOverviewVO> orderOverviewVOList = mongoOrderManager.listPayActualByDay(supplierId, startTime, endTime);
        Map<String, OrderOverviewVO> orderOverviewMap = orderOverviewVOList.stream().collect(Collectors.toMap(OrderOverviewVO::getTimeData, orderOverviewVO -> orderOverviewVO));

        List<Double> payActualList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<String> dateToStringList = new ArrayList<>(Constant.INITIAL_CAPACITY);

        for (int i = 0; i < NUM; i++) {
            if (orderOverviewMap.containsKey(DateUtils.dateToStrYmd(startTime))) {
                OrderOverviewVO orderOverviewVO = orderOverviewMap.get(DateUtils.dateToStrYmd(startTime));
                payActualList.add(Arith.div(orderOverviewVO.getPayActual(), 100, 2));
            } else {
                payActualList.add(0.0);
            }
            dateToStringList.add(DateUtils.dateToStrYmd(startTime));
            startTime = getNextTime(startTime);
        }

        supplierOrderOverviewVO.setDateToStringList(dateToStringList);
        supplierOrderOverviewVO.setPayActualList(payActualList);
    }


    /**
     * 根据结束时间与天数获取起始时间
     *
     * @param endTime
     * @param dayCount
     * @return
     */
    private Date getStartTime(Date endTime, Integer dayCount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endTime);
        calendar.add(Calendar.DATE, -dayCount + 1);
        return DateUtil.beginOfDay(calendar.getTime());
    }

    private Double getChangeRate(double nowValue, double oldValue) {
        if (Objects.equals(oldValue, 0.0)) {
            return Objects.equals(nowValue, 0.0) ? 0.0 : 1.0;
        }
        double minus = Arith.sub(nowValue, oldValue);
        return Arith.div(minus, oldValue, 4);
    }

    /**
     * 获取下一次循环的开始时间，以及设置后台显示的时间字符串
     *
     * @param startTime 开始时间
     * @return
     */
    private Date getNextTime(Date startTime) {
        startTime = DateUtil.offsetDay(startTime, 1);
        return startTime;
    }

    /**
     * 计算两个数的百分比
     *
     * @param dividend 被除数
     * @param divisor  除数
     * @return
     */
    private Double getRatioRate(Integer dividend, Integer divisor) {
        if (Objects.isNull(dividend) || dividend == 0.0) {
            return 0.0;
        }
        if (Objects.isNull(divisor) || divisor == 0.0) {
            return 100.0;
        }
        return Arith.mul(Arith.div(dividend, divisor, 4), 100.00);
    }
}
