<script lang="ts" setup>
// 导入部分
import type { EchartsUIType } from '@vben/plugins/echarts';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { ref, watch, onMounted } from 'vue';
import { Page } from '@vben/common-ui';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { ElSelect, ElOption, ElButton, ElSpace, ElRadioGroup, ElRadioButton, ElCard } from 'element-plus';

// 类型定义
interface StationOption {
  label: string;
  value: string;
}

interface AccountOption {
  label: string;
  value: 'operation' | 'hidden';
}

interface OrderType {
  id: number;
  name: string;
  count: number;
  percentage: string;
}

interface HotIssue {
  id: number;
  issue: string;
  count: number;
  station: string;
  percentage: string;
}

// 响应式数据
// 时间维度切换
const periodType = ref<'week' | 'month'>('week');
const currentPeriod = ref('12月4日-12月11日');
const dateRange = ref<string[]>([]);
const selectedStation = ref('');
const selectedAccount = ref('operation');

const stationOptions: StationOption[] = [
  { label: '油站1', value: 'station1' },
  { label: '油站2', value: 'station2' },
  { label: '油站3', value: 'station3' },
  { label: '油站4', value: 'station4' },
  { label: '油站5', value: 'station5' },
];

const accountOptions: AccountOption[] = [
  { label: '运营台账', value: 'operation' },
  { label: '隐患台账', value: 'hidden' },
];

// 图表相关数据
const pieChartRef = ref<EchartsUIType>();
const { renderEcharts: renderPieEcharts } = useEcharts(pieChartRef);

// 辅助函数
// 格式化日期为中文格式（MM月dd日）
const formatDate = (date: Date): string => {
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${month}月${day}日`;
};

// 格式化日期为 YYYY-MM-DD 格式
const formatDateToYMD = (date: Date): string => {
  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}`;
};

// 获取当前周的开始和结束日期（周一到周日）
const getCurrentWeekRange = (): string[] => {
  const today = new Date();
  const dayOfWeek = today.getDay() || 7; // 将周日从0改为7
  const startOfWeek = new Date(today);
  startOfWeek.setDate(today.getDate() - dayOfWeek + 1); // 周一
  const endOfWeek = new Date(startOfWeek);
  endOfWeek.setDate(startOfWeek.getDate() + 6); // 周日
  return [formatDateToYMD(startOfWeek), formatDateToYMD(endOfWeek)];
};

// 获取当前月的开始和结束日期
const getCurrentMonthRange = (): string[] => {
  const today = new Date();
  const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
  const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
  return [formatDateToYMD(startOfMonth), formatDateToYMD(endOfMonth)];
};

// 更新默认日期范围
const updateDefaultDateRange = () => {
  if (periodType.value === 'week') {
    // 设置为当前周的第一天到最后一天
    dateRange.value = getCurrentWeekRange();
  } else {
    // 设置为当前月的第一天到最后一天
    dateRange.value = getCurrentMonthRange();
  }
};

// 图表和数据配置
// 统一的图表颜色配置 - 确保图表颜色风格一致
const CHART_COLORS = {
  EQUIPMENT: '#5ab1ef', // 设备设施工单颜色
  HYGIENE: '#52c41a', // 卫生工单颜色
  COMPLIANCE: '#faad14', // 合规工单颜色
  OTHER: '#f5222d', // 其他工单颜色
  NONE: '#722ed1', // 无工单颜色
};

// Mock数据配置
// 工单类型数据
const MOCK_ORDER_TYPES: OrderType[] = [
  { id: 1, name: '设备设施', count: 120, percentage: '35%' },
  { id: 2, name: '卫生', count: 80, percentage: '23%' },
  { id: 3, name: '合规', count: 60, percentage: '17%' },
  { id: 4, name: '其他', count: 50, percentage: '15%' },
  { id: 5, name: '无', count: 35, percentage: '10%' },
];

// 热点问题TOP10数据
const MOCK_HOT_ISSUES: HotIssue[] = [
  { id: 1, issue: '加油机故障', count: 45, station: '油站1', percentage: '13%' },
  { id: 2, issue: '卫生间卫生差', count: 38, station: '油站2', percentage: '11%' },
  { id: 3, issue: '消防器材过期', count: 32, station: '油站3', percentage: '9%' },
  { id: 4, issue: '油品标识错误', count: 28, station: '油站1', percentage: '8%' },
  { id: 5, issue: '员工未穿工服', count: 25, station: '油站4', percentage: '7%' },
  { id: 6, issue: '地面油污严重', count: 22, station: '油站5', percentage: '6%' },
  { id: 7, issue: '价格牌显示错误', count: 20, station: '油站2', percentage: '6%' },
  { id: 8, issue: '便利店商品过期', count: 18, station: '油站3', percentage: '5%' },
  { id: 9, issue: '安全通道堵塞', count: 15, station: '油站4', percentage: '4%' },
  { id: 10, issue: '照明设备损坏', count: 12, station: '油站5', percentage: '3%' },
];



// 表格配置
// 工单类型表格配置
const orderTypeColumns: VxeGridProps['columns'] = [
  { title: '工单类型', field: 'name' },
  { title: '数量', field: 'count' },
  { title: '占比', field: 'percentage' },
];

const orderTypeGridOptions: VxeGridProps = {
  columns: orderTypeColumns,
  size: 'medium',
  height: '250px',
  useSearchForm: false,
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    ajax: {
      query: async () => {
        return { items: MOCK_ORDER_TYPES, total: MOCK_ORDER_TYPES.length };
      },
    },
  },
  rowConfig: { keyField: 'id' },
  toolbarConfig: {},
  id: 'order-type-table',
};

// 热点问题TOP10表格配置
const hotIssueColumns: VxeGridProps['columns'] = [
  { title: '排名', minWidth: 80, field: 'id', formatter: (row: any, column: any, cellValue: any, index: number) => {
      // 确保排名始终为有效数字
      const rank = Number.isFinite(Number(row.id)) ? Number(row.id) : 
                   Number.isFinite(index) ? index + 1 : 1;
      return `TOP${rank}`;
    }
  },
  { title: '问题描述', minWidth: 200, field: 'issue' },
  { title: '出现次数', minWidth: 100, field: 'count' },
  { title: '主要油站', minWidth: 120, field: 'station' },
  { title: '占比', minWidth: 100, field: 'percentage' },
];

const hotIssueGridOptions: VxeGridProps = {
  columns: hotIssueColumns,
  size: 'medium',
  height: '400px',
  useSearchForm: false,
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    ajax: {
      query: async () => {
        return { items: MOCK_HOT_ISSUES, total: MOCK_HOT_ISSUES.length };
      },
    },
  },
  rowConfig: { keyField: 'id' },
  toolbarConfig: {},
  id: 'hot-issues-table',
};

// 创建表格实例
const [OrderTypeTable] = useVbenVxeGrid({ gridOptions: orderTypeGridOptions });
const [HotIssueTable] = useVbenVxeGrid({ gridOptions: hotIssueGridOptions });

// 图表更新函数
// 更新饼图 - 各类工单占比
const updatePieChart = () => {
  const pieData = MOCK_ORDER_TYPES.map(item => ({
    name: item.name,
    value: item.count,
  }));

  renderPieEcharts({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    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: 20,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: pieData,
        color: [CHART_COLORS.EQUIPMENT, CHART_COLORS.HYGIENE, CHART_COLORS.COMPLIANCE, CHART_COLORS.OTHER, CHART_COLORS.NONE],
      },
    ],
  });
};

// 事件处理函数
// 查询按钮点击事件
const handleQuery = () => {
  console.log('查询条件:', {
    station: selectedStation.value,
    account: selectedAccount.value,
    periodType: periodType.value,
    dateRange: dateRange.value,
  });
  // TODO: 这里可以添加实际的查询逻辑，调用API获取真实数据
  updatePieChart();
};

// 导出按钮点击事件
const handleExport = () => {
  console.log('导出数据');
  // TODO: 这里可以添加导出逻辑
};

// 生命周期钩子和监听
// 监听时间类型变化 - 更新当前时段显示
watch(periodType, () => {
  updateDefaultDateRange();
});

// 组件初始化 - 设置默认数据和图表
onMounted(() => {
  updateDefaultDateRange(); // 初始化时间范围
  updatePieChart(); // 初始化饼图
});
</script>

<template>
  <Page :auto-content-height="true">
    <div class="analysis-container">
      <!-- 页面标题 -->
      <div class="page-title">
        <h2>订单类型分析</h2>
      </div>

      <!-- 搜索和时间筛选区域 -->
      <div class="search-filter-container">
        <ElSpace wrap>
          <div class="filter-item">
            <label>油站：</label>
            <ElSelect v-model="selectedStation" placeholder="请选择油站" style="width: 150px;">
              <ElOption v-for="station in stationOptions" :key="station.value" :label="station.label" :value="station.value" />
            </ElSelect>
          </div>
          <div class="filter-item">
            <label>台账类型：</label>
            <ElSelect v-model="selectedAccount" placeholder="请选择台账类型" style="width: 150px;">
              <ElOption v-for="account in accountOptions" :key="account.value" :label="account.label" :value="account.value" />
            </ElSelect>
          </div>
          <div class="filter-item">
            <label>时间：</label>
            <ElRadioGroup v-model="periodType" size="large">
              <ElRadioButton label="week" value="week">周</ElRadioButton>
              <ElRadioButton label="month" value="month">月</ElRadioButton>
            </ElRadioGroup>
          </div>
          <div class="filter-item">
            <label>选择时段：</label>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator=" 至 "
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 300px;"
            />
          </div>
          <div class="filter-item">
            <ElButton type="primary" @click="handleQuery">查询</ElButton>
          </div>
        </ElSpace>
      </div>



      <!-- 图形分析模块 -->
      <div class="graph-analysis-container">
        <h3 class="module-title">图形分析</h3>
        <div class="graph-content">
          <!-- 饼图区域 -->
          <div class="pie-chart-wrapper">
            <div class="chart-title">各类工单占比</div>
            <EchartsUI ref="pieChartRef" style="width: 100%; height: 350px;" />
          </div>
          <!-- 工单类型表格 -->
          <div class="order-type-table-wrapper">
            <div class="table-title">工单类型明细</div>
            <OrderTypeTable />
          </div>
        </div>
      </div>

      <!-- 热点问题TOP10模块 -->
      <div class="hot-issues-container">
        <div class="module-header">
          <h3 class="module-title">热点问题TOP10</h3>
          <ElButton @click="handleExport">导出</ElButton>
        </div>
        <div class="hot-issues-table">
          <HotIssueTable />
        </div>
      </div>
    </div>
  </Page>
</template>

<style scoped lang="scss">
.analysis-container {
  min-height: 100vh;
  padding: 16px;
  background-color: #fff;

  .page-title {
    margin-bottom: 24px;

    h2 {
      font-size: 20px;
      font-weight: 600;
      color: #1f2937;
    }
  }

  .search-filter-container {
    padding: 20px;
    margin-bottom: 24px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgb(0 0 0 / 8%);

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

      label {
        margin-right: 8px;
        font-weight: 500;
        color: #374151;
      }

      .period-info {
        padding: 4px 12px;
        font-weight: 500;
        color: #3b82f6;
        background-color: #f0f9ff;
        border-radius: 4px;
      }
    }
  }



  // 图形分析样式
  .graph-analysis-container {
    margin-bottom: 24px;

    .module-title {
      margin-bottom: 16px;
      font-size: 18px;
      font-weight: 600;
      color: #1f2937;
    }

    .graph-content {
      display: flex;
      gap: 24px;
      padding: 20px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgb(0 0 0 / 8%);

      @media (max-width: 1024px) {
        flex-direction: column;

        .pie-chart-wrapper,
        .exception-table-wrapper {
          flex: 1;
          min-width: auto;
        }
      }

      .pie-chart-wrapper {
        flex: 0.5;
        min-width: 350px;

        .chart-title {
          margin-bottom: 16px;
          font-size: 16px;
          font-weight: 500;
          color: #374151;
          text-align: center;
        }
      }

      .order-type-table-wrapper {
        flex: 0.5;
        min-width: 300px;

        .table-title {
          margin-bottom: 16px;
          font-size: 16px;
          font-weight: 500;
          color: #374151;
        }
      }
    }
  }

  // 热点问题样式
  .hot-issues-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgb(0 0 0 / 8%);

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

    .module-title {
      font-size: 18px;
      font-weight: 600;
      color: #1f2937;
    }

    .hot-issues-table {
      margin-top: 16px;
    }
  }
}
</style>
