<template>
  <a-spin :loading="loading" style="width: 100%">
    <a-card
      class="general-card"
      :header-style="{ paddingBottom: 0 }"
      :body-style="{
        paddingTop: '20px'
      }"
      title="订单量"
    >
      <template #extra>
        <a-space>
          <a-range-picker
            v-model="dateRange"
            style="width: 240px"
            @change="handleDateChange"
          />
          <a-select
            v-model="selectedMerchants"
            :options="merchantOptions"
            placeholder="选择商户"
            multiple
            allow-clear
            style="width: 200px"
            @change="handleMerchantChange"
          />
          <a-select
            v-model="selectedRoads"
            :options="roadOptions"
            placeholder="选择通道"
            multiple
            allow-clear
            style="width: 200px"
            @change="handleRoadChange"
          />
          <a-button type="primary" @click="handleDetailClick">明细</a-button>
        </a-space>
      </template>
      <Chart
        height="289px"
        :option="chartOption"
        @legendselectchanged="handleLegendSelect"
      />
    </a-card>

    <!-- 明细模态框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="订单明细"
      :width="1000"
      :footer="false"
    >
      <a-table
        :data="detailData"
        :pagination="{
          total: detailData.length,
          pageSize: 10,
          showTotal: true
        }"
        :bordered="false"
        :stripe="true"
      >
        <template #columns>
          <a-table-column title="日期" data-index="date" />
          <a-table-column title="商户" data-index="merchantName" />
          <a-table-column title="通道" data-index="roadName" />
          <a-table-column title="成功订单数" data-index="succeedCount" />
          <a-table-column title="总订单数" data-index="totalCount" />
          <a-table-column title="失败订单数" data-index="failedCount" />
          <a-table-column title="等待订单数" data-index="waitedCount" />
          <a-table-column title="成功展示金额" data-index="succeedShowAmount" />
          <a-table-column title="成功实际金额" data-index="succeedFactAmount" />
          <a-table-column title="总展示金额" data-index="totalShowAmount" />
          <a-table-column title="总实际金额" data-index="totalFactAmount" />
          <a-table-column title="成功率" data-index="rate">
            <template #cell="{ record }">{{ record.rate }}%</template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { graphic } from 'echarts';
import useLoading from '@/hooks/loading';
import useChartOption from '@/hooks/chart-option';
import { ToolTipFormatterParams } from '@/types/echarts';
import { AnyObject } from '@/types/global';
import { apiClient } from '@/api';
import { KamiApiOrderV1OrderSummaryDailyRecord } from '@/api/generated';
import dayjs from 'dayjs';
import { LegendComponentOption } from 'echarts';

// 状态变量
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
const selectedMerchants = ref<string[]>([]);
const selectedRoads = ref<string[]>([]);
const detailVisible = ref(false);
const detailData = ref<KamiApiOrderV1OrderSummaryDailyRecord[]>([]);
const rawData = ref<KamiApiOrderV1OrderSummaryDailyRecord[]>([]);

// 筛选选项数据
const merchantOptions = ref<{ label: string; value: string }[]>([]);
const roadOptions = ref<{ label: string; value: string }[]>([]);
const dateOptions = ref<{ startDate: string; endDate: string }>({
  startDate: '',
  endDate: ''
});

// 获取商户列表
const fetchMerchantList = async () => {
  try {
    const { data } = await apiClient.apiMerchantListSampleAllGet();
    merchantOptions.value = data.list.map(item => ({
      label: item.merchantName || '',
      value: item.id || null
    }));
  } catch (err) {
    console.error('获取商户列表失败:', err);
  }
};

// 获取通道列表
const fetchRoadList = async () => {
  try {
    const { data } = await apiClient.apiRoadSimpleGetAllGet();
    roadOptions.value = data.list.map(item => ({
      label: item.roadName || '',
      value: item.roadUid || ''
    }));
  } catch (err) {
    console.error('获取通道列表失败:', err);
  }
};

// 获取日期范围
const fetchDateRange = async () => {
  // 初始时间是当前时间-15 天
  dateRange.value = [dayjs().subtract(15, 'day'), dayjs()];
  dateOptions.value.startDate = dateRange.value[0].format('YYYY-MM-DD');
  dateOptions.value.endDate = dateRange.value[1].format('YYYY-MM-DD');
};

// 初始化数据
const initData = async () => {
  await Promise.all([fetchMerchantList(), fetchRoadList(), fetchDateRange()]);
  await fetchData();
};

// 处理日期变化
const handleDateChange = () => {
  fetchData();
};

// 处理商户变化
const handleMerchantChange = () => {
  fetchData();
};

// 处理通道变化
const handleRoadChange = () => {
  fetchData();
};

// 处理明细点击
const handleDetailClick = () => {
  detailData.value = rawData.value;
  detailVisible.value = true;
};

// 获取筛选后的数据
const getFilteredData = () => {
  let filtered = [...rawData.value];

  if (dateRange.value) {
    const [start, end] = dateRange.value;
    filtered = filtered.filter(item => {
      const date = dayjs(item.date);
      return date.isAfter(start) && date.isBefore(end);
    });
  }

  if (selectedMerchants.value.length > 0) {
    filtered = filtered.filter(item =>
      selectedMerchants.value.includes(item.merchantUid)
    );
  }

  if (selectedRoads.value.length > 0) {
    filtered = filtered.filter(item =>
      selectedRoads.value.includes(item.roadUid)
    );
  }

  return filtered;
};

// 更新图表数据
const updateChartData = () => {
  const filtered = getFilteredData();

  // 获取日期范围
  const dates = filtered.map(item => item.date);
  const minDate = dayjs(Math.min(...dates.map(d => new Date(d).getTime())));
  const maxDate = dayjs(Math.max(...dates.map(d => new Date(d).getTime())));

  // 生成完整的日期序列
  const allDates: string[] = [];
  let currentDate = minDate;
  while (currentDate.isBefore(maxDate) || currentDate.isSame(maxDate, 'day')) {
    allDates.push(currentDate.format('YYYY-MM-DD'));
    currentDate = currentDate.add(1, 'day');
  }

  // 重置数据
  xAxis.value = allDates;
  seriesData.value = [
    { name: '成功订单量', data: [] },
    { name: '总订单量', data: [] },
    { name: '成功率', data: [] }
  ];

  // 填充数据
  allDates.forEach(date => {
    const dayData = filtered.filter(item => item.date === date);
    const succeedAmount = dayData.reduce(
      (sum, item) => sum + item.succeedFactAmount,
      0
    );
    const totalAmount = dayData.reduce(
      (sum, item) => sum + item.totalFactAmount,
      0
    );

    // 计算成功率
    const rate = totalAmount > 0 ? (succeedAmount / totalAmount) * 100 : 0;

    seriesData.value[0].data.push(succeedAmount);
    seriesData.value[1].data.push(totalAmount);
    seriesData.value[2].data.push(rate);
  });

  // 更新图表边界文本
  if (allDates.length > 0) {
    graphicElements.value[0].style.text = allDates[0];
    graphicElements.value[1].style.text = allDates[allDates.length - 1];
  }
};

// 定义线条颜色配置
const lineColors = [
  {
    line: [
      { offset: 0, color: 'rgba(30, 231, 255, 1)' },
      { offset: 0.5, color: 'rgba(36, 154, 255, 1)' },
      { offset: 1, color: 'rgba(111, 66, 251, 1)' }
    ],
    area: [
      { offset: 0, color: 'rgba(17, 126, 255, 0.16)' },
      { offset: 1, color: 'rgba(17, 128, 255, 0)' }
    ]
  },
  {
    line: [
      { offset: 0, color: 'rgba(255, 99, 132, 1)' },
      { offset: 0.5, color: 'rgba(255, 159, 64, 1)' },
      { offset: 1, color: 'rgba(255, 205, 86, 1)' }
    ],
    area: [
      { offset: 0, color: 'rgba(255, 99, 132, 0.16)' },
      { offset: 1, color: 'rgba(255, 99, 132, 0)' }
    ]
  },
  {
    line: [
      { offset: 0, color: 'rgba(75, 192, 192, 1)' },
      { offset: 0.5, color: 'rgba(54, 162, 235, 1)' },
      { offset: 1, color: 'rgba(153, 102, 255, 1)' }
    ],
    area: [
      { offset: 0, color: 'rgba(75, 192, 192, 0.16)' },
      { offset: 1, color: 'rgba(75, 192, 192, 0)' }
    ]
  },
  {
    line: [
      { offset: 0, color: 'rgba(255, 159, 64, 1)' },
      { offset: 0.5, color: 'rgba(255, 99, 132, 1)' },
      { offset: 1, color: 'rgba(153, 102, 255, 1)' }
    ],
    area: [
      { offset: 0, color: 'rgba(255, 159, 64, 0.16)' },
      { offset: 1, color: 'rgba(255, 159, 64, 0)' }
    ]
  }
];

function graphicFactory(side: AnyObject) {
  return {
    type: 'text',
    bottom: '8',
    ...side,
    style: {
      text: '',
      textAlign: 'center',
      fill: '#4E5969',
      fontSize: 12
    }
  };
}

const { loading, setLoading } = useLoading(true);
const xAxis = ref<string[]>([]);
const seriesData = ref<{ name: string; data: number[] }[]>([]);
const graphicElements = ref([
  graphicFactory({ left: '2.6%' }),
  graphicFactory({ right: 0 })
]);

// 定义图例选中状态的类型
interface LegendSelected {
  成功订单量: boolean;
  总订单量: boolean;
  成功率: boolean;
}

// 添加图例选中状态
const legendSelected = ref<LegendSelected>({
  成功订单量: true,
  总订单量: true,
  成功率: true
});

const { chartOption } = useChartOption(() => {
  return {
    grid: {
      left: '2.6%',
      right: '0',
      top: '10',
      bottom: '30'
    },
    legend: {
      show: true,
      top: 0,
      right: 0,
      textStyle: {
        color: '#4E5969'
      },
      selectedMode: 'multiple',
      selected: legendSelected.value
    } as LegendComponentOption,
    xAxis: {
      type: 'category',
      offset: 2,
      data: xAxis.value,
      boundaryGap: false,
      axisLabel: {
        color: '#4E5969',
        formatter(value: number, idx: number) {
          if (idx === 0) return '';
          if (idx === xAxis.value.length - 1) return '';
          return `${value}`;
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: true,
        interval: (idx: number) => {
          if (idx === 0) return false;
          if (idx === xAxis.value.length - 1) return false;
          return true;
        },
        lineStyle: {
          color: '#E5E8EF'
        }
      },
      axisPointer: {
        show: true,
        lineStyle: {
          color: '#23ADFF',
          width: 2
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '订单量',
        nameTextStyle: {
          color: '#4E5969'
        },
        axisLine: {
          show: false
        },
        axisLabel: {
          formatter(value: any, idx: number) {
            if (idx === 0) return value;
            return `${value}`;
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#E5E8EF'
          }
        },
        min: 0,
        max: function (value: { min: number; max: number }) {
          // 获取当前显示的数据系列
          const visibleSeries = seriesData.value.filter((_, index) => {
            const name = ['成功订单量', '总订单量', '成功率'][index];
            return legendSelected.value[name as keyof LegendSelected];
          });

          // 返回订单所有数据的最大值
          let maxValue = 0;
          visibleSeries.forEach(series => {
            maxValue = Math.max(maxValue, Math.max(...series.data));
          });
          // 判断数字出多少位，数字中可能有小数
          return (
            Math.ceil(maxValue) + Math.pow(10, maxValue.toFixed().length - 2)
          ); // 向上取整到最接近的千位
        }
      },
      {
        type: 'value',
        name: '成功率',
        nameTextStyle: {
          color: '#4E5969'
        },
        axisLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value}%'
        },
        splitLine: {
          show: false
        }
      }
    ],
    tooltip: {
      trigger: 'axis',
      formatter(params: ToolTipFormatterParams[]) {
        const paramsList = params as ToolTipFormatterParams[];
        let result = `<div><p class="tooltip-title">${paramsList[0].axisValueLabel}</p>`;
        paramsList.forEach(item => {
          result += `<div class="content-panel"><span>${item.seriesName}</span><span class="tooltip-value">${
            item.seriesName === '成功率'
              ? `${Number(item.value).toFixed(2)}%`
              : Number(item.value).toLocaleString()
          }</span></div>`;
        });
        result += '</div>';
        return result;
      },
      className: 'echarts-tooltip-diy'
    },
    graphic: {
      elements: graphicElements.value
    },
    series: seriesData.value.map((series, index) => ({
      name: series.name,
      data: series.data,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 12,
      yAxisIndex: series.name === '成功率' ? 1 : 0,
      emphasis: {
        focus: 'series',
        itemStyle: {
          borderWidth: 2
        }
      },
      lineStyle: {
        width: 3,
        color: new graphic.LinearGradient(
          0,
          0,
          1,
          0,
          lineColors[index % lineColors.length].line
        )
      },
      showSymbol: false,
      areaStyle: {
        opacity: 0.8,
        color: new graphic.LinearGradient(
          0,
          0,
          0,
          1,
          lineColors[index % lineColors.length].area
        )
      }
    }))
  };
});

const fetchData = async () => {
  setLoading(true);
  try {
    const { data: chartData } =
      await apiClient.apiOrderInfoSummaryDailyStatsGet({
        roadUid:
          selectedRoads.value.length > 0 ? selectedRoads.value : undefined,
        merchantUid:
          selectedMerchants.value.length > 0
            ? selectedMerchants.value
            : undefined,
        dateRange: dateRange.value
          ? [
              dayjs(dateRange.value[0]).format('YYYY-MM-DD'),
              dayjs(dateRange.value[1]).format('YYYY-MM-DD')
            ]
          : undefined
      });

    rawData.value = chartData.list;
    updateChartData();
  } catch (err) {
    console.error('获取订单数据失败:', err);
  } finally {
    setLoading(false);
  }
};

// 使用 onMounted 替代直接调用
onMounted(() => {
  initData();
});

// 添加图例点击事件处理
const handleLegendSelect = (params: { selected: LegendSelected }) => {
  // 更新图例选中状态
  legendSelected.value = params.selected;
  // 重新计算并更新图表
  updateChartData();
};
</script>

<style scoped lang="less">
:deep(.arco-table-th) {
  background-color: var(--color-fill-2);
}
</style>
