package com.gree.mall.manager.logic.es;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.count.*;
import com.gree.mall.manager.commonmapper.CountMapper;
import com.gree.mall.manager.enums.OrderShareStatusEnum;
import com.gree.mall.manager.enums.OrderStatusEnum;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.EsOrderInfo;
import com.gree.mall.manager.plus.entity.OrderShare;
import com.gree.mall.manager.plus.service.EsOrderInfoService;
import com.gree.mall.manager.plus.service.OrderInfoService;
import com.gree.mall.manager.plus.service.OrderShareService;
import com.gree.mall.manager.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class EsCountLogic {

    private final CommonLogic commonLogic;
    private final CountMapper countMapper;
    private final OrderShareService orderShareService;
    private final EsOrderInfoService esOrderInfoService;


    /**
     * 概况统计
     */
    public EsCountBean info(){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //累计售出商品数量，已售中商品数量，待发货订单数量，维权中订单数量，今日订单数，昨日订单数，今日收益，昨日收益
        EsCountBean countBean = countMapper.countEsInfo(adminUser.getCompanyWechatId());
        //今日访客
        Integer todayVisit = countMapper.countVisit(sdf.format(DateUtils.getStartTime()),sdf.format(DateUtils.getEndTime()),adminUser.getCompanyWechatIds());
        //昨日访客
        Integer yestodayVisit = countMapper.countVisit(sdf.format(DateUtils.getBeginDayOfYesterday()),sdf.format(DateUtils.getEndDayOfYesterDay()),adminUser.getCompanyWechatIds());
        //查询待结算金额
//        List<OrderShare> list = orderShareService.lambdaQuery()
//                .eq(OrderShare::getStatus, OrderShareStatusEnum.ING.toString())
//                .list();
        //BigDecimal totalShareAmount = list.stream().map(OrderShare::getAmount).reduce(BigDecimal::add).orElse(new BigDecimal(0));
        //countBean.setOrderShareAmount(totalShareAmount);
        countBean.setTodayVisit(todayVisit);
        countBean.setYestodayVisit(yestodayVisit);
        return countBean;
    }


    /**
     * 商品销售排行
     */
    public IPage<EsGoodsRankBean> countGoodsRank(Integer flag,Integer pageNum,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //默认今天
        Date startTime = this.getStartTime(flag);
        Date endTime = this.getEndTime(flag);
        IPage<EsGoodsRankBean> goodsRankBeans = countMapper.countEsGoodsRank(new Page<>(pageNum,pageSize),sdf.format(startTime), sdf.format(endTime),adminUser.getCompanyWechatId());
        return goodsRankBeans;
    }


    /**
     * 交易概述
     */
    public CountOrderBean order(Integer flag){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //默认今天
        Date startTime = this.getStartTime(flag);
        Date endTime = this.getEndTime(flag);
        CountOrderBean countOrderBean = countMapper.countEsSaleOrder(DateUtils.formatDate(startTime), DateUtils.formatDate(endTime),adminUser.getCompanyWechatId());
        //各时段统计
        List<EsOrderInfo> list = esOrderInfoService.lambdaQuery()
                .notIn(EsOrderInfo::getStatus,Arrays.asList(OrderStatusEnum.NOPAY.toString(),OrderStatusEnum.TIMEOUT.toString(),OrderStatusEnum.CLOSE))
                .between(EsOrderInfo::getCreateTime, startTime, endTime).list();
        SimpleDateFormat hh = new SimpleDateFormat("HH");
        SimpleDateFormat dd = new SimpleDateFormat("dd");
        int[] day = new int[24];
        int[] week = new int[7];
        int[] month = new int[DateUtils.DateSubOfDay(DateUtils.getEndMonth(), DateUtils.getStartMonth()) + 1];
        for(EsOrderInfo orderInfo : list) {
            Date time = orderInfo.getCreateTime();
            if (flag == 1 || flag == 2) {
                int index = Integer.parseInt(hh.format(time));
                //天  按24小时维度 0-23
                day[index]++;
            }
            if (flag == 3) {
                int index = DateUtils.DateSubOfDay(time,startTime);
                //7天 按天维度 日不是从0号开始，所以-1
                week[index]++;
            }
            if (flag == 4) {
                int index = Integer.parseInt(dd.format(time));
                //月 按天维度 日不是从0号开始，所以-1
                month[index-1]++;
            }
        }
        if(flag == 1 || flag== 2) {
            countOrderBean.setCountAry(day);
            String str[] = new String[24];
            for(int i = 0 ;i < str.length;i++) {
                str[i] = i +"";
            }
            countOrderBean.setX(str);
        }
        if(flag == 3) {
            countOrderBean.setCountAry(week);
            countOrderBean.setX(getX(7,null));
        }
        if(flag == 4) {
            countOrderBean.setCountAry(month);
            countOrderBean.setX(getX(DateUtils.DateSubOfDay(DateUtils.getEndMonth(), DateUtils.getStartMonth()) + 1,DateUtils.getEndMonth()));
        }

        return countOrderBean;
    }




    private Date getStartTime(Integer flag){
        Date startTime = DateUtils.getStartTime();
        //昨天
        if(flag == 2){
            startTime = DateUtils.getTimeByDay(DateUtils.getStartTime(),-1);
        }
        //最近7天
        if(flag == 3 ){
            startTime = DateUtils.getTimeByDay(startTime,-6);
        }
        //本月
        if(flag == 4){
            startTime = DateUtils.getStartMonth();
        }
        return startTime;
    }

    private Date getEndTime(Integer flag){
        Date endTime = DateUtils.getEndTime();
        //昨天
        if(flag == 2){
            endTime =  DateUtils.getStartTime();
        }
        //最近7天
        if(flag == 3 ){
            endTime = DateUtils.getStartTime();
        }
        //本月
        if(flag == 4){
            endTime = DateUtils.getEndMonth();
        }
        return endTime;
    }


    private static String[] getX(int dayNum,Date date){
        if(date == null){
            date = new Date();
        }
        String[] x = new String[dayNum];
        for(int i = 0 ;i <dayNum;i++){
            Date timeByDay = DateUtils.getTimeByDay(date,i-dayNum+1);
            x[i] = DateUtils.formatDate1(timeByDay);
        }
        return x;
    }

}
