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

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.count.CountBean;
import com.gree.mall.manager.bean.count.CountOrderBean;
import com.gree.mall.manager.bean.count.GoodsRankBean;
import com.gree.mall.manager.bean.count.WebsitSaleCountBean;
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.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CountLogic {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    OrderRefundService orderRefundService;
    @Autowired
    OrderShareService orderShareService;
    @Autowired
    UserService userService;
    @Autowired
    CountMapper countMapper;
    @Autowired
    UserVisitService userVisitService;


    /**
     * 概况统计
     */
    public CountBean info(HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //累计售出商品数量，已售中商品数量，待发货订单数量，维权中订单数量，今日订单数，昨日订单数，今日收益，昨日收益
        CountBean countBean = countMapper.countInfo(adminUser.getAdminCompanyIds(), adminUser.getAdminWebsitIds());
        //今日访客
        Integer todayVisit = countMapper.countVisit(sdf.format(DateUtils.getStartTime()), sdf.format(DateUtils.getEndTime()), adminUser.getAdminCompanyIds(), adminUser.getAdminWebsitIds());
        //昨日访客
        Integer yestodayVisit = countMapper.countVisit(sdf.format(DateUtils.getBeginDayOfYesterday()), sdf.format(DateUtils.getEndDayOfYesterDay()), adminUser.getAdminCompanyIds(), adminUser.getAdminWebsitIds());
        //查询待结算金额
        List<OrderShare> list = orderShareService.lambdaQuery()
                .eq(OrderShare::getStatus, OrderShareStatusEnum.ING.toString())
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminCompanyIds()), OrderShare::getCompanyWechatId, adminUser.getAdminCompanyIds())
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds()), OrderShare::getWebsitId, adminUser.getAdminWebsitIds())
                .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 List<GoodsRankBean> countGoodsRank(Integer flag, HttpServletRequest request) {

        AdminUserCom adminUserCom = commonLogic.getAdminUser(request);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //默认今天
        Date startTime = this.getStartTime(flag);
        Date endTime = this.getEndTime(flag);
        List<GoodsRankBean> goodsRankBeans = countMapper.countGoodsRank(sdf.format(startTime), sdf.format(endTime),
                adminUserCom.getAdminCompanyIds(), adminUserCom.getAdminWebsitIds());
        return goodsRankBeans;
    }


    /**
     * 交易概述
     */
    public CountOrderBean order(String type, Integer flag, HttpServletRequest request) {
        AdminUserCom adminUserCom = commonLogic.getAdminUser(request);
        //默认今天
        Date startTime = this.getStartTime(flag);
        Date endTime = this.getEndTime(flag);
        CountOrderBean countOrderBean = countMapper.countSaleOrder(DateUtils.formatDate(startTime), DateUtils.formatDate(endTime), type,
                adminUserCom.getAdminCompanyIds(), adminUserCom.getAdminWebsitIds());
        //各时段统计
        List<OrderInfo> list = orderInfoService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminUserCom.getAdminCompanyIds()), OrderInfo::getCompanyId, adminUserCom.getAdminCompanyIds())
                .in(CollectionUtils.isNotEmpty(adminUserCom.getAdminWebsitIds()), OrderInfo::getWebsitId, adminUserCom.getAdminWebsitIds())
                .notIn(OrderInfo::getOrderStatus, Arrays.asList(OrderStatusEnum.CLOSE.toString(), OrderStatusEnum.NOPAY.toString(), OrderStatusEnum.TIMEOUT.toString()))
                .between(OrderInfo::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 (OrderInfo 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);
            countOrderBean.setX(new String[24]);
        }
        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;
    }


    /**
     * 师傅的销售金额统计
     */
    public List<Map<String, Object>> queryWorkAmount(String startTime, String endTime, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<Map<String, Object>> maps = countMapper.countWorkAmount(startTime, endTime, adminUser.getAdminCompanyIds());
        return maps;
    }


    /**
     * 网点的销售金额统计
     */
    public WebsitSaleCountBean queryWebsitAmount(List<String> websitNumbers) {
        //当月
        Map<String, Object> map = countMapper.countWebsitAmount(DateUtils.formatDate(DateUtils.getStartMonth()), DateUtils.formatDate(DateUtils.getEndMonth()), websitNumbers);
        //当日
        Map<String, Object> map2 = countMapper.countWebsitAmount(DateUtils.formatDate(DateUtils.getStartTime()), DateUtils.formatDate(DateUtils.getEndTime()), websitNumbers);

        WebsitSaleCountBean bean = new WebsitSaleCountBean();
        bean.setMonthNum((Integer) map.get("num"));
        bean.setMonthAmount(new BigDecimal(map.get("amount").toString()));
        bean.setDayNum((Integer) map2.get("num"));
        bean.setDayAmount(new BigDecimal(map2.get("amount").toString()));
        return bean;
    }


    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;
    }

}
