package com.rongwei.bscommon.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.EquEnergyRecordDao;
import com.rongwei.bscommon.sys.service.*;
import com.rongwei.bsentity.domain.EquEnergyMeterDosageDayDo;
import com.rongwei.bsentity.domain.EquEnergyRecordDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EquEnergyRecordServiceImpl extends ServiceImpl<EquEnergyRecordDao, EquEnergyRecordDo> implements EquEnergyRecordService {


    @Autowired
    private EquEnergyMeterDosageDayService equEnergyMeterDosageDayService;

    @Autowired
    private EquEnergyMeterDosageMonthService equEnergyMeterDosageMonthService;

    @Autowired
    private EquEnergyMeterCenterDosageDayService equEnergyMeterCenterDosageDayService;

    @Autowired
    private EquEnergyMeterCenterDosageMonthService equEnergyMeterCenterDosageMonthService;

    @Autowired
    private EquEnergyRecordDao equEnergyRecordDao;


    @Override
    public R calEnergyUsage() {
        //1.先将60天内计算出来的数据更新或者插入保存到 表具每日能源用量 equ_energy_meter_dosage_day表中
        this.calRecordDataToDosageDay(null);
        //2.根据equ_energy_meter_dosage_day中数据将近60天内每个日期的能源用量数据更新写入到 每月能源用量 equ_energy_meter_dosage_month
        equEnergyMeterDosageMonthService.calDayToMonth();
        //3.根据equ_energy_meter_dosage_day表中每日能源用量数据、能源成本中心与表具的关系和计算方式，equ_energy_meter_center_dosage_day
        equEnergyMeterCenterDosageDayService.calRecordDataToCenterDosageDay();
        //4.根据equ_energy_meter_center_dosage_day每日能源成本中心中数据将近60天内每个日期的能源用量数据更新写入到 每月能源用量equ_energy_meter_dosage_month表中
        equEnergyMeterCenterDosageMonthService.calRecordDataToCenterDosageMonth();
        return R.ok();
    }

    @Override
    public R calEnergyUsageByStartTime(String endTime) {
        //1.先将60天内计算出来的数据更新或者插入保存到 表具每日能源用量 equ_energy_meter_dosage_day表中
        this.calRecordDataToDosageDay(endTime);
        //2.根据equ_energy_meter_dosage_day中数据将近60天内每个日期的能源用量数据更新写入到 每月能源用量 equ_energy_meter_dosage_month
        equEnergyMeterDosageMonthService.calDayToMonth();
        //3.根据equ_energy_meter_dosage_day表中每日能源用量数据、能源成本中心与表具的关系和计算方式，equ_energy_meter_center_dosage_day
        equEnergyMeterCenterDosageDayService.calRecordDataToCenterDosageDay();
        //4.根据equ_energy_meter_center_dosage_day每日能源成本中心中数据将近60天内每个日期的能源用量数据更新写入到 每月能源用量equ_energy_meter_dosage_month表中
        equEnergyMeterCenterDosageMonthService.calRecordDataToCenterDosageMonth();
        return R.ok();
    }


    /**
     * 计算60天最新的 equ_energy_record 记录，插入 equ_energy_meter_dosage_day表
     *  月数据 按 表具id - 年 -月 统计
     * @return
     */
    private void calRecordDataToDosageDay(String endTime) {
        //间隔天数
        int intervalDays =60;
        // 获取当前日期
        LocalDate today = null;
        today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (endTime!=null){
            //根据传入的时间做当前日期
            today = LocalDate.parse(endTime, formatter);
        }
        // 计算60天前的日期
        LocalDate sixtyDaysAgo = today.minusDays(intervalDays);
        endTime = today.format(formatter)+" 23:59:59";
        String startTime = sixtyDaysAgo.format(formatter)+" 00:00:00";
        //获取60天内所有表具中最新记录的相差值
        List<EquEnergyMeterDosageDayDo> equEnergyMeterDosageDayDos = equEnergyRecordDao.calRecordDataToDosageDay(startTime,endTime);
        //根据表具,时间 分组 ，每个镖局补充 60 天的记录
        Map<String, Map<String, List<EquEnergyMeterDosageDayDo>>> collect = equEnergyMeterDosageDayDos.stream().collect(Collectors.groupingBy(EquEnergyMeterDosageDayDo::getMeterid,
                Collectors.groupingBy(EquEnergyMeterDosageDayDo::getCenterday)));
        List<EquEnergyMeterDosageDayDo>  dayList =new ArrayList<>();
        final EquEnergyMeterDosageDayDo[] dayDos= {null};
        final String[] dateKey = {""};
        final String[] tenantid = {""};
        final String[] ownedfactory = {""};
        LocalDate finalToday = today;
        collect.forEach((meterid, map) -> {
            tenantid[0] = map.values().stream().findFirst().get().get(0).getTenantid();
            ownedfactory[0] = map.values().stream().findFirst().get().get(0).getOwnedfactory();
            for (int i = 1; i < intervalDays; i++) {
                dateKey[0] =  finalToday.minusDays(i).format(formatter);
                if (!map.containsKey(dateKey[0])){
                    //表具能源用量 在该日期不存在记录，用量默认 null 新建记录
                    dayDos[0] =new EquEnergyMeterDosageDayDo();
                    dayDos[0].setCenterday(dateKey[0]);
                    dayDos[0].setMeterid(meterid);
                    dayDos[0].setTenantid(tenantid[0]);
                    dayDos[0].setOwnedfactory(ownedfactory[0]);
                }else {
                    //日表数据存
                    dayDos[0]=map.get(dateKey[0]).get(0);
                }
                dayDos[0].setId(SecurityUtil.getUUID());
                dayList.add( dayDos[0]);

            };

        });
        equEnergyMeterDosageDayService.deleteData();
        equEnergyMeterDosageDayService.saveBatch(dayList);
    }
}
