package com.sw.common.accessory.utils;

import com.sw.common.accessory.api.feignCilent.YbFeignClients;
import com.sw.common.accessory.api.model.AccessoryMaterialDto;
import com.sw.common.accessory.server.dto.ComputingTimeDto;
import com.sw.common.core.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DateCountTools {
    @Autowired
    private YbFeignClients ybFeignClients;

    /**
     * 计算返回结果
     *
     * @param materialCode
     * @param startTime
     * @param endTime
     * @return unitOfLife   寿命单位
     * useLife  额定寿命
     * weightValue 权重值
     * spanMonth    是否跨月
     * spanMonthCount  跨月次数
     * dateCount-yyyy-MM  每月每段统计结果
     */
    public ComputingTimeDto computingTime(String materialCode, Date startTime, Date endTime) {
        ComputingTimeDto computingTimeDto = new ComputingTimeDto();
        //todo 物料查询寿命模型,查看寿命单位
        Result<AccessoryMaterialDto> accessoryMaterial = ybFeignClients.getByMaterialCode(materialCode);
        if (accessoryMaterial.getCode().equals(200) && null != accessoryMaterial.getData()) {
            AccessoryMaterialDto accessoryMaterialDto = accessoryMaterial.getData();
            //寿命单位
            computingTimeDto.setUnitOfLife(accessoryMaterialDto.getUnitOfLife());
            //额定寿命
            computingTimeDto.setUseLife(accessoryMaterialDto.getUseLife());
            //权重值
            computingTimeDto.setWeightValue(accessoryMaterialDto.getWeightValue());
        }
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(startTime);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(endTime);
        int startYear = calendar1.get(Calendar.YEAR);
        int endYear = calendar2.get(Calendar.YEAR);
        // todo 检验时间是否跨年
        if (endYear - startYear > 0) {
            //是否跨年
            for (int i = 1; i < 3; i++) {
                //计算上一年份的最后时间
                if (i == 1) {
                    Date lastTime = lastYear(startTime);
                    computingTimeDto = monthCalculation(startTime, lastTime, computingTimeDto);
                }
                //计算当前年份的最开始时间
                if (i == 2) {
                    Date firstTime = firstYear(endTime);
                    computingTimeDto = monthCalculation(firstTime, endTime, computingTimeDto);
                }
            }

        } else {
            //是否跨年
            computingTimeDto = monthCalculation(startTime, endTime, computingTimeDto);
        }
        return computingTimeDto;
    }

    /**
     * 跨月计算
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public ComputingTimeDto monthCalculation(Date startTime, Date endTime, ComputingTimeDto computingTimeDto) {
        List<Map<String, Integer>> monthCounts = new ArrayList<>();
        //todo 校验是否跨月
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(startTime);
        //获取开始时间的月份
        int startMonth = calendar1.get(Calendar.MONTH) + 1;
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(endTime);
        int endMonth = calendar2.get(Calendar.MONTH) + 1;
        int spanMonth = endMonth - startMonth;
        if (spanMonth == 0) {
            //是否跨月
            computingTimeDto.setSpanMonth(false);
            //跨月次数
            computingTimeDto.setSpanMonthCount(spanMonth + 1);
        } else {
            //是否跨月
            computingTimeDto.setSpanMonth(true);
            //跨月次数
            computingTimeDto.setSpanMonthCount(spanMonth + 1);
        }
        //todo 跨月计算
        if (computingTimeDto.isSpanMonth()) {
            //获取跨月次数
            Integer spanMonthCount = computingTimeDto.getSpanMonthCount();
            for (int i = 0; i < spanMonthCount; i++) {
                Map<String, Integer> map = new HashMap<>();
                //第一个月
                if (i == 0) {
                    //开炉时间早于12点，这一天算，晚于12点这一天不算；
                    Calendar calendar3 = Calendar.getInstance();
                    calendar3.setTime(startTime);
                    int year1 = calendar3.get(Calendar.YEAR);
                    int startMonth1 = calendar3.get(Calendar.MONTH) + 1;
                    int startDay = calendar3.get(Calendar.DAY_OF_MONTH);
                    int startHour = calendar3.get(Calendar.HOUR_OF_DAY);
                    Date date = lastMonth(startTime);
                    Calendar calendar4 = Calendar.getInstance();
                    calendar4.setTime(date);
                    int endDay = calendar4.get(Calendar.DAY_OF_MONTH);
                    int endHour = calendar4.get(Calendar.HOUR_OF_DAY);
                    int day = dateCount(startDay, startHour, endDay, endHour);

                    map.put("dateCount" + "-" + year1 + "-" + startMonth1, day);
                    monthCounts.add(map);
                }
                //跨一个月以上
                if (i > 0 && i < spanMonthCount - 1) {
                    Calendar calendar4 = Calendar.getInstance();
                    calendar4.setTime(startTime);
                    calendar4.add(Calendar.MONTH, i);
                    Date firstMonth = firstMonth(calendar4.getTime());
                    Date lastMonth = lastMonth(calendar4.getTime());
                    Calendar calendar5 = Calendar.getInstance();
                    calendar5.setTime(firstMonth);
                    Calendar calendar6 = Calendar.getInstance();
                    calendar6.setTime(lastMonth);
                    int year1 = calendar5.get(Calendar.YEAR);
                    int startMonth1 = calendar5.get(Calendar.MONTH) + 1;
                    int startDay = calendar5.get(Calendar.DAY_OF_MONTH);
                    int startHour = calendar5.get(Calendar.HOUR_OF_DAY);
                    int endDay = calendar6.get(Calendar.DAY_OF_MONTH);
                    int endHour = calendar6.get(Calendar.HOUR_OF_DAY);
                    int day = dateCount(startDay, startHour, endDay, endHour);
                    //时间统计结果
                    map.put("dateCount" + "-" + year1 + "-" + startMonth1, day);
                    monthCounts.add(map);

                }
                //最后一个月
                if (i == spanMonthCount - 1) {
                    //开炉时间早于12点，这一天算，晚于12点这一天不算；
                    Date date = firstMonth(endTime);
                    Calendar calendar3 = Calendar.getInstance();
                    calendar3.setTime(date);
                    int startDay = calendar3.get(Calendar.DAY_OF_MONTH);
                    int startHour = calendar3.get(Calendar.HOUR_OF_DAY);
                    Calendar calendar4 = Calendar.getInstance();
                    calendar4.setTime(endTime);
                    int year1 = calendar3.get(Calendar.YEAR);
                    int startMonth1 = calendar3.get(Calendar.MONTH) + 1;
                    int endDay = calendar4.get(Calendar.DAY_OF_MONTH);
                    int endHour = calendar4.get(Calendar.HOUR_OF_DAY);
                    int day = dateCount(startDay, startHour, endDay, endHour);
                    //时间统计结果
                    map.put("dateCount" + "-" + year1 + "-" + startMonth1, day);
                    monthCounts.add(map);
                }
            }
        }
        //todo 非跨月计算
        if (!computingTimeDto.isSpanMonth()) {
            Map<String, Integer> map = new HashMap<>();
            int startDay = calendar1.get(Calendar.DAY_OF_MONTH);
            int startHour = calendar1.get(Calendar.HOUR_OF_DAY);
            int endDay = calendar2.get(Calendar.DAY_OF_MONTH);
            int endHour = calendar2.get(Calendar.HOUR_OF_DAY);
            int year1 = calendar1.get(Calendar.YEAR);
            int startMonth1 = calendar1.get(Calendar.MONTH) + 1;
            int day = dateCount(startDay, startHour, endDay, endHour);
            //时间统计结果
            map.put("dateCount" + "-" + year1 + "-" + startMonth1, day);
            monthCounts.add(map);
        }
        List<Map<String, Integer>> monthCounts1 = computingTimeDto.getMonthCounts();
        if (null == monthCounts1 || monthCounts1.size() < 1) {
            computingTimeDto.setMonthCounts(monthCounts);
        } else {
            monthCounts.forEach(entity -> {
                computingTimeDto.getMonthCounts().add(entity);
            });
        }
        computingTimeDto.setSpanMonthCount(computingTimeDto.getMonthCounts().size());
        return computingTimeDto;
    }

    public int dateCount(int satrtDay, int satrtHour, int endDay, int endHour) {
        int day;
        /**
         * 开炉时间早于12点，这一天算，晚于12点这一天不算；
         * 停炉时间早于12点这一天不算，晚于12点这一天算；
         */
        if (satrtHour < 12 && endHour >= 12) {
            day = endDay - satrtDay + 1;
        } else if ((satrtHour >= 12 && endHour >= 12) || (satrtHour < 12 && endHour < 12)) {
            day = endDay - satrtDay;
        } else {
            day = endDay - satrtDay - 1;
        }
        return day;
    }

    /**
     * 获取当月的最后一天
     *
     * @param date
     * @return
     */
    public Date lastMonth(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //获取年
        int year = calendar.get(Calendar.YEAR);
        //获取月份，0表示1月份
        int month = calendar.get(Calendar.MONTH) + 1;
        //获取本月最大天数
        int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        try {
            return format.parse(year + "-" + month + "-" + lastDay + " 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当年的最后一天
     *
     * @param date
     * @return
     */
    public Date lastYear(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //获取年
        int year = calendar.get(Calendar.YEAR);
        //获取当前的最大月份
        int month = calendar.getActualMaximum(Calendar.MONTH) + 1;
        //获取本月最大天数
        int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        try {
            return format.parse(year + "-" + month + "-" + lastDay + " 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Date firstYear(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //获取年
        int year = calendar.get(Calendar.YEAR);
        //获取当前的最小月份
        int month = calendar.getActualMinimum(Calendar.MONTH) + 1;
        //获取本月最小天数
        int lastDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        try {
            return format.parse(year + "-" + month + "-" + lastDay + " 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当月的第一天
     *
     * @param date
     * @return
     */
    public Date firstMonth(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //获取年
        int year = calendar.get(Calendar.YEAR);
        //获取月份，0表示1月份
        int month = calendar.get(Calendar.MONTH) + 1;
        //获取本月最小天数
        int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        try {
            return format.parse(year + "-" + month + "-" + firstDay + " 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}
