<script lang="ts" setup>
// 导入部分
import type { VxeGridProps } from '#/adapter/vxe-table';

import { onMounted, ref, watch } from 'vue';

import { Page } from '@vben/common-ui';

import {
  ElButton,
  ElOption,
  ElRadioButton,
  ElRadioGroup,
  ElSelect,
  ElSpace,
} from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';

// 类型定义
interface ReportTypeOption {
  label: string;
  value: 'evaluation' | 'full-indicator';
}

interface PeriodTypeOption {
  label: string;
  value: 'month' | 'week';
}

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

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

interface TaskReportData {
  id: number;
  station: string;
  manager: string;
  area: string;
  totalScore: number;
  completionRate: {
    ratio: string;
    score: number;
  };
  taskScore: {
    obtainedScore: number;
    score: number;
  };
  readRate: {
    ratio: string;
    score: number;
  };
  maxSameScoreRate: {
    ratio: string;
    score: number;
  };
  overdueCount: {
    count: number;
    score: number;
  };
}

// 全指标报表数据类型
interface FullIndicatorReportData {
  id: number;
  station: string;
  manager: string;
  area: string;
  // 任务数量
  taskQuantity: {
    authorizedRate: string;
    completedOnTime: number;
    completedOverdue: number;
    newTaskRate: string;
    notCompleted: number;
    overdueRate: string;
    totalCompletionRate: string;
    totalTasks: number;
  };
  // 任务质量
  taskQuality: {
    commentCount: number;
    ledgerAverage: number;
    taskScore: number;
  };
  // 授权
  authorization: {
    authorizationComments: number;
    authorizedCount: number;
    authorizedRate: string;
  };
  // 查阅
  查阅: {
    readableCount: number;
    readCount: number;
    readRate: string;
    查阅Count: number;
  };
  // 绩效
  performance: {
    maxSameScoreRate: string;
    performanceCommentRate: string;
  };
}

// 响应式数据
// 报表类型切换
const reportType = ref<'evaluation' | 'full-indicator'>('evaluation');
const reportTypeOptions: ReportTypeOption[] = [
  { label: '任务评估报表', value: 'evaluation' },
  { label: '任务全指标报表', value: 'full-indicator' },
];

// 时间类型切换
const periodType = ref<'month' | 'week'>('week');
const periodTypeOptions: PeriodTypeOption[] = [
  { label: '周', value: 'week' },
  { label: '月', value: 'month' },
];
const dateRange = ref<string[]>([]);

// 搜索条件
const selectedName = ref('');
const selectedStation = ref('');
const selectedArea = ref('');

// 下拉选项数据
const nameOptions: AreaOption[] = [
  { label: '李经理', value: '李经理' },
  { label: '王经理', value: '王经理' },
  { label: '张经理', value: '张经理' },
  { label: '刘经理', value: '刘经理' },
  { label: '陈经理', value: '陈经理' },
  { label: '李玫琳', value: '李玫琳' },
  { label: '安宁', value: '安宁' },
  { label: '张磊', value: '张磊' },
];

const stationOptions: StationOption[] = [
  { label: '机场油站', value: 'station1' },
  { label: '北京东加油站', value: 'station2' },
  { label: '北京西加油站', value: 'station3' },
  { label: '北京南加油站', value: 'station4' },
  { label: '北京北加油站', value: 'station5' },
];

const areaOptions: AreaOption[] = [
  { label: '默认片区', value: 'area1' },
  { label: '片区1', value: 'area2' },
  { label: '片区2', value: 'area3' },
  { label: '片区3', value: 'area4' },
];

// 辅助函数
// 格式化日期为中文格式（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 resetSearch = () => {
  selectedName.value = '';
  selectedStation.value = '';
  selectedArea.value = '';
  periodType.value = 'week';
  updateDefaultDateRange();
};

// 虚拟数据
const MOCK_DATA: TaskReportData[] = [
  {
    id: 1,
    station: '北京东加油站',
    manager: '李经理',
    area: '默认片区',
    totalScore: 44,
    completionRate: { ratio: '95.52%', score: 24 },
    taskScore: { score: 0, obtainedScore: 0 },
    readRate: { ratio: '0.00%', score: 0 },
    maxSameScoreRate: { ratio: '56.11%', score: 8 },
    overdueCount: { count: 3, score: 12 },
  },
  {
    id: 2,
    station: '北京西加油站',
    manager: '王经理',
    area: '默认片区',
    totalScore: 8,
    completionRate: { ratio: '77.14%', score: 0 },
    taskScore: { score: 0, obtainedScore: 0 },
    readRate: { ratio: '0.00%', score: 0 },
    maxSameScoreRate: { ratio: '25%', score: 8 },
    overdueCount: { count: 16, score: 0 },
  },
  {
    id: 3,
    station: '机场油站',
    manager: '张经理',
    area: '片区1',
    totalScore: 50,
    completionRate: { ratio: '100%', score: 25 },
    taskScore: { score: 0, obtainedScore: 0 },
    readRate: { ratio: '50.00%', score: 0 },
    maxSameScoreRate: { ratio: '33.33%', score: 10 },
    overdueCount: { count: 0, score: 15 },
  },
  {
    id: 4,
    station: '北京南加油站',
    manager: '刘经理',
    area: '片区2',
    totalScore: 38,
    completionRate: { ratio: '90.00%', score: 22 },
    taskScore: { score: 0, obtainedScore: 0 },
    readRate: { ratio: '33.33%', score: 0 },
    maxSameScoreRate: { ratio: '66.67%', score: 6 },
    overdueCount: { count: 2, score: 10 },
  },
  {
    id: 5,
    station: '北京北加油站',
    manager: '陈经理',
    area: '片区3',
    totalScore: 42,
    completionRate: { ratio: '93.33%', score: 23 },
    taskScore: { score: 0, obtainedScore: 0 },
    readRate: { ratio: '25.00%', score: 0 },
    maxSameScoreRate: { ratio: '40.00%', score: 8 },
    overdueCount: { count: 1, score: 11 },
  },
];

// 任务全指标报表虚拟数据
const FULL_INDICATOR_MOCK_DATA: FullIndicatorReportData[] = [
  {
    id: 1,
    station: '未来路加油',
    manager: '李玫琳',
    area: '默认片区',
    taskQuantity: {
      totalTasks: 52,
      completedOnTime: 48,
      completedOverdue: 3,
      notCompleted: 1,
      totalCompletionRate: '98.08%',
      overdueRate: '5.77%',
      authorizedRate: '2.5%',
      newTaskRate: '1.92%',
    },
    taskQuality: {
      commentCount: 12,
      taskScore: 4.5,
      ledgerAverage: 85.5,
    },
    authorization: {
      authorizedCount: 1,
      authorizedRate: '1.92%',
      authorizationComments: 0,
    },
    查阅: {
      readableCount: 51,
      readCount: 0,
      readRate: '0.00%',
      查阅Count: 2,
    },
    performance: {
      maxSameScoreRate: '25%',
      performanceCommentRate: '16.67%',
    },
  },
  {
    id: 2,
    station: '龙飞虎加',
    manager: '安宁',
    area: '默认片区',
    taskQuantity: {
      totalTasks: 67,
      completedOnTime: 58,
      completedOverdue: 8,
      notCompleted: 1,
      totalCompletionRate: '98.51%',
      overdueRate: '11.94%',
      authorizedRate: '33.33%',
      newTaskRate: '1.49%',
    },
    taskQuality: {
      commentCount: 8,
      taskScore: 4.2,
      ledgerAverage: 88.2,
    },
    authorization: {
      authorizedCount: 11,
      authorizedRate: '16.42%',
      authorizationComments: 3,
    },
    查阅: {
      readableCount: 80,
      readCount: 0,
      readRate: '0.00%',
      查阅Count: 1,
    },
    performance: {
      maxSameScoreRate: '36.11%',
      performanceCommentRate: '8.33%',
    },
  },
  {
    id: 3,
    station: '法站',
    manager: '张磊',
    area: '默认片区',
    taskQuantity: {
      totalTasks: 125,
      completedOnTime: 112,
      completedOverdue: 12,
      notCompleted: 1,
      totalCompletionRate: '99.20%',
      overdueRate: '9.60%',
      authorizedRate: '16.44%',
      newTaskRate: '0.80%',
    },
    taskQuality: {
      commentCount: 15,
      taskScore: 4.7,
      ledgerAverage: 90.5,
    },
    authorization: {
      authorizedCount: 12,
      authorizedRate: '9.60%',
      authorizationComments: 5,
    },
    查阅: {
      readableCount: 131,
      readCount: 0,
      readRate: '0.00%',
      查阅Count: 3,
    },
    performance: {
      maxSameScoreRate: '31.67%',
      performanceCommentRate: '11.67%',
    },
  },
  {
    id: 4,
    station: '机场油站',
    manager: '王经理',
    area: '片区1',
    taskQuantity: {
      totalTasks: 89,
      completedOnTime: 78,
      completedOverdue: 10,
      notCompleted: 1,
      totalCompletionRate: '98.88%',
      overdueRate: '11.24%',
      authorizedRate: '22.47%',
      newTaskRate: '1.12%',
    },
    taskQuality: {
      commentCount: 20,
      taskScore: 4.3,
      ledgerAverage: 87.8,
    },
    authorization: {
      authorizedCount: 10,
      authorizedRate: '11.24%',
      authorizationComments: 4,
    },
    查阅: {
      readableCount: 95,
      readCount: 5,
      readRate: '5.26%',
      查阅Count: 2,
    },
    performance: {
      maxSameScoreRate: '38.33%',
      performanceCommentRate: '13.33%',
    },
  },
  {
    id: 5,
    station: '北京南加油',
    manager: '刘经理',
    area: '片区2',
    taskQuantity: {
      totalTasks: 45,
      completedOnTime: 39,
      completedOverdue: 5,
      notCompleted: 1,
      totalCompletionRate: '97.78%',
      overdueRate: '11.11%',
      authorizedRate: '15.56%',
      newTaskRate: '2.22%',
    },
    taskQuality: {
      commentCount: 7,
      taskScore: 4.1,
      ledgerAverage: 84.2,
    },
    authorization: {
      authorizedCount: 6,
      authorizedRate: '13.33%',
      authorizationComments: 2,
    },
    查阅: {
      readableCount: 48,
      readCount: 3,
      readRate: '6.25%',
      查阅Count: 1,
    },
    performance: {
      maxSameScoreRate: '28.33%',
      performanceCommentRate: '10.00%',
    },
  },
];

// 任务评估报表表格配置
const taskReportColumns: VxeGridProps['columns'] = [
  { title: '姓名', field: 'manager', minWidth: 120, align: 'center' },
  { title: '油站', field: 'station', minWidth: 150, align: 'center' },
  { title: '片区', field: 'area', minWidth: 120, align: 'center' },
  { title: '总分', field: 'totalScore', minWidth: 80, align: 'center' },
  {
    title: '完成率',
    minWidth: 150,
    align: 'center',
    children: [
      {
        title: '比例',
        field: 'completionRate.ratio',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '得分',
        field: 'completionRate.score',
        minWidth: 70,
        align: 'center',
      },
    ],
  },
  {
    title: '任务得分',
    minWidth: 150,
    align: 'center',
    children: [
      {
        title: '分数',
        field: 'taskScore.score',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '得分',
        field: 'taskScore.obtainedScore',
        minWidth: 70,
        align: 'center',
      },
    ],
  },
  {
    title: '已阅比例',
    minWidth: 150,
    align: 'center',
    children: [
      { title: '比例', field: 'readRate.ratio', minWidth: 80, align: 'center' },
      { title: '得分', field: 'readRate.score', minWidth: 70, align: 'center' },
    ],
  },
  {
    title: '最多相同分数率',
    minWidth: 180,
    align: 'center',
    children: [
      {
        title: '比例',
        field: 'maxSameScoreRate.ratio',
        minWidth: 100,
        align: 'center',
      },
      {
        title: '得分',
        field: 'maxSameScoreRate.score',
        minWidth: 80,
        align: 'center',
      },
    ],
  },
  {
    title: '逾期未完成数',
    minWidth: 180,
    align: 'center',
    children: [
      {
        title: '过期数量',
        field: 'overdueCount.count',
        minWidth: 100,
        align: 'center',
      },
      {
        title: '过期分数',
        field: 'overdueCount.score',
        minWidth: 80,
        align: 'center',
      },
    ],
  },
];

const taskReportGridOptions: VxeGridProps = {
  columns: taskReportColumns,
  size: 'medium',
  height: '500px',
  useSearchForm: false,
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    ajax: {
      query: async () => {
        return { items: MOCK_DATA, total: MOCK_DATA.length };
      },
    },
  },
  rowConfig: { keyField: 'id' },
  toolbarConfig: {},
  id: 'task-report-table',
};

// 任务全指标报表表格配置
const fullIndicatorReportColumns: VxeGridProps['columns'] = [
  {
    title: '姓名',
    field: 'manager',
    minWidth: 120,
    align: 'center',
    fixed: 'left',
  },
  {
    title: '油站',
    field: 'station',
    minWidth: 150,
    align: 'center',
    fixed: 'left',
  },
  {
    title: '片区',
    field: 'area',
    minWidth: 120,
    align: 'center',
    fixed: 'left',
  },
  {
    title: '任务数量',
    minWidth: 400,
    align: 'center',
    children: [
      {
        title: '任务数',
        field: 'taskQuantity.totalTasks',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '按时完成',
        field: 'taskQuantity.completedOnTime',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '逾期完成',
        field: 'taskQuantity.completedOverdue',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '过期未完成',
        field: 'taskQuantity.notCompleted',
        minWidth: 90,
        align: 'center',
      },
      {
        title: '总完成率',
        field: 'taskQuantity.totalCompletionRate',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '逾期率',
        field: 'taskQuantity.overdueRate',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '被授权率',
        field: 'taskQuantity.authorizedRate',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '新增任务率',
        field: 'taskQuantity.newTaskRate',
        minWidth: 80,
        align: 'center',
      },
    ],
  },
  {
    title: '任务质量',
    minWidth: 250,
    align: 'center',
    children: [
      {
        title: '收到的点评数',
        field: 'taskQuality.commentCount',
        minWidth: 100,
        align: 'center',
      },
      {
        title: '任务得分',
        field: 'taskQuality.taskScore',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '台账平均数',
        field: 'taskQuality.ledgerAverage',
        minWidth: 80,
        align: 'center',
      },
    ],
  },
  {
    title: '授权',
    minWidth: 250,
    align: 'center',
    children: [
      {
        title: '已授权',
        field: 'authorization.authorizedCount',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '已授权率',
        field: 'authorization.authorizedRate',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '授权点评',
        field: 'authorization.authorizationComments',
        minWidth: 80,
        align: 'center',
      },
    ],
  },
  {
    title: '查阅',
    minWidth: 300,
    align: 'center',
    children: [
      {
        title: '可阅读',
        field: '查阅.readableCount',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '已阅读',
        field: '查阅.readCount',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '已阅读率',
        field: '查阅.readRate',
        minWidth: 80,
        align: 'center',
      },
      {
        title: '被查阅数',
        field: '查阅.查阅Count',
        minWidth: 80,
        align: 'center',
      },
    ],
  },
  {
    title: '绩效',
    minWidth: 250,
    align: 'center',
    children: [
      {
        title: '最多相同分数率',
        field: 'performance.maxSameScoreRate',
        minWidth: 100,
        align: 'center',
      },
      {
        title: '绩效评语率',
        field: 'performance.performanceCommentRate',
        minWidth: 100,
        align: 'center',
      },
    ],
  },
];

const fullIndicatorReportGridOptions: VxeGridProps = {
  columns: fullIndicatorReportColumns,
  size: 'medium',
  height: '500px',
  useSearchForm: false,
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    ajax: {
      query: async () => {
        return {
          items: FULL_INDICATOR_MOCK_DATA,
          total: FULL_INDICATOR_MOCK_DATA.length,
        };
      },
    },
  },
  rowConfig: { keyField: 'id' },
  toolbarConfig: {},
  id: 'full-indicator-report-table',
  scrollX: true,
  scrollY: true,
};

// 创建表格实例
const [TaskReportTable] = useVbenVxeGrid({
  gridOptions: taskReportGridOptions,
});
const [FullIndicatorReportTable] = useVbenVxeGrid({
  gridOptions: fullIndicatorReportGridOptions,
});

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

// 重置按钮点击事件
const handleReset = () => {
  resetSearch();
  console.log('重置搜索条件');
};

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

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

// 组件初始化 - 设置默认时间范围
onMounted(() => {
  updateDefaultDateRange();
});
</script>

<template>
  <Page :auto-content-height="true">
    <div class="task-report-container">
      <!-- 报表类型切换 -->
      <div class="report-type-container">
        <ElRadioGroup v-model="reportType" size="large">
          <ElRadioButton
            v-for="option in reportTypeOptions"
            :key="option.value"
            :label="option.value"
          >
            {{ option.label }}
          </ElRadioButton>
        </ElRadioGroup>
      </div>

      <!-- 搜索区域 -->
      <div class="search-container">
        <ElSpace>
          <div class="search-item">
            <label>姓名：</label>
            <ElSelect
              v-model="selectedName"
              placeholder="请选择姓名"
              style="width: 180px"
            >
              <ElOption
                v-for="option in nameOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </ElSelect>
          </div>
          <div class="search-item">
            <label>油站：</label>
            <ElSelect
              v-model="selectedStation"
              placeholder="请选择油站"
              style="width: 180px"
            >
              <ElOption
                v-for="option in stationOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </ElSelect>
          </div>
          <div class="search-item">
            <label>片区：</label>
            <ElSelect
              v-model="selectedArea"
              placeholder="请选择片区"
              style="width: 180px"
            >
              <ElOption
                v-for="option in areaOptions"
                :key="option.value"
                :label="option.label"
                :value="option.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>
          <ElButton @click="handleReset">重置</ElButton>
          <ElButton @click="handleExport">导出</ElButton>
        </ElSpace>
      </div>

      <!-- 报表提示语 -->
      <div class="notice-container">
        <p>数据周期：次周周三早9点自动生成，按周切片，次周日早9点自动生成。</p>
      </div>

      <!-- 报表数据表格 -->
      <div class="table-container">
        <TaskReportTable v-if="reportType === 'evaluation'" />
        <FullIndicatorReportTable v-else />
      </div>
    </div>
  </Page>
</template>

<style scoped lang="scss">
.task-report-container {
  min-height: calc(100vh - 120px);
  padding: 16px;
  background-color: #fff;

  .report-type-container {
    margin-bottom: 16px;
  }

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

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

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

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

  .notice-container {
    padding: 12px 16px;
    margin-bottom: 16px;
    font-size: 14px;
    color: #606266;
    background-color: #f0f5ff;
    border-left: 4px solid #409eff;
    border-radius: 4px;

    p {
      margin: 0;
    }
  }

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