package com.ruoyi.oa.service.impl;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.oa.domain.vo.*;
import com.ruoyi.oa.mapper.SalaryDashboardMapper;
import com.ruoyi.oa.service.ISalaryDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Service
public class SalaryDashboardServiceImpl implements ISalaryDashboardService {

    @Autowired
    private SalaryDashboardMapper dashboardMapper;

    @Override
    public SalaryDashboardVo getDashboardData(Long payYear, Long payMonth) {
        SalaryDashboardVo dashboardVo = new SalaryDashboardVo();

        // 1. 获取卡片数据
        dashboardVo.setCardData(getCardData(payYear, payMonth));

        // 2. 获取图表数据
        dashboardVo.setChartData(getChartData(payYear, payMonth));

        // 3. 获取部门统计表格数据
        List<DepartmentStatVo> deptStats = dashboardMapper.queryDepartmentStats(payYear, payMonth);
        TableDataInfo<DepartmentStatVo> tableData = new TableDataInfo<>(deptStats, deptStats.size());
        dashboardVo.setDepartmentStats(tableData);
        return dashboardVo;
    }

    private CardDataVo getCardData(Long payYear, Long payMonth) {
        CardDataVo cardData = new CardDataVo();

        // 初始化所有数值为0，避免NPE
        cardData.setTotalSalaryExpenditure(BigDecimal.ZERO);
        cardData.setLastMonthTotalSalaryExpenditureRate(BigDecimal.ZERO);
        cardData.setAvgDepartmentExpenditure(BigDecimal.ZERO);
        cardData.setLastMonthAvgDepartmentExpenditureRate(BigDecimal.ZERO);
        cardData.setAvgPersonSalary(BigDecimal.ZERO);
        cardData.setLastMonthAvgPersonSalaryRate(BigDecimal.ZERO);
        cardData.setYearOnYearGrowthRate(BigDecimal.ZERO);

        // 获取当月数据
        CardMetricsVo currentMonthMetrics = dashboardMapper.queryCardMetrics(payYear, payMonth);
        if (currentMonthMetrics == null) {
            return cardData; // 如果当月没有数据，直接返回零值
        }

        // 设置当月总支出
        cardData.setTotalSalaryExpenditure(
                currentMonthMetrics.getTotalSalaryExpenditure() != null ?
                        currentMonthMetrics.getTotalSalaryExpenditure() : BigDecimal.ZERO
        );

        // 获取上月数据 (处理1月的情况)
        Long lastMonth = payMonth == 1 ? 12 : payMonth - 1;
        Long lastYear = payMonth == 1 ? payYear - 1 : payYear;
        CardMetricsVo lastMonthMetrics = dashboardMapper.queryCardMetrics(lastYear, lastMonth);

        // 计算较上月增长率
        if (lastMonthMetrics != null &&
                lastMonthMetrics.getTotalSalaryExpenditure() != null &&
                lastMonthMetrics.getTotalSalaryExpenditure().compareTo(BigDecimal.ZERO) != 0) {
            try {
                BigDecimal monthGrowth = currentMonthMetrics.getTotalSalaryExpenditure()
                        .subtract(lastMonthMetrics.getTotalSalaryExpenditure())
                        .divide(lastMonthMetrics.getTotalSalaryExpenditure(), 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"));
                cardData.setLastMonthTotalSalaryExpenditureRate(monthGrowth);
            } catch (Exception e) {
                cardData.setLastMonthTotalSalaryExpenditureRate(BigDecimal.ZERO);
            }
        }

        // 计算部门平均支出
        if (currentMonthMetrics.getDepartmentCount() != null &&
                currentMonthMetrics.getDepartmentCount() > 0 &&
                currentMonthMetrics.getTotalCompanyExpenditure() != null) {
            try {
                BigDecimal avgDeptExpenditure = currentMonthMetrics.getTotalCompanyExpenditure()
                        .divide(new BigDecimal(currentMonthMetrics.getDepartmentCount()), 2, RoundingMode.HALF_UP);
                cardData.setAvgDepartmentExpenditure(avgDeptExpenditure);
            } catch (Exception e) {
                cardData.setAvgDepartmentExpenditure(BigDecimal.ZERO);
            }
        }

        // 计算人均实发工资
        if (currentMonthMetrics.getEmployeeCount() != null &&
                currentMonthMetrics.getEmployeeCount() > 0 &&
                currentMonthMetrics.getTotalSalaryExpenditure() != null) {
            try {
                BigDecimal avgPersonSalary = currentMonthMetrics.getTotalSalaryExpenditure()
                        .divide(new BigDecimal(currentMonthMetrics.getEmployeeCount()), 2, RoundingMode.HALF_UP);
                cardData.setAvgPersonSalary(avgPersonSalary);
            } catch (Exception e) {
                cardData.setAvgPersonSalary(BigDecimal.ZERO);
            }
        }

        // 获取去年同期数据并计算同比增长率
        CardMetricsVo lastYearMetrics = dashboardMapper.queryCardMetrics(payYear - 1, payMonth);
        if (lastYearMetrics != null &&
                lastYearMetrics.getEmployeeCount() != null &&
                lastYearMetrics.getEmployeeCount() > 0 &&
                lastYearMetrics.getTotalSalaryExpenditure() != null) {
            try {
                BigDecimal lastYearAvgSalary = lastYearMetrics.getTotalSalaryExpenditure()
                        .divide(new BigDecimal(lastYearMetrics.getEmployeeCount()), 2, RoundingMode.HALF_UP);
                if (lastYearAvgSalary.compareTo(BigDecimal.ZERO) != 0 &&
                        cardData.getAvgPersonSalary() != null) {
                    BigDecimal yearGrowth = cardData.getAvgPersonSalary()
                            .subtract(lastYearAvgSalary)
                            .divide(lastYearAvgSalary, 4, RoundingMode.HALF_UP)
                            .multiply(new BigDecimal("100"));
                    cardData.setYearOnYearGrowthRate(yearGrowth);
                }
            } catch (Exception e) {
                cardData.setYearOnYearGrowthRate(BigDecimal.ZERO);
            }
        }

        return cardData;
    }

    private ChartDataVo getChartData(Long payYear, Long payMonth) {
        ChartDataVo chartData = new ChartDataVo();

        // 1. 获取柱状图数据 (年度每月总支出)
        List<MonthlyExpenditureVo> monthlyExpenditures =
                dashboardMapper.queryMonthlyExpenditures(payYear);
        chartData.setMonthlyExpenditures(monthlyExpenditures != null ?
                monthlyExpenditures : new ArrayList<>());

        // 2. 获取饼图数据 (薪资构成)
        List<SalaryComponentVo> salaryComponents =
                dashboardMapper.querySalaryComponents(payYear, payMonth);
        chartData.setSalaryComponents(salaryComponents != null ?
                salaryComponents : new ArrayList<>());

        // 3. 获取折线图数据 (总支出 vs 平均工资)
        List<LineChartPointVo> lineChartData =
                dashboardMapper.queryLineChartData(payYear);
        chartData.setLineChartData(new LineChartVo(
                lineChartData != null ? lineChartData : new ArrayList<>()
        ));

        return chartData;
    }
}