package com.ruoyi.inspection.service.impl;

import com.ruoyi.inspection.domain.InspectionRecordTable;
import com.ruoyi.inspection.domain.InspectionManageTable;
import com.ruoyi.inspection.domain.VoAttendanceReport;
import com.ruoyi.inspection.mapper.AttendanceReportMapper;
import com.ruoyi.inspection.service.IAttendanceReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AttendanceReportService implements IAttendanceReportService {

    @Autowired
    private AttendanceReportMapper attendanceReportMapper;

    // 可视化柱形统计图
    @Override
    public List<VoAttendanceReport> ColumnVisualization(VoAttendanceReport voAttendanceReport) {
//        if (voAttendanceReport.getStartTime() == null || voAttendanceReport.getEndTime() == null){
//            LocalDate now = LocalDate.now();
//            LocalDate firstDayOfMonth = now.withDayOfMonth(1);
//            LocalDate lastDayOfMonth = now.withDayOfMonth(now.lengthOfMonth());
//
//            voAttendanceReport.setDefaultStartTime(firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//            voAttendanceReport.setDefaultEndTime(lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//        }

        return attendanceReportMapper.ColumnVisualization(voAttendanceReport);
    }

    /**
     * 构造 ECharts 柱状图所需的数据格式
     *
     * @param voAttendanceReport 查询参数
     * @return ECharts 数据格式
     */
    public Map<String, Object> getEchartsData(VoAttendanceReport voAttendanceReport) {
        List<VoAttendanceReport> list = ColumnVisualization(voAttendanceReport); // 获取柱状图数据列表

        // 构建 柱形图 需要的数据格式
        Map<String, Object> echartsData = new HashMap<>();
        List<String> xAxisData = new ArrayList<>();
        List<Integer> seriesData = new ArrayList<>();


        int monthTotal = 0  ;
        for (VoAttendanceReport report : list) {
            xAxisData.add(report.getInspectionPoint());
            seriesData.add(report.getCount());
            monthTotal += report.getCount();
        }

        echartsData.put("xAxis", xAxisData);
        echartsData.put("seriesData", seriesData);
        echartsData.put("monthTotal", monthTotal);

        return echartsData;
    }


    // 可视化圆形统计图
    @Override
    public List<VoAttendanceReport> RoundListVisualization(VoAttendanceReport voAttendanceReport) {
//        if (voAttendanceReport.getStartTime() == null || voAttendanceReport.getEndTime() == null){
//            LocalDate now = LocalDate.now();
//            LocalDate firstDayOfMonth = now.withDayOfMonth(1);
//            LocalDate lastDayOfMonth = now.withDayOfMonth(now.lengthOfMonth());
//
//            voAttendanceReport.setDefaultStartTime(firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//            voAttendanceReport.setDefaultEndTime(lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//        }
        return attendanceReportMapper.RoundListVisualization(voAttendanceReport);
    }

    /**
     * 构造 ECharts 饼图所需的数据格式
     *
     * @return ECharts 数据格式
     */
    public Map<String, Object> getEchartsPieChartData(VoAttendanceReport voAttendanceReport) {
        List<VoAttendanceReport> list = RoundListVisualization(voAttendanceReport); // 获取饼图数据列表

        // 构建 圆形图 需要的数据格式
        Map<String, Object> echartsData = new HashMap<>();
        List<Map<String, Object>> seriesData = new ArrayList<>();

        for (VoAttendanceReport data : list) {
            Map<String, Object> item = new HashMap<>();
            item.put("name", data.getInspectorId());
            item.put("value", data.getUserCount());
            seriesData.add(item);
        }

        echartsData.put("seriesData", seriesData);

        return echartsData;
    }

    // 总条数
    @Override
    public int tatol() {
        return attendanceReportMapper.total();
    }

    @Override
    public int monthTota(VoAttendanceReport voAttendanceReport) {
          if (voAttendanceReport.getStartTime() == null || voAttendanceReport.getEndTime() == null){
          LocalDate now = LocalDate.now();
           LocalDate firstDayOfMonth = now.withDayOfMonth(1);
           LocalDate lastDayOfMonth = now.withDayOfMonth(now.lengthOfMonth());

           voAttendanceReport.setDefaultStartTime(firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            voAttendanceReport.setDefaultEndTime(lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
          int monthTotal = 0;
          List<VoAttendanceReport> list = attendanceReportMapper.monthTotal(voAttendanceReport);
          for (VoAttendanceReport T : list){
              monthTotal += T.getCount();
          }
        return monthTotal;
    }


    // 按天趋势统计，返回 ECharts 折线图所需的 xAxis(date) 与 seriesData(count)
    @Override
    public Map<String, Object> trendDaily(VoAttendanceReport voAttendanceReport) {
        ensureDefaultRange(voAttendanceReport);
        List<Map<String, Object>> raw = attendanceReportMapper.trendDaily(voAttendanceReport);
        List<String> xAxis = new ArrayList<>();
        List<Integer> seriesData = new ArrayList<>();
        for (Map<String, Object> row : raw) {
            xAxis.add(String.valueOf(row.get("stat_date")));
            Object c = row.get("cnt");
            seriesData.add(c == null ? 0 : Integer.parseInt(String.valueOf(c)));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", xAxis);
        result.put("seriesData", seriesData);
        return result;
    }

    // 按天双序列（distinct点位数 与 总次数）
    @Override
    public Map<String, Object> trendDailyDual(VoAttendanceReport voAttendanceReport) {
        List<Map<String, Object>> raw = attendanceReportMapper.trendDailyDual(voAttendanceReport);
        List<String> xAxis = new ArrayList<>();
        List<Integer> seriesPoint = new ArrayList<>();
        List<Integer> seriesUser = new ArrayList<>();
        for (Map<String, Object> row : raw) {
            xAxis.add(String.valueOf(row.get("stat_date")));
            Object pc = row.get("point_cnt");
            Object ic = row.get("inspect_cnt");
            seriesPoint.add(pc == null ? 0 : Integer.parseInt(String.valueOf(pc)));
            seriesUser.add(ic == null ? 0 : Integer.parseInt(String.valueOf(ic)));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", xAxis);
        result.put("seriesPoint", seriesPoint);
        result.put("seriesUser", seriesUser);
        return result;
    }

    // 巡检类型占比
    @Override
    public Map<String, Object> typeProportion(VoAttendanceReport voAttendanceReport) {
        ensureDefaultRange(voAttendanceReport);
        List<VoAttendanceReport> list = attendanceReportMapper.typeProportion(voAttendanceReport);
        List<Map<String, Object>> seriesData = new ArrayList<>();
        for (VoAttendanceReport item : list) {
            Map<String, Object> d = new HashMap<>();
            d.put("name", item.getInspectionType());
            d.put("value", item.getCount());
            seriesData.add(d);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("seriesData", seriesData);
        return result;
    }

    // 覆盖率（期间已巡检点数量 / 管理表总点位数），以及分子分母
    @Override
    public Map<String, Object> coverage(VoAttendanceReport voAttendanceReport) {
        ensureDefaultRange(voAttendanceReport);
        int inspected = attendanceReportMapper.inspectedPointCount(voAttendanceReport);
        int total = attendanceReportMapper.totalManagePointCount();
        double rate = total == 0 ? 0.0 : (inspected * 1.0 / total);
        Map<String, Object> result = new HashMap<>();
        result.put("inspectedCount", inspected);
        result.put("totalCount", total);
        result.put("coverageRate", rate);
        return result;
    }

    // 未巡检点清单
    @Override
    public List<InspectionManageTable> listUninspectedPoints(VoAttendanceReport voAttendanceReport) {
        ensureDefaultRange(voAttendanceReport);
        return attendanceReportMapper.uninspectedPoints(voAttendanceReport);
    }

    // 点位类型对应的已巡检点数量（distinct）
    @Override
    public Map<String, Object> pointTypeCounts(VoAttendanceReport voAttendanceReport) {
        ensureDefaultRange(voAttendanceReport);
        List<Map<String, Object>> raw = attendanceReportMapper.pointTypeCounts(voAttendanceReport);
        List<String> xAxis = new ArrayList<>();
        List<Integer> seriesData = new ArrayList<>();
        for (Map<String, Object> row : raw) {
            xAxis.add(String.valueOf(row.get("type")));
            Object c = row.get("cnt");
            seriesData.add(c == null ? 0 : Integer.parseInt(String.valueOf(c)));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", xAxis);
        result.put("seriesData", seriesData);
        return result;
    }

    // 管理表点位状态分布
    @Override
    public Map<String, Object> statusDistribution() {
        List<Map<String, Object>> raw = attendanceReportMapper.statusDistribution();
        List<Map<String, Object>> seriesData = new ArrayList<>();
        for (Map<String, Object> row : raw) {
            Map<String, Object> d = new HashMap<>();
            d.put("name", row.get("status"));
            d.put("value", row.get("cnt"));
            seriesData.add(d);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("seriesData", seriesData);
        return result;
    }

    // 按月双序列（distinct点位数 与 总次数）
    @Override
    public Map<String, Object> trendMonthlyDual(VoAttendanceReport voAttendanceReport) {
        List<Map<String, Object>> raw = attendanceReportMapper.trendMonthlyDual(voAttendanceReport);
        List<String> xAxis = new ArrayList<>();
        List<Integer> seriesPoint = new ArrayList<>();
        List<Integer> seriesUser = new ArrayList<>();
        for (Map<String, Object> row : raw) {
            xAxis.add(String.valueOf(row.get("stat_month")));
            Object pc = row.get("point_cnt");
            Object ic = row.get("inspect_cnt");
            seriesPoint.add(pc == null ? 0 : Integer.parseInt(String.valueOf(pc)));
            seriesUser.add(ic == null ? 0 : Integer.parseInt(String.valueOf(ic)));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", xAxis);
        result.put("seriesPoint", seriesPoint);
        result.put("seriesUser", seriesUser);
        return result;
    }

    // 巡检人统计（三合一：总/月/日）
    @Override
    public Map<String, Object> inspectorStats3(VoAttendanceReport voAttendanceReport) {
        // total
        List<VoAttendanceReport> totalList = attendanceReportMapper.inspectorStatsTotal(voAttendanceReport);
        List<Map<String, Object>> totalSeries = new ArrayList<>();
        for (VoAttendanceReport item : totalList) {
            Map<String, Object> d = new HashMap<>();
            d.put("name", item.getInspectorId());
            d.put("value", item.getUserCount());
            totalSeries.add(d);
        }

        // month (当月)
        List<VoAttendanceReport> monthList = attendanceReportMapper.inspectorStatsMonth(voAttendanceReport);
        List<Map<String, Object>> monthSeries = new ArrayList<>();
        for (VoAttendanceReport item : monthList) {
            Map<String, Object> d = new HashMap<>();
            d.put("name", item.getInspectorId());
            d.put("value", item.getUserCount());
            monthSeries.add(d);
        }

        // day (本日)
        List<VoAttendanceReport> dayList = attendanceReportMapper.inspectorStatsDay(voAttendanceReport);
        List<Map<String, Object>> daySeries = new ArrayList<>();
        for (VoAttendanceReport item : dayList) {
            Map<String, Object> d = new HashMap<>();
            d.put("name", item.getInspectorId());
            d.put("value", item.getUserCount());
            daySeries.add(d);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("total", totalSeries);
        result.put("month", monthSeries);
        result.put("day", daySeries);
        return result;
    }

    // 巡检点统计（三合一：总/月/日），用于柱状图
    @Override
    public Map<String, Object> pointStats3(VoAttendanceReport voAttendanceReport) {
        Map<String, Object> out = new HashMap<>();

        // total：使用 ColumnVisualization（不限定时间，尊重外部过滤条件）
        List<VoAttendanceReport> total = attendanceReportMapper.ColumnVisualization(voAttendanceReport);
        Map<String, Object> t = new HashMap<>();
        List<String> tx = new ArrayList<>();
        List<Integer> ts = new ArrayList<>();
        for (VoAttendanceReport r : total) { tx.add(r.getInspectionPoint()); ts.add(r.getCount()); }
        t.put("xAxis", tx); t.put("seriesData", ts);
        out.put("total", t);

        // month：调用新增 SQL（当月数据），不依赖前端传参
        List<VoAttendanceReport> month = attendanceReportMapper.pointStatsMonth(voAttendanceReport);
        Map<String, Object> m = new HashMap<>();
        List<String> mx = new ArrayList<>();
        List<Integer> ms = new ArrayList<>();
        for (VoAttendanceReport r : month) { mx.add(r.getInspectionPoint()); ms.add(r.getCount()); }
        m.put("xAxis", mx); m.put("seriesData", ms);
        out.put("month", m);

        // day：调用新增 SQL（本日数据）
        List<VoAttendanceReport> day = attendanceReportMapper.pointStatsDay(voAttendanceReport);
        Map<String, Object> d = new HashMap<>();
        List<String> dx = new ArrayList<>();
        List<Integer> ds = new ArrayList<>();
        for (VoAttendanceReport r : day) { dx.add(r.getInspectionPoint()); ds.add(r.getCount()); }
        d.put("xAxis", dx); d.put("seriesData", ds);
        out.put("day", d);

        return out;
    }

    // 工具方法：如未传入时间范围则默认使用本月范围
    private void ensureDefaultRange(VoAttendanceReport voAttendanceReport) {
        if (voAttendanceReport.getStartTime() == null || voAttendanceReport.getEndTime() == null) {
            LocalDate now = LocalDate.now();
            LocalDate firstDayOfMonth = now.withDayOfMonth(1);
            LocalDate lastDayOfMonth = now.withDayOfMonth(now.lengthOfMonth());
            voAttendanceReport.setDefaultStartTime(firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            voAttendanceReport.setDefaultEndTime(lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
    }

}
