<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import type { Dayjs } from 'dayjs';
import { use } from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, TitleComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
import type { SatisfactionStatisticsModel, SatisfactionStatisticsQuery, SatisfactionModel } from '@/model/satisfaction.model';
import { satisfactionStatisticsMethod, satisfactionMethod } from '@/request/api/satisfaction.api';
import { useRequest } from 'alova/client';
import { notification } from 'ant-design-vue';

use([CanvasRenderer, BarChart, GridComponent, TooltipComponent, TitleComponent]);

defineOptions({
  name: 'SatisfactionStatisticsPage',
});

const questionnaireList = ref<Array<{ label: string; value: string }>>([]);
const { onSuccess } = useRequest(satisfactionMethod, {
  immediate: true,
});
onSuccess((res: any) => {
  if (res && res.data && Array.isArray(res.data?.data)) {
    questionnaireList.value = res.data.data.map((item: SatisfactionModel) => ({
      label: item.name || '',
      value: item.id || '',
    }));
  }
});

// 默认选中第一张问卷
const questionnaireId = ref<Array<{ label: string; value: string }>>([]);
type RangeValue = [Dayjs, Dayjs] | null;

const selectedRange = ref<RangeValue>(null) as any;

const statisticsData = ref<Record<string, SatisfactionStatisticsModel>>({});

const { loading, send: fetchStatistics } = useRequest((params?: SatisfactionStatisticsQuery) => satisfactionStatisticsMethod(params), {
  immediate: false,
});

async function loadStatistics(range?: RangeValue) {
  const selected = questionnaireId.value;
  if (!selected || !Array.isArray(selected) || selected.length === 0) {
    statisticsData.value = {};
    return;
  }

  // 获取所有选中的问卷ID
  const ids = selected.map((item) => {
    if (typeof item === 'object' && item !== null) {
      return String(item.value || '');
    }
    return String(item);
  });

  //时间范围
  const baseParams: Partial<SatisfactionStatisticsQuery> = {};
  if (range) {
    baseParams.sendTimeStart = range[0].startOf('day').format('YYYY-MM-DD');
    baseParams.sendTimeEnd = range[1].endOf('day').format('YYYY-MM-DD');
  }

  // 为每个问卷ID分别调用接口
  const dataMap: Record<string, SatisfactionStatisticsModel> = {};

  try {
    // 并发请求所有问卷的统计数据
    const promises = ids.map(async (id) => {
      const params: SatisfactionStatisticsQuery = {
        id,
        ...baseParams,
      } as SatisfactionStatisticsQuery;

      try {
        const res = await fetchStatistics(params);
        console.log(`问卷 ${id} 的统计数据:`, res);
        if (res && typeof res === 'object') {
          const data = { ...res, id: id } as SatisfactionStatisticsModel;
          if (Array.isArray(data.xaxis) && Array.isArray(data.yaxis)) {
            return { id, data };
          }
        }
        return null;
      } catch (error) {
        notification.error({ message: `获取问卷 ${id} 的统计数据失败`, description: (error as Error).message });
        return null;
      }
    });

    const results = await Promise.all(promises);

    // 处理返回结果
    results.forEach((result) => {
      if (result && result.data) {
        dataMap[result.id] = result.data;
      }
    });

    statisticsData.value = dataMap;
  } catch (error) {
    notification.error({ message: '获取满意度统计失败', description: (error as Error).message });
    statisticsData.value = {};
  }
}

// 处理查询按钮点击
function handleQuery() {
  loadStatistics(selectedRange.value ?? undefined);
}

// 监听问卷列表变化，自动选中第一张问卷
let isInitialLoad = true;
watch(
  questionnaireList,
  (newList) => {
    if (newList.length > 0 && questionnaireId.value.length === 0) {
      questionnaireId.value = [
        {
          label: newList[0].label,
          value: newList[0].value,
        },
      ];
      // 默认选中第一个问卷时，自动加载一次数据
      if (isInitialLoad) {
        isInitialLoad = false;
        loadStatistics(selectedRange.value ?? undefined);
      }
    }
  },
  { immediate: true }
);

// 为每个选中的问卷生成图表配置
const chartOptions = computed(() => {
  const selected = questionnaireId.value;
  if (!selected || !Array.isArray(selected) || selected.length === 0) {
    return [];
  }

  return selected
    .map((questionnaire) => {
      let qValue: string;
      let qLabel: string;

      if (typeof questionnaire === 'object' && questionnaire !== null) {
        qValue = String(questionnaire.value || '');

        let tempLabel: any = questionnaire.label;
        if (tempLabel && typeof tempLabel === 'string') {
          qLabel = tempLabel;
        } else {
          const found = questionnaireList.value.find((item) => String(item.value) === qValue);
          qLabel = found?.label || `问卷 ${qValue}`;
        }
      } else {
        qValue = String(questionnaire);
        const found = questionnaireList.value.find((item) => String(item.value) === qValue);
        qLabel = found?.label || `问卷 ${qValue}`;
      }

      qLabel = String(qLabel || `问卷 ${qValue}`);

      // 获取该问卷的统计数据
      const statData = statisticsData.value[qValue];

      if (!statData || !Array.isArray(statData.xaxis) || !Array.isArray(statData.yaxis)) {
        return null;
      }

      // 使用返回的数据 xaxis 和 yaxis
      const xaxis = statData.xaxis;
      const yaxis = statData.yaxis;

      return {
        questionnaireId: qValue,
        questionnaireLabel: qLabel,
        option: {
          title: {
            text: String(qLabel), // 确保是字符串
            left: 'center',
            top: 0,
            textStyle: {
              fontSize: 16,
              fontWeight: 600,
              color: '#333',
            },
          },
          tooltip: { trigger: 'axis' },
          grid: { left: 60, right: 40, top: 50, bottom: 50 },
          xAxis: {
            type: 'category',
            data: xaxis,
            name: '分',
            nameGap: 25,
            axisTick: { alignWithLabel: true },
            axisLabel: { fontSize: 12 },
          },
          yAxis: {
            type: 'value',
            name: '人',
            minInterval: 1,
            splitLine: {
              lineStyle: { type: 'dashed', color: '#eaeaea' },
            },
            axisLine: { lineStyle: { color: '#d9d9d9' } },
          },
          series: [
            {
              type: 'bar',
              data: yaxis,
              barWidth: 40,
              itemStyle: {
                color: '#69c0ff',
                borderRadius: [6, 6, 0, 0],
              },
              emphasis: {
                focus: 'series',
                itemStyle: {
                  color: '#4096ff',
                },
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}',
              },
            },
          ],
        },
      };
    })
    .filter((config) => config !== null) as Array<{
    questionnaireId: string;
    questionnaireLabel: string;
    option: any;
  }>;
});

defineExpose({
  send: () => loadStatistics(selectedRange.value ?? undefined),
});
</script>

<template>
  <div class="statistics-page">
    <section class="filter-card">
      <div class="filter-item mr-10">
        <span class="label">发送日期：</span>
        <a-range-picker v-model:value="selectedRange" allow-clear format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" />
      </div>
      <div class="filter-item">
        <span class="label">选择问卷：</span>
        <a-select v-model:value="questionnaireId" placeholder="请选择问卷名称" style="width: 300px" mode="multiple" :labelInValue="true">
          <a-select-option v-for="item in questionnaireList" :key="item.value" :value="item.value" :label="item.label">{{ item.label }}</a-select-option>
        </a-select>
      </div>
      <div class="button-item"><a-button type="primary" @click="handleQuery">查询</a-button></div>
    </section>

    <section class="chart-card">
      <a-spin :spinning="loading">
        <main>
          <template v-if="chartOptions.length > 0">
            <div v-for="(chartConfig, index) in chartOptions" :key="`chart-${String(chartConfig.questionnaireId)}-${index}`" class="chart-wrapper">
              <VChart class="chart" :option="chartConfig.option" autoresize />
            </div>
          </template>
          <a-empty v-else description="请选择问卷查看统计" />
        </main>
      </a-spin>
    </section>
  </div>
</template>

<style scoped lang="scss">
.button-item {
  margin-left: 80px;
}
.statistics-page {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #f0f0f0;
}

.filter-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px 24px;
  display: flex;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 12px;

  .label {
    color: rgba(0, 0, 0, 0.65);
    font-weight: 500;
  }
}

.filter-hint {
  color: rgba(0, 0, 0, 0.45);
}

.chart-card {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  flex-direction: column;
  min-height: 0;

  :deep(.ant-spin-container) {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  main {
    flex: 1;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 24px;
    min-height: 0;
  }
}

.chart-wrapper {
  width: calc((100% - 24px) / 2);
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #f0f0f0;
  box-sizing: border-box;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
}

.chart-subtitle {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  margin-top: 4px;
}

.summary {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);

  strong {
    font-size: 20px;
    color: #1677ff;
  }
}

.chart {
  width: 100%;
  height: 420px;
}
</style>
