<template>
  <div class="qa-analysis">
    <!-- 抽问抽答标题 -->
    <div class="section-title">
      <h2>抽问抽答</h2>
    </div>

    <!-- 三个横向均分的内容区域 -->
    <div class="three-panel-layout">
      <!-- 第一个：答题完成趋势 -->
      <div class="panel-item">
        <div class="panel-header">
          <h3>答题完成趋势</h3>
        </div>

        <!-- 描述卡片 -->
        <div class="describe-card">
          <div class="describe-content">
            {{ completionTrendDescription }}
          </div>
        </div>

        <!-- 折线图 -->
        <div class="chart-container">
          <div ref="completionTrendChartRef" class="echarts-chart"></div>
        </div>
      </div>

      <!-- 第二个：错题分布 -->
      <div class="panel-item">
        <div class="panel-header">
          <h3>错题分布</h3>
        </div>

        <!-- 描述卡片 -->
        <div class="describe-card">
          <div class="describe-content">
            {{ errorDistributionDescription }}
          </div>
        </div>

        <!-- 饼图 -->
        <div class="chart-container">
          <div ref="errorDistributionChartRef" class="echarts-chart"></div>
        </div>
      </div>

      <!-- 第三个：各科错题分布对比 -->
      <div class="panel-item" v-show="isStationType">
        <div class="panel-header">
          <h3>各科错题分布对比</h3>
        </div>

        <!-- 描述卡片 -->
        <div class="describe-card">
          <div class="describe-content">
            {{ departmentComparisonDescription }}
          </div>
        </div>

        <!-- 雷达图 -->
        <div class="chart-container">
          <div ref="departmentComparisonChartRef" class="echarts-chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { useEcharts } from '@/hooks/chart.js'
import useUserStore from '@/store/modules/user'
import { getCompletionTrend, getWrongAnalysisOverview, getWrongAnalysisRadar } from '@/api/assistant/assistant.js'

const userStore = useUserStore()

// 计算属性：用户角色
const role = computed(() => {
  return userStore.roles || []
})

// 定义props接收queryForm参数
const props = defineProps({
  queryForm: {
    type: Object,
    default: () => ({
      dateRangeQueryType: '',
      year: '',
      quarter: '',
      month: ''
    })
  },
  selectedDeptObject: {
    type: Object,
    default: null
  }
})

// 计算属性：处理selectedDeptObject逻辑
const selectedDeptType = computed(() => {
  return props.selectedDeptObject && props.selectedDeptObject?.deptType
})

const selectedDeptName = computed(() => {

  return props.selectedDeptObject && props.selectedDeptObject?.label
})

// 计算属性：检查是否为STATION类型
const isStationType = computed(() => {
  return selectedDeptType.value === 'STATION' || !selectedDeptType.value
})

// 统一的参数处理函数
const processQueryParams = (queryParams) => {
  const processedParams = { ...queryParams }

  // 根据部门类型添加相应的参数
  const selectedDept = props.selectedDeptObject
  const { deptType = "", id } = selectedDept ? selectedDept : { deptType: "", id: "" }
  
  processedParams.scopeType = deptType === 'STATION' ? 'STATION' : deptType == 'BRIGADE' ? 'BRIGADE' : deptType == 'MANAGER' ? 'MANAGER' : deptType == 'TEAMS' ? 'TEAM' : deptType == 'USER' ? 'USER' : ''
  processedParams.scopeId = id
  delete processedParams.deptId;
  delete processedParams.teamId;
  delete processedParams.userId;

  return processedParams
}

// 图表容器引用
const completionTrendChartRef = ref(null)
const errorDistributionChartRef = ref(null)
const departmentComparisonChartRef = ref(null)

// 图表实例
const { setOption: setCompletionTrendOption, dispose: disposeCompletionTrend } = useEcharts(completionTrendChartRef)
const { setOption: setErrorDistributionOption, dispose: disposeErrorDistribution } = useEcharts(errorDistributionChartRef)
const { setOption: setDepartmentComparisonOption, dispose: disposeDepartmentComparison } = useEcharts(departmentComparisonChartRef)





// 描述卡片文本变量
const completionTrendDescription = ref('')
const errorDistributionDescription = ref('')
const departmentComparisonDescription = ref('')

// API数据处理函数
const processApiData = (apiData) => {
  console.log('processApiData', apiData);

  // 根据API返回的数据结构进行处理
  if (!apiData || !apiData.model) {
    return { processedData: [], xAxisData: [] };
  }

  const { xAxis, series } = apiData.model;

  // 处理x轴数据
  const xAxisData = xAxis || [];

  // 处理系列数据
  const processedData = [];

  if (series && series.length > 0) {
    // 如果是站长角色，显示多条线；如果是科长角色，显示单条线
    // 这里简化处理，只显示第一条线
    for (let i = 0; i < series.length; i++) {
      // 确保数据是数值类型
      const numericData = series[i].data.map(item => {
        if (typeof item === 'string') {
          return parseFloat(item) || 0;
        }
        return Number(item) || 0;
      });

      processedData.push({
        name: series[i].name,
        type: 'line',
        data: numericData,

      });
    }
  }

  return { processedData, xAxisData };
}

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

  if (!categories.length) return [];

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

  }));
}

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

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

  return { indicators, series }
}

// 获取答题完成趋势数据
const fetchCompletionTrendData = async () => {
  try {
    // 使用统一的参数处理函数
    const processedParams = processQueryParams(props.queryForm)
    const response = await getCompletionTrend(processedParams);
    const { processedData, xAxisData } = processApiData(response);
  
    let stationData = processedData.find(item => item.name === '全站')?.data || 0;


    // 找到除了全站之外的其他科室数据
    const otherDepartments = processedData.filter(item => item.name !== '全站');

    let maxData = null;
    let maxDataPercent = '0.00';

    if (otherDepartments.length > 0) {
      // 如果有其他科室数据，找出完成人数最多的科室
      maxData = otherDepartments.reduce((max, item) => {
        if (item.data[2] > max.data[2]) {
          return item;
        }
        return max;
      }, otherDepartments[0]);

      // 防止除数为0或NaN
      const stationLastValue = stationData[stationData.length - 1] || 0;
      if (stationLastValue > 0) {
        maxDataPercent = ((maxData.data[maxData.data.length - 1] / stationLastValue) * 100).toFixed(2);
      } else {
        maxDataPercent = '0.00';
      }
    }

   


    // 安全获取数组元素，防止NaN
    const lastValue = stationData[stationData.length - 1] || 0;
    const firstValue = stationData[0] || 0;
    const secondValue = stationData[1] || 0;

    // 计算同比
    let tongValue = 0;
    if (firstValue > 0) {
      tongValue = ((lastValue - firstValue) / firstValue) * 100;
    }
    let tong = firstValue === 0 ? '--' : (tongValue > 0 ? '+' : '') + tongValue.toFixed(2);

    // 计算环比
    let huanValue = 0;
    if (secondValue > 0) {
      huanValue = ((lastValue - secondValue) / secondValue) * 100;
    }
    let huan = secondValue === 0 ? '--' : (huanValue > 0 ? '+' : '') + huanValue.toFixed(2);
    // 安全获取maxData数组元素，防止NaN
    const maxDataLastValue = maxData.data[maxData.data.length - 1] || 0;
    const maxDataFirstValue = maxData.data[0] || 0;
    const maxDataSecondValue = maxData.data[1] || 0;
    // 为maxData也计算同比和环比
    let maxDataTong = '--';
    let maxDataHuan = '--';
    if (maxData && maxData.data) {


      // 计算maxData同比
      let maxDataTongValue = 0;
      if (maxDataFirstValue > 0) {
        maxDataTongValue = ((maxDataLastValue - maxDataFirstValue) / maxDataFirstValue) * 100;
      }
      maxDataTong = maxDataFirstValue === 0 ? '--' : (maxDataTongValue > 0 ? '+' : (maxDataTongValue < 0 ? '' : '')) + maxDataTongValue.toFixed(2);

      // 计算maxData环比
      let maxDataHuanValue = 0;
      if (maxDataSecondValue > 0) {
        maxDataHuanValue = ((maxDataLastValue - maxDataSecondValue) / maxDataSecondValue) * 100;
      }
      maxDataHuan = maxDataSecondValue === 0 ? '--' : (maxDataHuanValue > 0 ? '+' : (maxDataHuanValue < 0 ? '' : '')) + maxDataHuanValue.toFixed(2);
    }

    // 根据查询条件决定显示内容
    let descriptionText = '';
    let totalPerson = stationData[stationData.length - 1] || 0;
    if (maxData) {
      
      // 有其他科室数据时显示科室信息
      if (props.queryForm.dateRangeQueryType === 'YEAR') {
        const firstYearStr = isStationType.value ? `${maxData.name}共答题${totalPerson}人次，同比${tong}%，` : '';
        const secondYearStr = isStationType.value ? `${maxData.name}共答题${maxData.data[maxData.data.length - 1]}人次，占比最高为${maxDataPercent}%。` : `${maxData.name}完成${maxDataLastValue}人次，同比${maxDataTong}%。`
        // 年查询：只显示同比，隐藏环比
        descriptionText = `${firstYearStr}${secondYearStr}`;
      } else {
        const firstNotYearStr = isStationType.value ? `${maxData.name}共答题${totalPerson}人次，同比${tong}%，环比${huan}%，` : '';
        const secondNotYearStr = isStationType.value ? `${maxData.name}共答题${maxData.data[maxData.data.length - 1]}人次，占比最高为${maxDataPercent}%。` : `${maxData.name}完成${maxDataLastValue}人次，同比${maxDataTong}%，环比${maxDataHuan}%。`
        // 季度或月查询：显示同比和环比
        descriptionText = `${firstNotYearStr}${secondNotYearStr}`;
      }
    } else {
      // 只有全站数据时显示简化的描述
      if (props.queryForm.dateRangeQueryType === 'YEAR') {
        descriptionText = `${maxData.name}共答题${totalPerson}人次，同比${tong}%。`;
      } else {
        descriptionText = `${maxData.name}共答题${totalPerson}人次，同比${tong}%，环比${huan}%。`;
      }
    }

    // 设置描述卡片文本
    completionTrendDescription.value = descriptionText;
    let data = processedData.map(series => ({
      ...series,
      symbol: 'circle', // 添加数据点标记
      symbolSize: 6,
      smooth: true,
      lineStyle: {
        width: 3
      },
    }))
    

    // 更新答题完成趋势图表
    setCompletionTrendOption({
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: processedData.map(item => item.name)
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxisData
      },
      yAxis: {
        type: 'value'
        // 移除min/max限制，让ECharts自动计算范围
      },
      series: data
    }, true);
  } catch (error) {
    console.error('获取答题完成趋势数据失败:', error);
    // 使用默认数据作为后备
    setCompletionTrendOption({
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['完成率']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: []
      },
      yAxis: {
        type: 'value',
        min: 70,
        max: 100
      },
      series: [
        
      ]
    });
  }
}

// 获取错题分布数据（饼图）
const fetchWrongAnalysisOverviewData = async () => {
  try {
    // 使用统一的参数处理函数
    const processedParams = processQueryParams(props.queryForm)
    const response = await getWrongAnalysisOverview(processedParams);
    const pieData = processOverviewData(response);
    console.log('fetchWrongAnalysisOverviewData', pieData);
    let sortData = pieData.sort((a, b) => b.value - a.value);
    let total = pieData.reduce((acc, cur) => acc + cur.value, 0);
    console.log('total', (sortData[0]?.value / total) * 100)
    // 设置描述卡片文本
    const firstPercentage = ((sortData[0]?.value / total) * 100);
    const secondPercentage = ((sortData[1]?.value / total) * 100);

    errorDistributionDescription.value = `错题主要集中于：${sortData[0]?.name || '--'}，占比：${isNaN(firstPercentage) ? '--' : firstPercentage.toFixed(2)}%；其次为：${sortData[1]?.name || '--'}，占比：${isNaN(secondPercentage) ? '--' : secondPercentage.toFixed(2)}%，为靶向培训、题库优化提供核心依据。`

    // 更新错题分布饼图
    setErrorDistributionOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        top: 'center'
      },

      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      series: [
        {
          name: '错题分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },

          emphasis: {
            label: {
              show: true,
              fontSize: 12,
              fontWeight: 'bold'
            }
          },
          label: {
            show: true,
            formatter: '{b}\n{c} ({d}%)',
            fontSize: 12,
            fontWeight: 'normal'
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 20
          },
          data: pieData
        }
      ]
    });
  } catch (error) {
    console.error('获取错题分布数据失败:', error);
    // 使用默认数据作为后备
    setErrorDistributionOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center'
      },
      series: [
        {
          name: '错题分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 12,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 45.3, name: '操作执行类' },
            { value: 28.7, name: '设施设备类' },
            { value: 15.2, name: '勤务组织类' },
            { value: 8.4, name: '安全知识类' },
            { value: 2.4, name: '其他' }
          ]
        }
      ]
    });
  }
}
// 计算雷达图数据的最大值
const calculateRadarMaxValue = (radarData) => {
  if (!radarData || radarData === 0) return 100;

  let maxValue = 0;

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


  return maxValue
}
// 获取各科错题分布对比数据（雷达图）
const fetchWrongAnalysisRadarData = async () => {
  try {
    // 使用统一的参数处理函数
    const processedParams = processQueryParams(props.queryForm)
    const response = await getWrongAnalysisRadar(processedParams);
    const radarData = processRadarData(response);
    let max = calculateRadarMaxValue(radarData.series)
    // console.log('fetchWrongAnalysisRadarData', radarData);

    const series = radarData.series.map(ele => {
      if (ele.data.every(item => item === 0)) {
        return ''
      }
      let maxIndex = ele.data.indexOf(Math.max(...ele.data))
      return `${ele.name}：问题主要集中于${radarData.indicators[maxIndex]}`

    }).filter(element => !!element).join('；')


    // 设置描述卡片文本
    departmentComparisonDescription.value = `${series}${series.length > 0 ? '，' : '暂无问题'}，可精准识别主管管理短板，分配质控资源。`

    // 更新各科错题分布对比雷达图
    setDepartmentComparisonOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        show: true,
        orient: 'vertical',
        left: 10,
        top: 'center'
      },
      radar: {
        indicator: radarData.indicators.map(indicator => ({
          name: indicator,
          max: max || 100
        }))
      },
      series: [
        {
          type: 'radar',
          data: radarData.series.map(seriesItem => ({
            value: seriesItem.data,
            name: seriesItem.name,
            // areaStyle: {
            //   color: seriesItem.color || 'rgba(84, 112, 198, 0.3)'
            // },
            // lineStyle: {
            //   color: seriesItem.lineColor || '#5470c6'
            // }
          })),
          areaStyle: {

          },

        }
      ]
    });
  } catch (error) {
    console.error('获取各科错题分布对比数据失败:', error);
    // 使用默认数据作为后备
    setDepartmentComparisonOption({
      tooltip: {
        trigger: 'item'
      },
      radar: {
        indicator: [
          { name: '操作执行类', max: 100 },
          { name: '设施设备类', max: 100 },
          { name: '勤务组织类', max: 100 },
          { name: '安全知识类', max: 100 },
          { name: '其他', max: 100 }
        ]
      },
      series: [
        {
          type: 'radar',
          data: [
            {
              value: [85, 45, 30, 60, 10],
              name: '旅检一科',
              areaStyle: {
                color: 'rgba(84, 112, 198, 0.3)'
              },
              lineStyle: {
                color: '#5470c6'
              }
            },
            {
              value: [40, 80, 55, 70, 15],
              name: '旅检二科',
              areaStyle: {
                color: 'rgba(91, 192, 222, 0.3)'
              },
              lineStyle: {
                color: '#5bc0de'
              }
            },
            {
              value: [35, 50, 90, 45, 20],
              name: '旅检三科',
              areaStyle: {
                color: 'rgba(240, 173, 78, 0.3)'
              },
              lineStyle: {
                color: '#f0ad4e'
              }
            }
          ]
        }
      ]
    });
  }
}

// 初始化图表
const initCharts = () => {
  // 获取答题完成趋势数据
  fetchCompletionTrendData();

  // 获取错题分布数据（饼图）
  fetchWrongAnalysisOverviewData();

  // 获取各科错题分布对比数据（雷达图）
  if (selectedDeptType.value === 'STATION' || !selectedDeptType.value) {
    fetchWrongAnalysisRadarData()
  }
}

// 监听查询参数变化
watch(() => props.queryForm, (newVal) => {
  console.log('Q&A分析组件接收到新的查询参数:', newVal)

  // 重新获取所有图表数据
  fetchCompletionTrendData()
  fetchWrongAnalysisOverviewData()
  if (selectedDeptType.value === 'STATION' || !selectedDeptType.value) {
    fetchWrongAnalysisRadarData()
  }

}, { deep: true })

// 组件挂载时初始化
onMounted(() => {
  initCharts()
})

// 组件卸载时清理
onUnmounted(() => {
  disposeCompletionTrend()
  disposeErrorDistribution()
  disposeDepartmentComparison()
})
</script>

<style scoped>
.qa-analysis {
  margin-bottom: 20px;
}

.section-title {
  margin: 14px 0 14px 0;

  /* border-bottom: 2px solid #e8e8e8; */
}

.section-title h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.three-panel-layout {
  display: flex;
  gap: 20px;
}

.panel-item {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.panel-header h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.describe-card {
  background: #F8F8F8;
  border: 1px dashed #CDCCCC;
  border-radius: 6px;
  padding: 7px 10px;
  text-align: left;
  margin-bottom: 10px;
}

.describe-content {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.chart-container {
  height: 300px;
}

.echarts-chart {
  width: 100%;
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .three-panel-layout {
    flex-direction: column;
  }

  .panel-item {
    margin-bottom: 20px;
  }
}
</style>