<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 } from 'element-plus';

// 类型定义
interface TabOption {
  label: string;
  value: 'station' | 'area';
}

interface StationOption {
  label: string;
  value: string;
}

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

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

interface StationException {
  id: number;
  station: string;
  area: string;
  total: number;
  transferred: number;
  completed: number;
  pending: number;
  unhandled: number;
  equipment: number;
  none: number;
  hygiene: number;
  compliance: number;
}

// 响应式数据
// Tab切换数据
const activeTab = ref<'station' | 'area'>('station');
const tabOptions: TabOption[] = [
  { label: '油站', value: 'station' },
  { label: '片区', value: 'area' },
];

// 搜索相关数据
const periodType = ref<'week' | 'month'>('week');
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 barChartRef = ref<EchartsUIType>();
const { renderEcharts: renderPieEcharts } = useEcharts(pieChartRef);
const { renderEcharts: renderBarEcharts } = useEcharts(barChartRef);

// 辅助函数
// 格式化日期为中文格式（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', // 无异常颜色
  TRANSFERRED: '#5ab1ef', // 转任务颜色
  COMPLETED: '#52c41a', // 已完成颜色
  PENDING: '#faad14', // 待处理颜色
  UNHANDLED: '#f5222d', // 未处理颜色
};

// Mock数据配置
// 异常类型数据
const MOCK_EXCEPTION_TYPES: ExceptionType[] = [
  { 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%' },
];

// 油站异常数据
const MOCK_STATION_EXCEPTIONS: StationException[] = [
  { id: 1, station: '油站1', area: '片区1', total: 150, transferred: 80, completed: 40, pending: 20, unhandled: 10, equipment: 60, none: 20, hygiene: 40, compliance: 30 },
  { id: 2, station: '油站2', area: '片区1', total: 120, transferred: 70, completed: 30, pending: 15, unhandled: 5, equipment: 50, none: 15, hygiene: 30, compliance: 25 },
  { id: 3, station: '油站3', area: '片区2', total: 180, transferred: 90, completed: 50, pending: 30, unhandled: 10, equipment: 70, none: 25, hygiene: 50, compliance: 35 },
  { id: 4, station: '油站4', area: '片区2', total: 90, transferred: 50, completed: 25, pending: 10, unhandled: 5, equipment: 35, none: 10, hygiene: 25, compliance: 20 },
  { id: 5, station: '油站5', area: '片区3', total: 200, transferred: 100, completed: 60, pending: 30, unhandled: 10, equipment: 80, none: 30, hygiene: 55, compliance: 35 },
];

// 表格配置
// 异常类型表格配置
const exceptionColumns: VxeGridProps['columns'] = [
  { title: '标签名', field: 'name' },
  { title: '数量', field: 'count' },
  { title: '占比', field: 'percentage' },
];

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

// 油站异常表格配置
const stationExceptionColumns: VxeGridProps['columns'] = [
  { title: '油站', minWidth: 120, field: 'station' },
  { title: '片区', minWidth: 120, field: 'area' },
  { title: '总数', minWidth: 100, field: 'total' },
  { title: '转任务', minWidth: 100, field: 'transferred' },
  { title: '已完成', minWidth: 100, field: 'completed' },
  { title: '未处理', minWidth: 100, field: 'unhandled' },
  { title: '待处理', minWidth: 100, field: 'pending' },
  { title: '设备设施', minWidth: 120, field: 'equipment' },
  { title: '无', minWidth: 80, field: 'none' },
  { title: '卫生', minWidth: 80, field: 'hygiene' },
  { title: '合规', minWidth: 80, field: 'compliance' },
];

const stationExceptionGridOptions: VxeGridProps = {
  columns: stationExceptionColumns,
  size: 'medium',
  height: '400px',
  useSearchForm: false,
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    ajax: {
      query: async () => {
        return { items: MOCK_STATION_EXCEPTIONS, total: MOCK_STATION_EXCEPTIONS.length };
      },
    },
  },
  rowConfig: { keyField: 'id' },
  toolbarConfig: {},
  id: 'station-exception-table',
};

// 创建表格实例
const [ExceptionTable] = useVbenVxeGrid({ gridOptions: exceptionGridOptions });
const [StationExceptionTable] = useVbenVxeGrid({ gridOptions: stationExceptionGridOptions });

// 图表更新函数
// 更新饼图 - 各类异常占比
const updatePieChart = () => {
  const pieData = MOCK_EXCEPTION_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 updateBarChart = () => {
  const stationNames = MOCK_STATION_EXCEPTIONS.map(item => item.station);
  const exceptionData = MOCK_STATION_EXCEPTIONS.map(item => item.total);

  renderBarEcharts({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: stationNames,
        axisTick: {
          alignWithLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '异常数量',
      },
    ],
    series: [
      {
        name: '异常总数',
        type: 'bar',
        barWidth: '10%',
        data: exceptionData,
        itemStyle: {
          color: CHART_COLORS.TRANSFERRED,
        },
      },
    ],
  });
};

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

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

// 生命周期钩子和监听
// 监听时间类型变化 - 更新默认日期范围
watch(periodType, () => {
  updateDefaultDateRange();
});

// 监听标签页变化 - 重新加载数据和图表
watch(activeTab, () => {
  updatePieChart();
  updateBarChart();
});

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

<template>
  <Page :auto-content-height="true">
    <div class="account-analysis">
      <!-- Tab切换区域 -->
      <div class="tab-container">
        <el-tabs v-model="activeTab">
          <el-tab-pane v-for="tab in tabOptions" :key="tab.value" :label="tab.label" :name="tab.value">
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 搜索栏区域 -->
      <div class="search-container">
        <ElSpace>
          <div class="search-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="search-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="search-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="search-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>
        </ElSpace>
      </div>

      <!-- 操作按钮区域 -->
      <div class="button-container">
        <ElSpace>
          <ElButton type="primary" @click="handleQuery">查询</ElButton>
        </ElSpace>
      </div>

      <!-- 各类异常占比模块 -->
      <div class="exception-type-container">
        <h3>各类异常占比</h3>
        <div class="exception-type-content">
          <!-- 饼图区域 -->
          <div class="pie-chart">
            <EchartsUI ref="pieChartRef" style="width: 100%; height: 300px;" />
          </div>
          <!-- 异常类型表格 -->
          <div class="exception-type-table">
            <ExceptionTable />
          </div>
        </div>
      </div>

      <!-- 油站异常报表模块 -->
      <div class="station-exception-container">
        <div class="station-exception-header">
          <h3>油站异常报表</h3>
          <ElButton @click="handleExport">导出</ElButton>
        </div>
        <!-- 柱状图区域 -->
        <div class="bar-chart">
          <EchartsUI ref="barChartRef" style="width: 100%; height: 300px;" />
        </div>
        <!-- 油站异常表格 -->
        <div class="station-exception-table">
          <StationExceptionTable />
        </div>
      </div>
    </div>
  </Page>
</template>

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

  .tab-container {
    margin-bottom: 16px;
  }

  .search-container {
    display: flex;
    align-items: center;
    padding: 16px;
    margin-bottom: 16px;
    background-color: #fff;
    border-radius: 6px;

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

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

  .button-container {
    margin-bottom: 16px;
  }

  .exception-type-container {
    padding: 16px;
    margin-bottom: 16px;
    background-color: #fff;
    border-radius: 6px;

    h3 {
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
    }

    .exception-type-content {
      display: flex;
      gap: 16px;

      .pie-chart {
        flex: 0.4;
        min-width: 300px;
      }

      .exception-type-table {
        flex: 0.6;
        min-width: 300px;
      }
    }
  }

  .station-exception-container {
    padding: 16px;
    background-color: #fff;
    border-radius: 6px;

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

      h3 {
        font-size: 16px;
        font-weight: 600;
      }
    }

    .bar-chart {
      width: 100%;
      margin-bottom: 16px;
    }

    .station-exception-table {
      width: 100%;
    }
  }
}
</style>
