package com.hotwj.platform.workbench.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hotwj.platform.config.squareInfo.domain.HotSquareInfo;
import com.hotwj.platform.config.squareInfo.mapper.HotSquareInfoMapper;
import com.hotwj.platform.noticeManagerment.complaintAdvice.domain.HotComplaintAdvice;
import com.hotwj.platform.noticeManagerment.complaintAdvice.mapper.HotComplaintAdviceMapper;
import com.hotwj.platform.workbench.domain.vo.*;
import com.hotwj.platform.workbench.mapper.HeadquartersWorkbenchMapper;
import com.hotwj.platform.workbench.service.IHeadquartersWorkbenchService;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.service.ISysDictTypeService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 总部端工作台Service业务层处理
 *
 * @author shihongwei
 */
@RequiredArgsConstructor
@Service
public class HeadquartersWorkbenchServiceImpl implements IHeadquartersWorkbenchService {

    private final HeadquartersWorkbenchMapper headquartersWorkbenchMapper;
    private final ISysDictTypeService sysDictTypeService;
    private final HotSquareInfoMapper hotSquareInfoMapper;
    private final HotComplaintAdviceMapper hotComplaintAdviceMapper;

    @Override
    public List<HeadquartersTrainingStatsVo> getTrainingStats() {
        // 1. 获取所有启用的培训类型字典
        List<SysDictDataVo> dictDataList = sysDictTypeService.selectDictDataByType("hot_training_type");
        if (dictDataList != null) {
            dictDataList = dictDataList.stream()
                    .filter(item -> !"offline".equals(item.getDictValue()))
                    .collect(Collectors.toList());
        }

        // 2. 统计各类型培训计划数量
        List<TrainingTypeStatRow> statsList = headquartersWorkbenchMapper.selectTrainingTypeStats();

        // 将统计结果转为 Map<Type, Count>
        Map<String, Long> countMap = statsList.stream()
            .collect(Collectors.toMap(
                r -> r.getType(),
                r -> r.getCount(),
                (v1, v2) -> v1
            ));

        // 3. 组装结果
        List<HeadquartersTrainingStatsVo> result = new ArrayList<>();
        if (dictDataList != null) {
            for (SysDictDataVo dict : dictDataList) {
                Long count = countMap.getOrDefault(dict.getDictValue(), 0L);
                result.add(new HeadquartersTrainingStatsVo(dict.getDictLabel(), count));
            }
        }

        return result;
    }

    /**
     * 获取总部端某年月度学习折线图数据<p>
     * <p>
     * 口径说明：<p>
     * 1) 数据来源：hot_training_daily_stats（日统计表），按天汇总；仅统计已启用且未删除的企业（sys_company.status=1 且 is_deleted=0）。<p>
     * 2) 统计区间：当月1日 00:00:00 至 当月最后1日 23:59:59（startDate、endDate 均为包含边界）。<p>
     * 3) 指标定义：completed 来源于 daily_stats.completed_count，uncompleted 来源于 daily_stats.uncompleted_count。<p>
     * 4) 缺失补零：若某天无数据，返回 0，确保前端 X 轴为整月完整日历。<p>
     *
     * @param year  年份（如 2025）
     * @param month 月份（1-12）
     * @return 月度折线图数据（dates、completed、uncompleted 一一对应）
     */
    @Override
    public MonthlyStudyTrendVo getMonthlyStudyTrend(int year, int month) {
        Calendar cal = new GregorianCalendar(year, month - 1, 1, 0, 0, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date startDate = cal.getTime();
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        Date endDate = cal.getTime();

        List<MonthlyTrendRow> rows = headquartersWorkbenchMapper.selectMonthlyStudyTrendFromDailyStats(startDate, endDate);

        // 根据日期分组
        Map<String, MonthlyTrendRow> map = rows == null ? new HashMap<>() : rows.stream()
                .collect(Collectors.toMap(MonthlyTrendRow::getDay, r -> r, (a, b) -> a));

        List<String> dates = new ArrayList<>();
        List<Long> completed = new ArrayList<>();
        List<Long> uncompleted = new ArrayList<>();

        // 填充缺失日期
        Calendar iter = new GregorianCalendar(year, month - 1, 1, 0, 0, 0);
        iter.set(Calendar.MILLISECOND, 0);
        Calendar endExclusive = new GregorianCalendar(year, month - 1, 1, 0, 0, 0);
        endExclusive.set(Calendar.MILLISECOND, 0);
        endExclusive.add(Calendar.MONTH, 1);
        while (iter.getTime().before(endExclusive.getTime())) {
            int y = iter.get(Calendar.YEAR);
            int m = iter.get(Calendar.MONTH) + 1;
            int d = iter.get(Calendar.DAY_OF_MONTH);
            String dayStr = String.format("%04d-%02d-%02d", y, m, d);
            dates.add(dayStr);
            MonthlyTrendRow r = map.get(dayStr);
            completed.add(r != null && r.getCompleted() != null ? r.getCompleted() : 0L);
            uncompleted.add(r != null && r.getUncompleted() != null ? r.getUncompleted() : 0L);
            iter.add(Calendar.DAY_OF_MONTH, 1);
        }

        // 3. 组装结果
        return new MonthlyStudyTrendVo(dates, completed, uncompleted);
    }

    @Override
    public ViolationMonthlyBarVo getViolationMonthlyStats(Integer year) {
        Calendar cal = new GregorianCalendar();
        int y = (year == null || year <= 0) ? cal.get(Calendar.YEAR) : year;
        cal.set(y, Calendar.JANUARY, 1, 0, 0, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date startDate = cal.getTime();
        cal.add(Calendar.YEAR, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        Date endDate = cal.getTime();

        List<ViolationMonthlyRow> rows = headquartersWorkbenchMapper.selectViolationMonthlyCounts(startDate, endDate);
        Map<Integer, Long> monthCount = new HashMap<>();
        if (rows != null) {
            for (ViolationMonthlyRow r : rows) {
                try {
                    int m = Integer.parseInt(r.getMonth());
                    monthCount.put(m, r.getCnt() == null ? 0L : r.getCnt());
                } catch (Exception ignored) {
                }
            }
        }

        List<String> months = new ArrayList<>();
        List<Long> values = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            months.add(i + "月");
            values.add(monthCount.getOrDefault(i, 0L));
        }
        ViolationMonthlyBarVo vo = new ViolationMonthlyBarVo();
        vo.setMonths(months);
        vo.setValues(values);
        return vo;
    }

    @Override
    public HeadquartersHiddenDangerSummaryVo getHeadquartersHiddenDangerSummary(String regionCode) {
        // 处理区域代码：如果是省/市级别（以00结尾），截取有效前缀
        if (regionCode != null && regionCode.length() == 6) {
            if (regionCode.endsWith("0000")) {
                regionCode = regionCode.substring(0, 2);
            } else if (regionCode.endsWith("00")) {
                regionCode = regionCode.substring(0, 4);
            }
        }
        HeadquartersHiddenDangerSummaryVo vo = headquartersWorkbenchMapper.selectLatestHiddenDangerSummary(regionCode);
        if (vo == null) {
            vo = new HeadquartersHiddenDangerSummaryVo();
            vo.setEnterpriseCount(0L);
            vo.setVehicleCount(0L);
            vo.setPersonnelCount(0L);
            vo.setTotalCount(0L);
        } else {
            long ent = vo.getEnterpriseCount() == null ? 0L : vo.getEnterpriseCount();
            long veh = vo.getVehicleCount() == null ? 0L : vo.getVehicleCount();
            long per = vo.getPersonnelCount() == null ? 0L : vo.getPersonnelCount();
            vo.setEnterpriseCount(ent);
            vo.setVehicleCount(veh);
            vo.setPersonnelCount(per);
            vo.setTotalCount(ent + veh + per);
        }
        return vo;
    }

    private static final Set<String> PASSENGER_LABELS = new HashSet<>(Arrays.asList(
            "城市公共汽电客运", "道路旅客运输", "网约车", "巡游出租汽车", "水路旅客运输", "港口客运码头"
    ));

    private static final Set<String> GENERAL_LABELS = new HashSet<>(Arrays.asList(
            "道路普通货物运输", "道路货运场站", "水路普通货物运输", "港口普货码头", "渣土（普货）", "商砼（普货）"
    ));

    private static final Set<String> DANGEROUS_LABELS = new HashSet<>(Arrays.asList(
            "道路危险货物运输", "水路危险货物运输", "港口危货码头"
    ));

    @Override
    public RegionCompanyStatsVo getRegionCompanyStats(String regionCode) {
        // 处理区域代码：如果是省/市级别（以00结尾），截取有效前缀
        if (regionCode != null && regionCode.length() == 6) {
            if (regionCode.endsWith("0000")) {
                regionCode = regionCode.substring(0, 2);
            } else if (regionCode.endsWith("00")) {
                regionCode = regionCode.substring(0, 4);
            }
        }

        // 1. 获取所有行业字典数据
        List<SysDictDataVo> industryDicts = sysDictTypeService.selectDictDataByType("hot_industry");
        if (industryDicts == null) {
            industryDicts = new ArrayList<>();
        }

        // 2. 查询数据库统计数据
        List<Map<String, Object>> dbStats = headquartersWorkbenchMapper.selectCompanyIndustryCounts(regionCode);

        // 3. 构建映射关系：行业Code -> 分类（普货/危货/客运/其他）
        Map<String, String> categoryMap = new HashMap<>();
        for (SysDictDataVo dict : industryDicts) {
            String label = dict.getDictLabel();
            String code = dict.getDictValue();
            String category = "其他";
            if (label != null) {
                // 去除可能存在的首尾空格
                label = label.trim();
                if (PASSENGER_LABELS.contains(label)) {
                    category = "客运";
                } else if (GENERAL_LABELS.contains(label)) {
                    category = "普货";
                } else if (DANGEROUS_LABELS.contains(label)) {
                    category = "危货";
                }
            }
            categoryMap.put(code, category);
        }

        // 4. 聚合统计
        RegionCompanyStatsVo vo = new RegionCompanyStatsVo();
        long total = 0;

        if (dbStats != null) {
            for (Map<String, Object> stat : dbStats) {
                String industryStr = (String) stat.get("industry");
                Object countObj = stat.get("count");
                long count = countObj == null ? 0L : ((Number) countObj).longValue();
                total += count;

                if (industryStr == null || industryStr.isEmpty()) {
                    vo.setOtherCount(vo.getOtherCount() + count);
                    continue;
                }

                // 处理可能存在的多个行业（中英文逗号分隔）
                String[] industries = industryStr.split("[,，]");
                Set<String> categoriesFound = new HashSet<>();

                for (String industry : industries) {
                    if (industry == null || industry.trim().isEmpty()) {
                        continue;
                    }
                    String category = categoryMap.getOrDefault(industry.trim(), "其他");
                    categoriesFound.add(category);
                }

                // 如果没有找到有效分类（例如全是空字符串），归为其他
                if (categoriesFound.isEmpty()) {
                    vo.setOtherCount(vo.getOtherCount() + count);
                } else {
                    for (String category : categoriesFound) {
                        switch (category) {
                            case "普货":
                                vo.setGeneralCargoCount(vo.getGeneralCargoCount() + count);
                                break;
                            case "危货":
                                vo.setDangerousGoodsCount(vo.getDangerousGoodsCount() + count);
                                break;
                            case "客运":
                                vo.setPassengerTransportCount(vo.getPassengerTransportCount() + count);
                                break;
                            default:
                                vo.setOtherCount(vo.getOtherCount() + count);
                        }
                    }
                }
            }
        }
        vo.setTotalCount(total);
        return vo;
    }

    @Override
    public HeadquartersEnterpriseTrendVo getEnterpriseTrendStats() {
        // 1. 获取所有行业字典数据
        List<SysDictDataVo> industryDicts = sysDictTypeService.selectDictDataByType("hot_industry");
        if (industryDicts == null) {
            industryDicts = new ArrayList<>();
        }

        // 构建行业代码到分类的映射
        Map<String, String> categoryMap = new HashMap<>();
        for (SysDictDataVo dict : industryDicts) {
            String label = dict.getDictLabel();
            String code = dict.getDictValue();
            String category = "其他";
            if (label != null) {
                label = label.trim();
                if (PASSENGER_LABELS.contains(label)) {
                    category = "客运";
                } else if (GENERAL_LABELS.contains(label)) {
                    category = "普货";
                } else if (DANGEROUS_LABELS.contains(label)) {
                    category = "危货";
                }
            }
            categoryMap.put(code, category);
        }

        // 2. 获取所有企业的创建年份和行业
        List<Map<String, Object>> companyList = headquartersWorkbenchMapper.selectAllCompanyCreateYears();

        int currentYear = java.time.LocalDate.now().getYear();
        int startYear = currentYear;
        if (companyList != null && !companyList.isEmpty()) {
            Object yearObj = companyList.get(0).get("year");
            if (yearObj != null) {
                startYear = ((Number) yearObj).intValue();
            }
        }

        // 3. 按年份分组
        Map<Integer, List<String>> yearToIndustries = new HashMap<>();
        if (companyList != null) {
            for (Map<String, Object> row : companyList) {
                Object yearObj = row.get("year");
                String industry = (String) row.get("industry");
                if (yearObj != null) {
                    int y = ((Number) yearObj).intValue();
                    yearToIndustries.computeIfAbsent(y, k -> new ArrayList<>()).add(industry);
                }
            }
        }

        // 4. 计算累积趋势
        List<Integer> years = new ArrayList<>();
        List<Long> totalCounts = new ArrayList<>();
        List<Long> generalCounts = new ArrayList<>();
        List<Long> dangerousCounts = new ArrayList<>();
        List<Long> passengerCounts = new ArrayList<>();
        List<Long> otherCounts = new ArrayList<>();

        long currentTotal = 0;
        long currentGeneral = 0;
        long currentDangerous = 0;
        long currentPassenger = 0;
        long currentOther = 0;

        for (int y = startYear; y <= currentYear; y++) {
            List<String> industriesInYear = yearToIndustries.get(y);
            if (industriesInYear != null) {
                for (String industryStr : industriesInYear) {
                    currentTotal++; // 每一个企业ID都是唯一的，所以总数直接+1

                    if (industryStr == null || industryStr.isEmpty()) {
                        currentOther++;
                        continue;
                    }

                    String[] industries = industryStr.split("[,，]");
                    Set<String> categoriesFound = new HashSet<>();
                    for (String ind : industries) {
                        if (ind == null || ind.trim().isEmpty()) continue;
                        String category = categoryMap.getOrDefault(ind.trim(), "其他");
                        categoriesFound.add(category);
                    }

                    if (categoriesFound.isEmpty()) {
                        currentOther++;
                    } else {
                        for (String category : categoriesFound) {
                            switch (category) {
                                case "普货":
                                    currentGeneral++;
                                    break;
                                case "危货":
                                    currentDangerous++;
                                    break;
                                case "客运":
                                    currentPassenger++;
                                    break;
                                default:
                                    currentOther++;
                            }
                        }
                    }
                }
            }

            years.add(y);
            totalCounts.add(currentTotal);
            generalCounts.add(currentGeneral);
            dangerousCounts.add(currentDangerous);
            passengerCounts.add(currentPassenger);
            otherCounts.add(currentOther);
        }

        HeadquartersEnterpriseTrendVo vo = new HeadquartersEnterpriseTrendVo();
        vo.setYears(years);
        vo.setTotalCounts(totalCounts);
        vo.setGeneralCounts(generalCounts);
        vo.setDangerousCounts(dangerousCounts);
        vo.setPassengerCounts(passengerCounts);
        vo.setOtherCounts(otherCounts);
        return vo;
    }

    @Override
    public HeadquartersPersonnelTrendVo getPersonnelTrendStats() {
        // 1. 获取人员类型字典
        List<SysDictDataVo> typeDicts = sysDictTypeService.selectDictDataByType("hot_person_type");
        if (typeDicts == null) {
            typeDicts = new ArrayList<>();
        }
        // 按字典顺序排序（通常数据库查出来已经是按sort_order排序的）
        List<String> categories = typeDicts.stream()
                .map(SysDictDataVo::getDictLabel)
                .collect(Collectors.toList());
        Map<String, String> valueToLabelMap = typeDicts.stream()
                .collect(Collectors.toMap(SysDictDataVo::getDictValue, SysDictDataVo::getDictLabel));

        // 2. 获取所有从业人员入职年份和类型
        List<Map<String, Object>> personnelList = headquartersWorkbenchMapper.selectAllPersonnelCreateYears();

        int currentYear = java.time.LocalDate.now().getYear();
        int startYear = currentYear;
        if (personnelList != null && !personnelList.isEmpty()) {
            Object yearObj = personnelList.get(0).get("year");
            if (yearObj != null) {
                startYear = ((Number) yearObj).intValue();
            }
        }

        // 3. 按年份分组
        Map<Integer, List<String>> yearToTypes = new HashMap<>();
        if (personnelList != null) {
            for (Map<String, Object> row : personnelList) {
                Object yearObj = row.get("year");
                String typeVal = (String) row.get("personType");
                if (yearObj != null && typeVal != null) {
                    int y = ((Number) yearObj).intValue();
                    yearToTypes.computeIfAbsent(y, k -> new ArrayList<>()).add(typeVal);
                }
            }
        }

        // 4. 初始化累积计数器
        Map<String, Long> cumulativeCounts = new HashMap<>();
        for (String label : categories) {
            cumulativeCounts.put(label, 0L);
        }

        // 5. 计算趋势
        List<Integer> years = new ArrayList<>();
        Map<String, List<Long>> seriesData = new HashMap<>();
        for (String label : categories) {
            seriesData.put(label, new ArrayList<>());
        }

        for (int y = startYear; y <= currentYear; y++) {
            List<String> typesInYear = yearToTypes.get(y);
            if (typesInYear != null) {
                for (String typeVal : typesInYear) {
                    String label = valueToLabelMap.get(typeVal);
                    if (label != null && cumulativeCounts.containsKey(label)) {
                        cumulativeCounts.put(label, cumulativeCounts.get(label) + 1);
                    }
                }
            }

            years.add(y);
            for (String label : categories) {
                seriesData.get(label).add(cumulativeCounts.get(label));
            }
        }

        HeadquartersPersonnelTrendVo vo = new HeadquartersPersonnelTrendVo();
        vo.setYears(years);
        vo.setCategories(categories);
        vo.setSeriesData(seriesData);
        return vo;
    }

    @Override
    public HeadquartersVehicleTrendVo getVehicleTrendStats() {
        List<SysDictDataVo> industryDicts = sysDictTypeService.selectDictDataByType("hot_industry");
        if (industryDicts == null) {
            industryDicts = new ArrayList<>();
        }
        Map<String, String> categoryMap = new HashMap<>();
        for (SysDictDataVo dict : industryDicts) {
            String label = dict.getDictLabel();
            String code = dict.getDictValue();
            String category = "其他";
            if (label != null) {
                label = label.trim();
                if (PASSENGER_LABELS.contains(label)) {
                    category = "客运";
                } else if (GENERAL_LABELS.contains(label)) {
                    category = "普货";
                } else if (DANGEROUS_LABELS.contains(label)) {
                    category = "危货";
                }
            }
            categoryMap.put(code, category);
        }

        List<Map<String, Object>> vehicleList = headquartersWorkbenchMapper.selectAllVehicleCreateYears();
        int currentYear = java.time.LocalDate.now().getYear();
        int startYear = currentYear;
        if (vehicleList != null && !vehicleList.isEmpty()) {
            Object yearObj = vehicleList.get(0).get("year");
            if (yearObj != null) {
                startYear = ((Number) yearObj).intValue();
            }
        }

        Map<Integer, List<String>> yearToIndustries = new HashMap<>();
        if (vehicleList != null) {
            for (Map<String, Object> row : vehicleList) {
                Object yearObj = row.get("year");
                String industry = row.get("industry") == null ? null : row.get("industry").toString();
                if (yearObj != null) {
                    int y = ((Number) yearObj).intValue();
                    if (industry != null && !industry.isEmpty()) {
                        String[] codes = industry.split("[,，]");
                        for (String code : codes) {
                            String trimmed = code.trim();
                            if (!trimmed.isEmpty()) {
                                yearToIndustries.computeIfAbsent(y, k -> new ArrayList<>()).add(trimmed);
                            }
                        }
                    } else {
                        yearToIndustries.computeIfAbsent(y, k -> new ArrayList<>()).add("__NONE__");
                    }
                }
            }
        }

        long cumulativeTotal = 0;
        long cumulativeGeneral = 0;
        long cumulativeDangerous = 0;
        long cumulativePassenger = 0;
        long cumulativeOther = 0;

        List<Integer> years = new ArrayList<>();
        List<Long> totalCounts = new ArrayList<>();
        List<Long> generalCounts = new ArrayList<>();
        List<Long> dangerousCounts = new ArrayList<>();
        List<Long> passengerCounts = new ArrayList<>();
        List<Long> otherCounts = new ArrayList<>();

        for (int y = startYear; y <= currentYear; y++) {
            List<String> industriesInYear = yearToIndustries.get(y);
            if (industriesInYear != null) {
                for (String code : industriesInYear) {
                    cumulativeTotal += 1;
                    String category = "其他";
                    if (!"__NONE__".equals(code)) {
                        category = categoryMap.getOrDefault(code, "其他");
                    }
                    switch (category) {
                        case "普货" -> cumulativeGeneral += 1;
                        case "危货" -> cumulativeDangerous += 1;
                        case "客运" -> cumulativePassenger += 1;
                        default -> cumulativeOther += 1;
                    }
                }
            }
            years.add(y);
            totalCounts.add(cumulativeTotal);
            generalCounts.add(cumulativeGeneral);
            dangerousCounts.add(cumulativeDangerous);
            passengerCounts.add(cumulativePassenger);
            otherCounts.add(cumulativeOther);
        }

        HeadquartersVehicleTrendVo vo = new HeadquartersVehicleTrendVo();
        vo.setYears(years);
        vo.setTotalCounts(totalCounts);
        vo.setGeneralCounts(generalCounts);
        vo.setDangerousCounts(dangerousCounts);
        vo.setPassengerCounts(passengerCounts);
        vo.setOtherCounts(otherCounts);
        return vo;
    }

    @Override
    public HeadquartersYearlyComparisonVo getAccidentYearlyComparison() {
        int currentYear = java.time.LocalDate.now().getYear();
        int lastYear = currentYear - 1;

        List<Map<String, Object>> rows = headquartersWorkbenchMapper.selectMonthlyAccidentCounts(lastYear, currentYear);
        return buildYearlyComparisonVo(rows, currentYear, lastYear);
    }

    @Override
    public HeadquartersYearlyComparisonVo getHiddenDangerYearlyComparison() {
        int currentYear = java.time.LocalDate.now().getYear();
        int lastYear = currentYear - 1;

        List<Map<String, Object>> rows = headquartersWorkbenchMapper.selectMonthlyHiddenDangerCounts(lastYear, currentYear);
        return buildYearlyComparisonVo(rows, currentYear, lastYear);
    }

    private HeadquartersYearlyComparisonVo buildYearlyComparisonVo(List<Map<String, Object>> rows, int currentYear, int lastYear) {
        // 初始化数据容器
        Map<Integer, Long> currentYearMap = new HashMap<>();
        Map<Integer, Long> lastYearMap = new HashMap<>();

        if (rows != null) {
            for (Map<String, Object> row : rows) {
                Object yearObj = row.get("year");
                Object monthObj = row.get("month");
                Object countObj = row.get("count");

                if (yearObj != null && monthObj != null) {
                    try {
                        int year = Integer.parseInt(yearObj.toString());
                        int month = Integer.parseInt(monthObj.toString());
                        long count = 0L;
                        if (countObj != null) {
                            if (countObj instanceof Number) {
                                count = ((Number) countObj).longValue();
                            } else {
                                count = Long.parseLong(countObj.toString());
                            }
                        }

                        if (year == currentYear) {
                            currentYearMap.put(month, count);
                        } else if (year == lastYear) {
                            lastYearMap.put(month, count);
                        }
                    } catch (Exception ignored) {
                    }
                }
            }
        }

        List<String> months = new ArrayList<>();
        List<Long> currentValues = new ArrayList<>();
        List<Long> lastValues = new ArrayList<>();

        for (int i = 1; i <= 12; i++) {
            months.add(i + "月");
            currentValues.add(currentYearMap.getOrDefault(i, 0L));
            lastValues.add(lastYearMap.getOrDefault(i, 0L));
        }

        HeadquartersYearlyComparisonVo vo = new HeadquartersYearlyComparisonVo();
        vo.setMonths(months);
        vo.setCurrentYearValues(currentValues);
        vo.setLastYearValues(lastValues);
        return vo;
    }

    @Override
    public HeadquartersCompanyListVo getCompanyList() {
        List<HeadquartersCompanyListVo.CompanyRow> rows = headquartersWorkbenchMapper.selectCompanyListWithManagerCount();
        HeadquartersCompanyListVo vo = new HeadquartersCompanyListVo();
        if (rows != null) {
            vo.setTotalCount((long) rows.size());
            vo.setList(rows);
        } else {
            vo.setTotalCount(0L);
            vo.setList(new ArrayList<>());
        }
        return vo;
    }

    @Override
    public Long getSquareInfoPendingAuditCount() {
        return hotSquareInfoMapper.selectCount(
                Wrappers.<HotSquareInfo>lambdaQuery()
                        .eq(HotSquareInfo::getIsDeleted, 0L)
                        .eq(HotSquareInfo::getAuditStatus, 0L)
        );
    }

    @Override
    public Long getComplaintAdvicePendingReplyCount() {
        return hotComplaintAdviceMapper.selectCount(
                Wrappers.<HotComplaintAdvice>lambdaQuery()
                        .eq(HotComplaintAdvice::getIsDeleted, 0L)
                        .eq(HotComplaintAdvice::getIsReplied, 0L)
        );
    }
}
