<template>
  <div class="error-analysis">
    <!-- 时间筛选器 -->
    <view class="time-filter-section">
      <view class="filter-row">
        <StaticsTab v-model="activeTimeRange" :tabs="timeRangeOptions" active-color="#2B7BFF"
          @change="handleTimeRangeChange" />
        <view v-if="activeTimeRange === 'custom'" class="custom-time-section">
          <uni-datetime-picker v-model="dateRange" type="daterange" rangeSeparator="至" @change="handleDateRangeChange"
            class="date-range-picker" :clear-icon="false" />
          <text class="days-count">共 {{ totalDays }} 天</text>
        </view>
      </view>
    </view>

    <!-- 总体问题分布 - 所有角色都能看到 -->
    <div class="section" v-if="!!pieData">
      <h3 class="section-title">总体问题分布</h3>
      <div class="chart-container">
        <div ref="pieChart" class="chart" style="width: 100%; height: 400rpx;"></div>
      </div>
    </div>

    <!-- 站长角色：显示所有图表 -->

    <!-- 问题分布对比 -->
    <div class="section" v-if="!!radarData">
      <h3 class="section-title">问题分布对比</h3>
      <div class="chart-container">
        <div ref="radarChart" class="chart" style="width: 100%; height: 400rpx;"></div>
      </div>
    </div>


    <!-- 站长角色：根据数组遍历展示 -->
    <template v-if="userRole === 'test'">
      <div v-for="(category, index) in stationMasterCharts" :key="index" class="section">
        <!-- 问题对比 -->
        <div class="chart-section" v-if="category.tableData && category.tableData.length > 0">
          <h3 class="section-title">{{ category.name }}-问题对比</h3>
          <div class="table-container">
            <statistic-table :data="category.tableData" :columns="category.tableColumns"></statistic-table>
          </div>
        </div>

        <!-- 问题趋势 -->
        <div class="chart-section"
          v-if="category.trendData && category.trendData.xAxis && category.trendData.xAxis.length > 0">
          <h3 class="section-title" style="margin-top: 20rpx;">{{ category.name }}-问题趋势</h3>
          <div class="chart-container">
            <div class="chart" :ref="`chart_${index}`" style="width: 100%; height: 400rpx;"></div>
          </div>
        </div>
      </div>
    </template>

    <!-- 科长角色：根据数组遍历展示 -->
    <template v-else-if="userRole === 'kezhang'">
      <div v-for="(category, index) in sectionChiefCharts" :key="index" class="section">
        <!-- 问题明细 -->
        <div class="chart-section" v-if="category.pieData && category.pieData.length > 0">
          <h3 class="section-title">{{ category.name }}-问题明细</h3>
          <div class="chart-container">
            <div class="chart" :ref="`sectionChiefRoundChart_${index}`" style="width: 100%; height: 400rpx;"></div>
          </div>
        </div>

        <!-- 问题趋势 -->
        <div class="chart-section"
          v-if="category.trendData && category.trendData.xAxis && category.trendData.xAxis.length > 0">
          <h3 class="section-title" style="margin-top: 20rpx;">{{ category.name }}-问题趋势</h3>
          <div class="chart-container">
            <div class="chart" :ref="`sectionChiefLineChart_${index}`" style="width: 100%; height: 400rpx;"></div>
          </div>
        </div>
      </div>
    </template>

    <!-- 班组长角色：只显示总体问题分布 -->

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <text>加载中...</text>
    </div>

    <!-- 无数据提示 -->
    <div v-if="!loading && pieData.length === 0" class="no-data">
      <text>暂无分析数据</text>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import StatisticTable from "@/components/statistic-table/statistic-table.vue";
import StaticsTab from "@/pages/inspectionStatistics/components/StaticsTab.vue";
import { mapState, mapGetters } from 'vuex'
import {
  getWrongAnalysisOverview,
  getWrongAnalysisRadar,
  getWrongAnalysisCategoryDetail
} from '@/api/questionStatistics/questionStatistics';
import { calculateTimeRange } from '@/utils/formatUtils.js';

export default {
  name: 'ErrorAnalysis',
  components: {
    StatisticTable,
    StaticsTab
  },
  data() {
    return {
      loading: false,
      activeTimeRange: 'month', // year, month, custom
      customStartTime: '',
      customEndTime: '',
      dateRange: [],
      totalDays: 0,
      pieChart: null,
      radarChart: null,
      trendChart: null,
      teamPieChart: null,
      teamTrendChart: null,
      pieData: [],
      radarData: [],
      radarIndicator: [],
      trendData: [],
      comparisonData: [],
      // 站长角色数据数组
      stationMasterCharts: [],
      // 科长角色数据数组
      sectionChiefCharts: [],
      // 班组管理相关数据
      teamPieData: [],
      teamTrendData: [],
      timeRangeOptions: [
        { title: '本年', type: 'year' },
        { title: '本月', type: 'month' },
        { title: '自定义', type: 'custom' }
      ],
      tableColumns: [
        { props: 'category', title: '分类' },
        { props: 'depart1', title: '旅检一科' },
        { props: 'depart2', title: '旅检二科' },
        { props: 'depart3', title: '旅检三科' }
      ]
    };
  },
  computed: {
    ...mapState({
      userRoles: state => state.user.roles
    }),
    // 根据用户角色判断当前用户类型
    userRole() {
      console.log('用户角色：', this.userRoles);

      // 根据实际的角色名称进行映射
      if (this.userRoles.includes('test') || this.userRoles.includes('stationMaster')) {
        return 'test' // 站长
      } else if (this.userRoles.includes('kezhang') || this.userRoles.includes('sectionChief')) {
        return 'kezhang' // 科长
      } else if (this.userRoles.includes('banzuzhang') || this.userRoles.includes('teamLeader')) {
        return 'banzuzhang' // 班组长
      }

      // 默认返回站长角色
      return 'test'
    }
  },
  mounted() {
    this.setDefaultDates();
    this.initCharts();
    this.loadData();
  },
  beforeDestroy() {
    // 清理固定图表
    [this.pieChart, this.radarChart, this.teamPieChart, this.teamTrendChart].forEach(chart => {
      if (chart) chart.dispose();
    });

    // 清理站长角色动态图表
    if (this.stationMasterChartInstances) {
      this.stationMasterChartInstances.forEach(chart => {
        if (chart) chart.dispose();
      });
    }

    // 清理科长角色动态图表
    if (this.sectionChiefChartInstances) {
      this.sectionChiefChartInstances.forEach(chart => {
        if (chart) chart.dispose();
      });
    }
  },
  methods: {
    // 设置默认日期
    setDefaultDates() {
      const today = new Date();
      // 本月第一天
      const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

      // 使用本地时间格式化，避免UTC时间转换问题
      this.customStartTime = this.formatLocalDate(firstDayOfMonth);
      this.customEndTime = this.formatLocalDate(today);
      // 初始化dateRange
      this.dateRange = [this.customStartTime, this.customEndTime];
      this.calculateDays();
    },

    // 格式化本地日期为YYYY-MM-DD格式
    formatLocalDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    initCharts() {
      // 初始化固定图表
      const pieDom = this.$refs.pieChart;
      if (pieDom) {
        this.pieChart = echarts.init(pieDom);
      }

      const radarDom = this.$refs.radarChart;
      if (radarDom) {
        this.radarChart = echarts.init(radarDom);
      }

      const teamPieDom = this.$refs.teamPieChart;
      if (teamPieDom) {
        this.teamPieChart = echarts.init(teamPieDom);
      }

      const teamTrendDom = this.$refs.teamTrendChart;
      if (teamTrendDom) {
        this.teamTrendChart = echarts.init(teamTrendDom);
      }

      // 动态初始化站长角色图表
      this.initStationMasterCharts();

      // 动态初始化科长角色图表
      this.initSectionChiefCharts();

      this.setChartsOption();
    },

    initStationMasterCharts() {
      console.log('初始化站长角色图表，分类数量:', this.stationMasterCharts ? this.stationMasterCharts.length : 0);

      // 清理之前的站长角色图表
      if (this.stationMasterChartInstances) {
        this.stationMasterChartInstances.forEach(chart => {
          if (chart) chart.dispose();
        });
      }

      this.stationMasterChartInstances = [];

      // 初始化站长角色图表
      if (this.stationMasterCharts && this.stationMasterCharts.length > 0) {
        this.stationMasterCharts.forEach((category, index) => {
          // 只初始化有趋势数据的图表
          if (category.trendData && category.trendData.xAxis && category.trendData.xAxis.length > 0) {
            console.log('初始化趋势图表:', index, category.name);
            const chartDom = this.$refs[`chart_${index}`];
            console.log('图表DOM元素:', chartDom);

            if (chartDom && chartDom.length > 0) {
              const chartInstance = echarts.init(chartDom[0]);
              this.stationMasterChartInstances[index] = chartInstance;
              console.log('趋势图表实例创建成功:', index);
            } else {
              console.warn('趋势图表DOM元素未找到:', `chart_${index}`);
            }
          }
        });
      }
    },

    initSectionChiefCharts() {
      console.log('初始化科长角色图表，分类数量:', this.sectionChiefCharts ? this.sectionChiefCharts.length : 0);

      // 清理之前的科长角色图表
      if (this.sectionChiefChartInstances) {
        this.sectionChiefChartInstances.forEach(chart => {
          if (chart) chart.dispose();
        });
      }

      this.sectionChiefChartInstances = [];

      // 初始化科长角色图表
      if (this.sectionChiefCharts && this.sectionChiefCharts.length > 0) {
        this.sectionChiefCharts.forEach((category, index) => {
          // 初始化环形图
          if (category.pieData && category.pieData.length > 0) {
            console.log('初始化环形图:', index, category.name);
            const pieChartDom = this.$refs[`sectionChiefRoundChart_${index}`];
            console.log('环形图DOM元素:', pieChartDom);

            if (pieChartDom && pieChartDom.length > 0) {
              const pieChartInstance = echarts.init(pieChartDom[0]);
              this.sectionChiefChartInstances[`pie_${index}`] = pieChartInstance;
              console.log('环形图实例创建成功:', index);
            } else {
              console.warn('环形图DOM元素未找到:', `sectionChiefRoundChart_${index}`);
            }
          }

          // 初始化趋势图
          if (category.trendData && category.trendData.xAxis && category.trendData.xAxis.length > 0) {
            console.log('初始化趋势图:', index, category.name);
            const trendChartDom = this.$refs[`sectionChiefLineChart_${index}`];
            console.log('趋势图DOM元素:', trendChartDom);

            if (trendChartDom && trendChartDom.length > 0) {
              const trendChartInstance = echarts.init(trendChartDom[0]);
              this.sectionChiefChartInstances[`trend_${index}`] = trendChartInstance;
              console.log('趋势图实例创建成功:', index);
            } else {
              console.warn('趋势图DOM元素未找到:', `sectionChiefLineChart_${index}`);
            }
          }
        });
      }
    },
    setPieOption() {
      console.log('设置饼图选项', this.pieData);
      if (this.pieChart) {
        this.pieChart.setOption({

          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            show: false
          },
          series: [
            {
              name: '问题分布',
              type: 'pie',
              radius: '60%',
              center: ['50%', '50%'],
              data: this.pieData,
              label: {
                show: true,
                formatter: '{b}\n{c} ({d}%)',
                fontSize: 12,
                fontWeight: 'normal'
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 20
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      }
    },
    setRadarOption() {

      if (this.radarChart && this.radarData && this.radarData.length > 0) {
        console.log('设置雷达图选项', this.calculateRadarMaxValue());
        this.radarChart.setOption({
          // title: {
          //   text: '',
          //   left: 'center',
          //   textStyle: {
          //     fontSize: 14,
          //     fontWeight: 'normal'
          //   }
          // },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            show: true,
          },
          radar: {
            shape: 'polygon',
            radius: '60%',
            center: ['50%', '55%'],
            indicator: this.radarIndicators.map(indicator => ({
              name: indicator,
              max: this.calculateRadarMaxValue()
            }))
          },
          series: [
            {
              type: 'radar',
              data: this.radarData.map(item => ({
                value: item.data,
                name: item.name,
              })),
              areaStyle: {

              },
              symbol: 'none',
            }
          ]
        });
      }
    },



    // 设置站长角色动态图表选项
    setStationMasterChartOptions() {
      if (this.stationMasterChartInstances && this.stationMasterChartInstances.length > 0) {
        this.stationMasterCharts.forEach((category, index) => {
          if (category.trendData && category.trendData.xAxis && category.trendData.xAxis.length > 0 && this.stationMasterChartInstances[index]) {
            const chartInstance = this.stationMasterChartInstances[index];
            const chartData = category.trendData;

            if (chartData.xAxis && chartData.xAxis.length > 0 && chartData.series && chartData.series.length > 0) {
              chartInstance.setOption({
                tooltip: {
                  trigger: 'axis',
                  formatter: function (params) {
                    let result = params[0].axisValue + '<br/>';
                    params.forEach(param => {
                      result += `${param.seriesName}: ${param.value}<br/>`;
                    });
                    return result;
                  }
                },
                legend: {
                  data: chartData.series.map(s => s.name),
                  bottom: 10
                },
                grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '15%',
                  containLabel: true
                },
                xAxis: {
                  type: 'category',
                  boundaryGap: false,
                  data: chartData.xAxis
                },
                yAxis: {
                  type: 'value'
                },
                series: chartData.series.map(series => ({
                  name: series.name,
                  type: 'line',
                  data: series.data,
                  smooth: true,
                  lineStyle: {
                    width: 3
                  },
                  areaStyle: {
                    opacity: 0.3
                  }
                }))
              });
            }
          }
        });
      }
    },

    // 设置科长角色动态图表选项
    setSectionChiefChartOptions() {
      if (this.sectionChiefChartInstances && Object.keys(this.sectionChiefChartInstances).length > 0) {
        this.sectionChiefCharts.forEach((category, index) => {
          // 设置环形图选项
          const pieChartInstance = this.sectionChiefChartInstances[`pie_${index}`];

          if (pieChartInstance && category.pieData && category.pieData.length > 0) {
            pieChartInstance.setOption({
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              legend: {
                show: false
              },
              label: {
                show: true,
                formatter: '{b}\n{c} ({d}%)',
                fontSize: 12,
                fontWeight: 'normal'
              },
              series: [
                {
                  name: `${category.name}-问题明细`,
                  type: 'pie',
                  radius: ['40%', '70%'],
                  center: ['50%', '50%'],
                  data: category.pieData.filter(item => item.value > 0),
                  emphasis: {
                    itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  }
                }
              ]
            });
          }

          // 设置趋势图选项
          const trendChartInstance = this.sectionChiefChartInstances[`trend_${index}`];
          if (trendChartInstance && category.trendData && category.trendData.xAxis && category.trendData.xAxis.length > 0 && category.trendData.series && category.trendData.series.length > 0) {
            trendChartInstance.setOption({
              tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                  let result = params[0].axisValue + '<br/>';
                  params.forEach(param => {
                    result += `${param.seriesName}: ${param.value}<br/>`;
                  });
                  return result;
                }
              },
              legend: {
                data: category.trendData.series.map(s => s.name),
                bottom: 10
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
              },
              xAxis: {
                type: 'category',
                boundaryGap: false,
                data: category.trendData.xAxis
              },
              yAxis: {
                type: 'value'
              },
              series: category.trendData.series.map(series => ({
                name: series.name,
                type: 'line',
                data: series.data,
                lineStyle: {
                  width: 3
                },
                areaStyle: {
                  opacity: 0.3
                }
              }))
            });
          }
        });
      }
    },

    setChartsOption() {
      this.setPieOption();
      this.setRadarOption();

      this.setStationMasterChartOptions();

      // 设置科长角色动态图表选项
      this.setSectionChiefChartOptions();

    },
    handleTimeRangeChange(range) {
      console.log('时间范围选择:', range, this.dateRange);

      // 使用calculateTimeRange计算时间范围
      const timeRangeResult = calculateTimeRange(range, this.dateRange);
      this.customStartTime = timeRangeResult.startDate;
      this.customEndTime = timeRangeResult.endDate;
      this.dateRange = [this.customStartTime, this.customEndTime];

      this.activeTimeRange = range;
      this.calculateDays();
      this.loadData();
    },
    handleDateRangeChange(e) {
      if (e && e.length === 2) {
        this.dateRange = e;
        this.customStartTime = e[0];
        this.customEndTime = e[1];
        this.calculateDays();
        this.loadData();
      }
    },

    // 计算天数
    calculateDays() {
      if (this.customStartTime && this.customEndTime) {
        const start = new Date(this.customStartTime);
        const end = new Date(this.customEndTime);
        const diffTime = Math.abs(end - start);
        this.totalDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
      }
    },

    async loadData() {
      this.loading = true;

      try {
        // 构建请求参数
        const params = {
          timeType: this.activeTimeRange
        };

        // 如果是自定义时间范围，添加开始和结束日期
        if (this.activeTimeRange === 'custom') {
          if (!this.customStartTime || !this.customEndTime) {
            uni.showToast({
              title: '请选择完整的时间范围',
              icon: 'none'
            });
            this.loading = false;
            return;
          }
          params.startDate = this.customStartTime;
          params.endDate = this.customEndTime;
        }

        // 并行调用总体问题分布和雷达图API
        const [overviewResponse, radarResponse] = await Promise.all([
          // 总体问题分布（饼图）
          getWrongAnalysisOverview(params),
          // 问题分布对比（雷达图）
          getWrongAnalysisRadar(params)
        ]);

        // 处理总体问题分布数据（饼图）
        if (overviewResponse.show !== false) {
          this.pieData = this.processOverviewData(overviewResponse);
        } else {
          this.pieData = [];
        }

        // 处理问题分布对比数据（雷达图）
        if (radarResponse.show !== false) {
          const { indicators, series } = this.processRadarData(radarResponse);

          this.radarData = series;
          this.radarIndicators = indicators;
        } else {
          this.radarData = [];
          this.radarIndicators = [];
        }

        // 批量请求大类详情接口（站长角色）
        if (this.userRole === 'test' && this.pieData.length > 0) {
          // 获取所有分类ID
          const categoryIds = this.pieData.map(category => category.id);

          // 批量请求每个分类的详情
          const categoryDetailPromises = categoryIds.map(categoryId =>
            getWrongAnalysisCategoryDetail({ ...params, categoryId })
          );

          const categoryDetailResponses = await Promise.all(categoryDetailPromises);

          // 处理批量返回的数据
          this.stationMasterCharts = this.processBatchCategoryData(categoryDetailResponses, this.pieData);
          console.log(this.stationMasterCharts, 1111);
        } else {
          this.stationMasterCharts = [];
        }
        if (this.userRole === 'kezhang' && this.pieData.length > 0) {
          // 获取所有分类ID
          const categoryIds = this.pieData.map(category => category.id);

          // 批量请求每个分类的详情
          const categoryDetailPromises = categoryIds.map(categoryId =>
            getWrongAnalysisCategoryDetail({ ...params, categoryId })
          );

          const categoryDetailResponses = await Promise.all(categoryDetailPromises);

          // 处理批量返回的数据
          this.sectionChiefCharts = this.processSectionChiefCategoryData(categoryDetailResponses, this.pieData);
          console.log('科长角色图表数据:', this.sectionChiefCharts);
        } else {
          this.sectionChiefCharts = [];
        }




        this.setChartsOption();

        // 数据加载完成后，重新初始化动态图表
        this.$nextTick(() => {
          this.initStationMasterCharts();
          this.setChartsOption();
        });
      } catch (error) {
        console.error('加载数据失败:', error);
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 处理总体问题分布数据（饼图）
    processOverviewData(apiData) {
      const { categories } = apiData.model;

      if (!categories.length) return [];

      return categories.map(category => ({
        id: category.id,
        value: category.count,
        name: category.name
      }));
    },

    // 处理雷达图数据
    processRadarData(apiData) {
      const { indicators, series } = apiData.model;

      if (!apiData || !indicators || !series) return [];

      return { indicators, series }
    },

    // 计算雷达图数据的最大值
    calculateRadarMaxValue() {
      if (!this.radarData || this.radarData.length === 0) return 100;

      let maxValue = 0;

      // 遍历所有雷达图数据系列，找出最大值
      this.radarData.forEach(series => {
        if (series.data && Array.isArray(series.data)) {
          const seriesMax = Math.max(...series.data);
          if (seriesMax > maxValue) {
            maxValue = seriesMax;
          }
        }
      });


      return maxValue
    },

    // 处理大类详情数据
    processCategoryData(apiData) {
      if (!apiData) return { tableData: [], trendData: [] };

      // 处理表格数据
      let tableData = [];
      if (apiData.table) {
        tableData = apiData.table.rows.map(row => {
          const rowData = { category: row.subCategory };
          apiData.table.depts.forEach((dept, index) => {
            rowData[`department${index + 1}`] = row.counts[index] || 0;
          });
          return rowData;
        });
      }

      // 处理趋势数据
      let trendData = [];
      if (apiData.trend) {
        // 简化处理：只显示第一个系列的趋势数据
        const firstSeries = apiData.trend.series[0];
        if (firstSeries) {
          trendData = apiData.trend.xAxis.map((date, index) => ({
            date: date,
            value: firstSeries.data[index] || 0
          }));
        }
      }

      return { tableData, trendData };
    },



    // 处理批量大类详情数据（站长角色）
    processBatchCategoryData(categoryDetailResponses, pieData) {
      if (!categoryDetailResponses || categoryDetailResponses.length === 0) return [];

      const categories = [];

      // 为每个分类创建包含表格和趋势数据的对象
      categoryDetailResponses.forEach((response, index) => {
        if (response.show !== false && pieData[index]) {
          const categoryName = pieData[index].name;
          const { table, trend } = response.model;

          console.log('API响应数据 - table:', table);
          console.log('API响应数据 - trend:', trend);

          const { depts, rows } = table || {};
          const { xAxis, series } = trend || {};

          // 处理表格数据
          const tableData = rows ? rows.filter((item) => {
            // 筛选出counts里面不全等于0的数据（排除所有count都为0的数据）
            return !item.counts.every(element => element === 0);
          }).map(row => {
            // 确保row.counts存在且是数组
            const counts = Array.isArray(row.counts) ? row.counts : [];
            const departs = counts.map((item, i) => ({
              [`depart${i + 1}`]: item
            }));

            // 将数组中的对象合并成一个对象
            const departObj = Object.assign({}, ...departs);

            return {
              category: row.subCategory || '未知分类',
              ...departObj
            };
          }) : [];
          console.log('处理后的表格数据:', tableData);
          // 处理趋势数据
          const trendData = {
            xAxis: xAxis || [],
            series: series || []
          };

          // 创建分类对象，包含表格数据和趋势数据
          const category = {
            name: categoryName,
            tableData: [],
            trendData: {},
            tableColumns: [
              { props: 'category', title: '分类' },
              { props: 'depart1', title: '旅检一科' },
              { props: 'depart2', title: '旅检二科' },
              { props: 'depart3', title: '旅检三科' }
            ]
          };

          // 添加表格数据
          if (tableData && Array.isArray(tableData) && tableData.length > 0) {
            category.tableData = tableData;
          } else {
            console.warn('表格数据为空或格式不正确:', tableData);
          }

          // 添加趋势数据
          if (trendData.xAxis.length > 0 && trendData.series.length > 0) {
            category.trendData = trendData;
          }

          categories.push(category);
        }
      });
      console.log(categories, "categories")
      return categories;
    },

    // 处理科长角色大类详情数据
    processSectionChiefCategoryData(categoryDetailResponses, pieData) {
      if (!categoryDetailResponses || categoryDetailResponses.length === 0) return [];

      const categories = [];

      // 为每个分类创建包含环形图和趋势数据的对象
      categoryDetailResponses.forEach((response, index) => {
        if (response.show !== false && pieData[index]) {

          const { donut, trend, categoryName } = response.model;

          console.log('科长角色API响应数据 - donut:', donut);
          console.log('科长角色API响应数据 - trend:', trend);

          // 处理环形图数据
          const pieData = donut ? donut.map(item => ({
            value: item.count,
            name: item.name
          })) : [];

          // 处理趋势数据
          const trendData = {
            xAxis: trend?.xAxis || [],
            series: trend?.series || []
          };

          // 创建分类对象，包含环形图数据和趋势数据
          const category = {
            name: categoryName,
            pieData: [],
            trendData: {}
          };

          // 添加环形图数据
          if (pieData.length > 0) {
            category.pieData = pieData;
          }

          // 添加趋势数据
          if (trendData.xAxis.length > 0 && trendData.series.length > 0) {
            category.trendData = trendData;
          }

          categories.push(category);
        }
      });
      console.log(categories, "categories")
      return categories;
    }
  },
  watch: {
    pieData: {
      handler() {
        this.$nextTick(() => {
          this.setPieOption();
        });
      },
      deep: true
    },
    stationMasterCharts: {
      handler() {
        this.$nextTick(() => {
          // 当站长角色图表数据变化时，重新初始化图表
          this.initStationMasterCharts();
          this.setStationMasterChartOptions();
        });
      },
      deep: true
    },
    sectionChiefCharts: {
      handler() {
        this.$nextTick(() => {
          // 当科长角色图表数据变化时，重新初始化图表
          this.initSectionChiefCharts();
          this.setSectionChiefChartOptions();
        });
      },
      deep: true
    },
    radarData: {
      handler() {
        this.$nextTick(() => {
          this.setRadarOption();
        });
      },
      deep: true
    },
    trendData: {
      handler() {
        this.$nextTick(() => {
          this.setChartsOption();
        });
      },
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.error-analysis {
  padding: 10rpx 0;

  .time-filter-section {
    margin-bottom: 20rpx;
    padding: 0 20rpx;

    .filter-row {
      display: flex;
      align-items: center;
      flex-direction: row;

      .custom-time-section {
        position: relative;
        display: flex;
        align-items: center;
        gap: 24rpx;
        margin-top: 2rpx;
        width: 350rpx;

        .date-range-picker {
          ::v-deep .icon-calendar {
            display: none !important;
          }

          ::v-deep .uni-date-range {
            font-size: 16rpx !important;
            background: transparent !important;
            color: black !important;
          }

          ::v-deep .uni-date-x {
            height: 25rpx !important;
            line-height: 25rpx !important;

            .range-separator {
              font-size: 20rpx !important;
              padding: 0 !important;
            }

            .uni-date__x-input {
              height: 25rpx !important;
              line-height: 25rpx !important;
            }
          }

          ::v-deep .uni-date-x--border {
            border: none !important;
          }
        }

        .days-count {
          position: absolute;
          right: -86rpx;
          top: -8rpx;
          font-size: 25rpx;
          color: black;
          font-weight: 500;
          white-space: nowrap;
        }
      }
    }
  }

  .section {
    margin-bottom: 24rpx;
    background: #fff;
    border-radius: 12rpx;
    padding: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 24rpx;


    }

    .chart-container {}


  }

  .loading-container,
  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200rpx;
    font-size: 28rpx;
    color: #999;
  }
}
</style>