package com.ruoyi.homepage.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.frequency.workstype.entity.WorksType;
import com.ruoyi.frequency.workstype.service.WorksTypeService;
import com.ruoyi.homepage.mapper.HomePageMapper;
import com.ruoyi.homepage.model.param.ChartReq;
import com.ruoyi.homepage.model.param.RankingListReq;
import com.ruoyi.homepage.model.result.*;
import com.ruoyi.homepage.service.HomePageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 首页数据统计
 *
 * @author liwenlong
 * @date 2023-02-13
 */
@Service
public class HomePageServiceImpl implements HomePageService {

    @Autowired
    private HomePageMapper homePageMapper;

    @Override
    public AjaxResult statistics() {

        List<StatisticsResult> list = homePageMapper.statistics();

        if (list.size() > 0) {
            //求环比
            list.stream().forEach(s -> {

                int index = list.indexOf(s);

                BigDecimal position_2 = new BigDecimal(s.getPosition2());

                BigDecimal position_3 = new BigDecimal(s.getPosition3());

                if (position_2.compareTo(BigDecimal.ZERO) == 0) {
                    s.setPosition4("0");
                } else if (position_3.compareTo(BigDecimal.ZERO) == 0) {
                    s.setPosition4("100");
                } else {
                    s.setPosition4(position_2.subtract(position_3).divide(position_3, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                }

                if (index >= 4) {
                    s.setPosition1(s.getPosition1() + "元");
                    s.setPosition2(s.getPosition2() + "元");
                    s.setPosition3(s.getPosition3() + "元");
                } else {
                    s.setPosition1(new BigDecimal(s.getPosition1()).intValue() + "");
                }
                s.setPosition4(s.getPosition4() + "%");
            });
        }

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult orderAmountChartNear(ChartReq req) {

        List<ChartResult> list = new ArrayList<>();
        //1 本月  2 近一年
        if (req.getTimeType() == 1) {
            list = homePageMapper.monthOrderAmountChartNear();
            //补全没有数据的日期

        } else if (req.getTimeType() == 2) {
            list = homePageMapper.yearOrderAmountChartNear();
        }

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult orderAmountChart(ChartReq req) {

        List<ChartResult> list = new ArrayList<>();

        List<ChartResult> listNew = new ArrayList<>();
        //1 本月  2 近一年
        if (req.getTimeType() == 1) {
            list = homePageMapper.monthOrderAmountChart(req.getMonth());
            //补全没有数据的日期
            int daysInMonth = getDaysInMonth(Integer.valueOf(req.getMonth().split("-")[0]), Integer.valueOf(req.getMonth().split("-")[1]));
            Map<String, ChartResult> map = new HashMap<>();
            list.stream().forEach(x -> {
                map.put(x.getUnit(), x);
            });
            for (int i = 0; i < daysInMonth; i++) {
                String unit = req.getMonth() + "-" + (i < 9 ? "0" + (i + 1) : (i + 1));
                if (map.containsKey(unit)) {
                    listNew.add(map.get(unit));
                } else {
                    ChartResult chartResult = new ChartResult();
                    chartResult.setUnit(unit);
                    chartResult.setAmount("0");
                    chartResult.setHasReceiveAmount("0");
                    chartResult.setNum("0");
                    listNew.add(chartResult);
                }
            }

        } else if (req.getTimeType() == 2) {
            list = homePageMapper.yearOrderAmountChart(req.getYear());
            //补全没有数据的日期
            int monthsInYear = getMonthsInYear(Integer.valueOf(req.getYear()));

            Map<String, ChartResult> map = new HashMap<>();
            list.stream().forEach(x -> {
                map.put(x.getUnit(), x);
            });

            for (int i = 0; i < monthsInYear; i++) {
                String unit = req.getYear() + "-" + (i < 9 ? "0" + (i + 1) : (i + 1));
                if (map.containsKey(unit)) {
                    listNew.add(map.get(unit));
                } else {
                    ChartResult chartResult = new ChartResult();
                    chartResult.setUnit(unit);
                    chartResult.setAmount("0");
                    chartResult.setHasReceiveAmount("0");
                    chartResult.setNum("0");
                    listNew.add(chartResult);
                }

            }
        }

        return AjaxResult.success(listNew);
    }

    public static void main(String[] args) {
        int year = 2022;
        int month = 11; // 11代表11月

        int daysInMonth = getDaysInMonth(year, month);
        int monthsInYear = getMonthsInYear(2024);
        System.out.println(monthsInYear);

        System.out.println("The number of days in " + month + "/" + year + " is: " + daysInMonth);
    }

    public static int getDaysInMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1); // 月份是从0开始计算的，因此要减1

        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    public static int getMonthsInYear(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, 0, 1); // 月份是从0开始计算的，因此要减1

        return calendar.getActualMaximum(Calendar.MONTH) + 1;
    }

    @Override
    public AjaxResult rankingList(RankingListReq req) {

        List<RankingResult> list = new ArrayList<>();

        //1设计师 2表现师 3销售佣金
        if (req.getType() == 1) {
            list = homePageMapper.rankingCustomerList();
        } else if (req.getType() == 2) {
            list = homePageMapper.rankingStoreList();
        } else if (req.getType() == 3) {
            list = homePageMapper.rankingSaleList();
        }

        Integer i = 1;
        //添加排名
        for (RankingResult s : list) {
            s.setRanking(i++);
        }

        return AjaxResult.success(list);
    }

    @Autowired
    private WorksTypeService worksTypeService;


    @Override
    public AjaxResult classificationProportion(ChartReq req) {
        //查询当前所有的二级分类
        List<WorksType> worksTypes = worksTypeService.worksTypeList();

        List<WorksType> workTypeIdList = new ArrayList<>();

        worksTypes.stream().forEach(worksType -> {
            List<WorksType> childList = worksType.getChildList();
            childList.stream().forEach(child -> {
                workTypeIdList.add(child);
            });
        });

        //1 近一月  2 近一年
        List<ClassificationProportionResult> classificationProportionResultList = homePageMapper.classificationProportion(req);
        Map<String, Object> result = new HashMap<>();
        result.put("worksTypeList", workTypeIdList);
        result.put("classificationProportionResultList", classificationProportionResultList);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult newOldCustomers(ChartReq req) {
        List<NewOldCustomersResult> newOldCustomersResultList = homePageMapper.newOldCustomers(req);
        Integer newCount = 0;
        Integer oldCount = 0;
        for (NewOldCustomersResult newOldCustomersResult : newOldCustomersResultList) {
            //用户注册时间是否大于查询的年月开始时间 1 是 2 否
            if (newOldCustomersResult.getIsNewCustomer() == 1) {
                newCount = newCount + 1;
            } else {
                oldCount = oldCount + 1;
            }
        }
        Map<String, Integer> result = new HashMap<>();
        result.put("newCount", newCount);
        result.put("oldCount", oldCount);
        return AjaxResult.success(result);
    }

}
