package xiaoqu.home.open.service.db1.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import xiaoqu.home.open.model.db1.*;
import xiaoqu.home.open.mapper.db1.StatisticsMonthLogMapper;
import xiaoqu.home.open.service.db1.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 月度统计 服务实现类
 * </p>
 *
 * @author mk
 * @since 2023-10-18
 */
@Service
public class StatisticsMonthLogServiceImpl extends ServiceImpl<StatisticsMonthLogMapper, StatisticsMonthLog> implements StatisticsMonthLogService {
    @Autowired
    private MonthlyStatisticsService monthlyStatisticsService;
    @Autowired
    private HardwareService hardwareService;
    @Autowired
    private RfidInfoService rfidInfoService;
    @Autowired
    private DistrictService districtService;
    @Autowired
    private EquipmentRepairRecordingService equipmentRepairRecordingService;

    public List<StatisticsMonthLog> insertStatisticsMonthLogByMonth(String year, String month, Integer type) {
        QueryWrapper<MonthlyStatistics> monthlyStatisticswrapper = Wrappers.query();
        monthlyStatisticswrapper.select("DATE_FORMAT(statistics_time, '%Y-%m') position,district_id,agent_id,COUNT(*) gender,SUM(paper_length) paper_length,SUM(paper_count) paper_count,SUM(total_count) total_count,SUM(use_count) use_count");
        monthlyStatisticswrapper.eq("soft_delete", 0);
        monthlyStatisticswrapper.apply("year(statistics_time)={0}", year);
        monthlyStatisticswrapper.apply("month(statistics_time)={0}", month);
        monthlyStatisticswrapper.groupBy("district_id");
        List<MonthlyStatistics> list = monthlyStatisticsService.list(monthlyStatisticswrapper);
        HashMap<Long, StatisticsMonthLog> agentMap = new HashMap<Long, StatisticsMonthLog>();
        HashMap<Long, StatisticsMonthLog> districtMap = new HashMap<Long, StatisticsMonthLog>();
        String curmonth = year + "-" + month;
        //用纸数据填充
        for (MonthlyStatistics monthlyStatistics : list) {
            if (!districtMap.containsKey(monthlyStatistics.getDistrictId())) {
                StatisticsMonthLog statisticsMonthLog = new StatisticsMonthLog();
                statisticsMonthLog.setParseType(0);
                statisticsMonthLog.setCustomType(0);
                statisticsMonthLog.setAgentId(monthlyStatistics.getAgentId());
                statisticsMonthLog.setPropertyId(monthlyStatistics.getPropertyId());
                statisticsMonthLog.setDistrictId(monthlyStatistics.getDistrictId());
                statisticsMonthLog.setMonth(curmonth);
                statisticsMonthLog.setPaperLength(monthlyStatistics.getPaperLength().longValue());
                statisticsMonthLog.setPaperCount(monthlyStatistics.getPaperCount());
                statisticsMonthLog.setTotalCount(monthlyStatistics.getTotalCount());
                statisticsMonthLog.setUseCount(monthlyStatistics.getUseCount());
                statisticsMonthLog.setHardwareDayCount(monthlyStatistics.getGender());
                District district = districtService.getById(monthlyStatistics.getDistrictId());
                statisticsMonthLog.setCity(district.getCity());
                districtMap.put(monthlyStatistics.getDistrictId(), statisticsMonthLog);

                if (agentMap.containsKey(monthlyStatistics.getAgentId())) {
                    StatisticsMonthLog curAgentStatisticsMonthLog = agentMap.get(monthlyStatistics.getAgentId());
                    curAgentStatisticsMonthLog.setPaperLength(curAgentStatisticsMonthLog.getPaperLength() + monthlyStatistics.getPaperLength());
                    curAgentStatisticsMonthLog.setPaperCount(curAgentStatisticsMonthLog.getPaperCount() + monthlyStatistics.getPaperCount());
                    curAgentStatisticsMonthLog.setTotalCount(curAgentStatisticsMonthLog.getTotalCount() + monthlyStatistics.getTotalCount());
                    curAgentStatisticsMonthLog.setUseCount(curAgentStatisticsMonthLog.getUseCount() + monthlyStatistics.getUseCount());
                    curAgentStatisticsMonthLog.setHardwareDayCount(curAgentStatisticsMonthLog.getHardwareDayCount() + monthlyStatistics.getGender());
                } else {
                    StatisticsMonthLog agentstatisticsMonthLog = new StatisticsMonthLog();
                    agentstatisticsMonthLog.setParseType(0);
                    agentstatisticsMonthLog.setCustomType(0);
                    agentstatisticsMonthLog.setAgentId(monthlyStatistics.getAgentId());
                    agentstatisticsMonthLog.setPropertyId(monthlyStatistics.getPropertyId());
                    agentstatisticsMonthLog.setDistrictId(monthlyStatistics.getDistrictId());
                    agentstatisticsMonthLog.setMonth(curmonth);
                    agentstatisticsMonthLog.setPaperLength(monthlyStatistics.getPaperLength().longValue());
                    agentstatisticsMonthLog.setPaperCount(monthlyStatistics.getPaperCount());
                    agentstatisticsMonthLog.setTotalCount(monthlyStatistics.getTotalCount());
                    agentstatisticsMonthLog.setUseCount(monthlyStatistics.getUseCount());
                    agentstatisticsMonthLog.setHardwareDayCount(monthlyStatistics.getGender());
                    agentstatisticsMonthLog.setHardwareCount(0);
                    agentstatisticsMonthLog.setRfidCount(0);
                    agentstatisticsMonthLog.setEquipmentRepairCount(0);
                    agentMap.put(monthlyStatistics.getAgentId(), statisticsMonthLog);
                }
            }
        }



        //设备数统计
        if(type==0){
            QueryWrapper<Hardware> hardwareQueryWrapper = Wrappers.query();
            hardwareQueryWrapper.eq("soft_delete", 0);
            hardwareQueryWrapper.select("agent_id,district_id,count(*) status");
            hardwareQueryWrapper.groupBy("district_id");
            List<Hardware> hardwareList = hardwareService.list(hardwareQueryWrapper);
            for (Hardware hardware : hardwareList) {
                if (hardware.getDistrictId() != null && hardware.getDistrictId() > 0) {
                    StatisticsMonthLog statisticsMonthLog = districtMap.get(hardware.getDistrictId());
                    if (statisticsMonthLog != null) {
                        statisticsMonthLog.setHardwareCount(hardware.getStatus());
                    }
                    StatisticsMonthLog statisticsMonthLogAgent = agentMap.get(hardware.getAgentId());
                    if (statisticsMonthLogAgent != null) {
                        statisticsMonthLogAgent.setHardwareCount(statisticsMonthLogAgent.getHardwareCount() + hardware.getStatus());
                    }
                }
            }
        }else if(type==1){
            QueryWrapper<MonthlyStatistics> monthlyStatisticsDaywrapper = Wrappers.query();
            monthlyStatisticsDaywrapper.select("district_id,agent_id,COUNT(*) gender");
            monthlyStatisticsDaywrapper.eq("soft_delete", 0);
            monthlyStatisticsDaywrapper.apply("year(statistics_time)={0}", year);
            monthlyStatisticsDaywrapper.apply("month(statistics_time)={0}", month);
            monthlyStatisticsDaywrapper.apply("day(statistics_time)={0}", 28);
            monthlyStatisticsDaywrapper.groupBy("district_id");
            List<MonthlyStatistics> hardwarelist = monthlyStatisticsService.list(monthlyStatisticsDaywrapper);
            int i =0;
            for (MonthlyStatistics monthlyStatistics : hardwarelist) {
                try {
                    if (monthlyStatistics.getDistrictId() != null && monthlyStatistics.getDistrictId() > 0) {
                       Integer count =  monthlyStatistics.getGender()==null?0:monthlyStatistics.getGender();
                        StatisticsMonthLog statisticsMonthLog = districtMap.get(monthlyStatistics.getDistrictId());
                        if (statisticsMonthLog != null) {
                            statisticsMonthLog.setHardwareCount(count);
                        }
                        StatisticsMonthLog statisticsMonthLogAgent = agentMap.get(monthlyStatistics.getAgentId());
                        if (statisticsMonthLogAgent != null) {
                            statisticsMonthLogAgent.setHardwareCount(statisticsMonthLogAgent.getHardwareCount() + count);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(i);
                    continue;
                }
                i++;
            }
        }




        //故障数统计
        QueryWrapper<EquipmentRepairRecording> recordingQueryWrapper = Wrappers.query();
        recordingQueryWrapper.eq("soft_delete", 0);
        recordingQueryWrapper.eq("effective_state",1);
        recordingQueryWrapper.select("agent_id,district_id,count(*) fault_count");
        recordingQueryWrapper.apply("year(create_time)={0}", year);
        recordingQueryWrapper.apply("month(create_time)={0}", month);
        recordingQueryWrapper.groupBy("district_id");
        List<EquipmentRepairRecording> equipmentRepairRecordingList = equipmentRepairRecordingService.list(recordingQueryWrapper);
        for (EquipmentRepairRecording equipmentRepairRecording : equipmentRepairRecordingList) {
            if (equipmentRepairRecording.getDistrictId() != null && equipmentRepairRecording.getDistrictId() > 0) {
                StatisticsMonthLog statisticsMonthLog = districtMap.get(equipmentRepairRecording.getDistrictId());
                if (statisticsMonthLog != null) {
                    statisticsMonthLog.setEquipmentRepairCount(equipmentRepairRecording.getFaultCount());
                }
                StatisticsMonthLog statisticsMonthLogAgent = agentMap.get(equipmentRepairRecording.getAgentId());
                if (statisticsMonthLogAgent != null) {
                    statisticsMonthLogAgent.setEquipmentRepairCount(statisticsMonthLogAgent.getHardwareCount() + equipmentRepairRecording.getFaultCount());
                }
            }
        }


        //故障数统计
        QueryWrapper<RfidInfo> rfidInfoQueryWrapper = Wrappers.query();
        rfidInfoQueryWrapper.eq("soft_delete", 0);
        rfidInfoQueryWrapper.select("agent_id,district_id,count(*) isused");
        rfidInfoQueryWrapper.apply("year(create_time)={0}", year);
        rfidInfoQueryWrapper.apply("month(create_time)={0}", month);
        rfidInfoQueryWrapper.groupBy("district_id");
        List<RfidInfo> rfidInfoList = rfidInfoService.list(rfidInfoQueryWrapper);
        for (RfidInfo rfidInfo : rfidInfoList) {
            if (rfidInfo.getDistrictId() != null && rfidInfo.getDistrictId() > 0) {
                StatisticsMonthLog statisticsMonthLog = districtMap.get(rfidInfo.getDistrictId());
                if (statisticsMonthLog != null) {
                    statisticsMonthLog.setRfidCount(rfidInfo.getIsused());
                }
                StatisticsMonthLog statisticsMonthLogAgent = agentMap.get(rfidInfo.getAgentId());
                if (statisticsMonthLogAgent != null) {
                    statisticsMonthLogAgent.setRfidCount(statisticsMonthLogAgent.getHardwareCount() + rfidInfo.getIsused());
                }
            }
        }

        ArrayList<StatisticsMonthLog> statisticsMonthLogs = new ArrayList<StatisticsMonthLog>();
        Iterator<Map.Entry<Long, StatisticsMonthLog>> agentIterator = agentMap.entrySet().iterator();
        while (agentIterator.hasNext()){
            Map.Entry<Long, StatisticsMonthLog> next = agentIterator.next();
            StatisticsMonthLog value = next.getValue();
            this.save(value);
        }
        Iterator<Map.Entry<Long, StatisticsMonthLog>> districtIterator = districtMap.entrySet().iterator();
        while (districtIterator.hasNext()){
            Map.Entry<Long, StatisticsMonthLog> next = districtIterator.next();
            StatisticsMonthLog value = next.getValue();
            this.save(value);
            statisticsMonthLogs.add(value);
        }


        return statisticsMonthLogs;

    }
}
