<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { EchartsUIType } from '@vben/plugins/echarts';
import { ref, onMounted } from 'vue';
import { Page } from '@vben/common-ui';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { queryFormSchema, tableColumns } from './taskProcessingDurationRecord-data';
import { ElTabs, ElTabPane, ElForm, ElFormItem, ElSelect, ElOption, ElDatePicker, ElButton, ElSpace } from 'element-plus';

// 类型定义
interface TaskRecord {
  id: number;
  taskName: string;
  station: string;
  executor: string;
  position: string;
  startProcessingTime: string;
  submitTime: string;
  duration: number;
  belowWarning: boolean;
}

// 响应式数据
const activeTab = ref('detail'); // 'detail' 或 'statistics'
const mockData = ref<TaskRecord[]>([]);

// 统计模块响应式数据
const statisticsForm = ref({
  station: '',
  startDate: '',
  endDate: '',
});

// 图表相关数据
const barChartRef = ref<EchartsUI>();
const { renderEcharts: renderBarEcharts } = useEcharts(barChartRef);

// 初始化模拟数据
function initMockData() {
  // 如果已经有数据，就不再生成
  if (mockData.value.length > 0) {
    return;
  }
  
  const tasks = [
    {
      id: 1,
      taskName: '班组日志',
      station: '龙飞加油站',
      executor: '王刚',
      position: '当班组长',
      startProcessingTime: '2025-11-14 01:24:10',
      submitTime: '2025-11-14 09:39:48',
      duration: 495,
      belowWarning: false,
    },
    {
      id: 2,
      taskName: '巡站自检',
      station: '龙飞加油站',
      executor: '安宁',
      position: '站长',
      startProcessingTime: '2025-11-14 09:35:11',
      submitTime: '2025-11-14 09:37:40',
      duration: 2,
      belowWarning: true,
    },
    {
      id: 3,
      taskName: '开站操作',
      station: '未来城加油站',
      executor: '汤钦钦',
      position: '当班组长',
      startProcessingTime: '2025-11-14 08:50:03',
      submitTime: '2025-11-14 08:50:03',
      duration: 0,
      belowWarning: false,
    },
    {
      id: 4,
      taskName: '班组日志',
      station: '未来城加油站',
      executor: '汤钦钦',
      position: '当班组长',
      startProcessingTime: '2025-11-14 08:12:58',
      submitTime: '2025-11-14 08:49:57',
      duration: 36,
      belowWarning: false,
    },
    {
      id: 5,
      taskName: '班前检查',
      station: '未来城加油站',
      executor: '张伯滕',
      position: '当班组长',
      startProcessingTime: '2025-11-14 08:07:01',
      submitTime: '2025-11-14 08:19:35',
      duration: 12,
      belowWarning: true,
    },
    {
      id: 6,
      taskName: '班前检查',
      station: '未来城加油站',
      executor: '汤钦钦',
      position: '当班组长',
      startProcessingTime: '2025-11-14 04:28:31',
      submitTime: '2025-11-14 08:12:53',
      duration: 224,
      belowWarning: false,
    },
    {
      id: 7,
      taskName: '班前检查',
      station: '龙飞加油站',
      executor: '王刚',
      position: '当班组长',
      startProcessingTime: '2025-11-14 01:24:24',
      submitTime: '2025-11-14 01:36:28',
      duration: 12,
      belowWarning: true,
    },
    {
      id: 8,
      taskName: '开站操作',
      station: '龙飞加油站',
      executor: '王刚',
      position: '当班组长',
      startProcessingTime: '2025-11-14 01:24:05',
      submitTime: '2025-11-14 01:24:05',
      duration: 0,
      belowWarning: false,
    },
    {
      id: 9,
      taskName: '开站操作',
      station: '龙飞加油站',
      executor: '王刚',
      position: '当班组长',
      startProcessingTime: '2025-11-14 01:12:38',
      submitTime: '2025-11-14 01:12:38',
      duration: 0,
      belowWarning: false,
    },
    {
      id: 10,
      taskName: '班组日志',
      station: '龙飞加油站',
      executor: '王刚',
      position: '当班组长',
      startProcessingTime: '2025-11-14 01:11:46',
      submitTime: '2025-11-14 01:12:28',
      duration: 0,
      belowWarning: false,
    },
  ]
  
  mockData.value = tasks;
}

// 初始化模拟数据
initMockData();

// 表单配置
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
};

// 表格配置
const gridOptions: VxeGridProps = {
  columns: tableColumns,
  size: 'medium',
  // 设置固定高度，避免自动高度导致的无限滚动问题
  height: 700,
  // 分页配置，确保每页只显示10条数据
  pagerConfig: {
    pageSize: 10,
    pageSizes: [10], // 只提供10条/页的选项
    layouts: ['PrevJump', 'PrevPage', 'Jump', 'PageCount', 'NextPage', 'NextJump', 'FullJump', 'Total'],
  },
  // 禁用无限滚动
  scrollY: {
    gt: -1, // 禁用虚拟滚动
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 模拟数据过滤和分页
        let filteredRows = [...mockData.value];

        // 根据搜索条件过滤
        if (formValues.station) {
          filteredRows = filteredRows.filter(row => row.station === formValues.station);
        }
        if (formValues.taskName) {
          filteredRows = filteredRows.filter(row => row.taskName.includes(formValues.taskName));
        }
        if (formValues.executor) {
          filteredRows = filteredRows.filter(row => row.executor.includes(formValues.executor));
        }
        if (formValues.position) {
          filteredRows = filteredRows.filter(row => row.position === formValues.position);
        }
        if (formValues.submitTime && formValues.submitTime.length === 2) {
          const [startTime, endTime] = formValues.submitTime;
          filteredRows = filteredRows.filter(
            row => row.submitTime >= startTime && row.submitTime <= endTime
          );
        }
        if (formValues.belowWarning !== undefined) {
          filteredRows = filteredRows.filter(row => row.belowWarning === formValues.belowWarning);
        }
        if (formValues.durationMin !== undefined) {
          filteredRows = filteredRows.filter(row => row.duration >= formValues.durationMin);
        }
        if (formValues.durationMax !== undefined) {
          filteredRows = filteredRows.filter(row => row.duration <= formValues.durationMax);
        }

        // 模拟分页
        const start = (page.currentPage - 1) * page.pageSize;
        const end = start + page.pageSize;
        const paginatedRows = filteredRows.slice(start, end);
        return {
          items: paginatedRows,
          total: filteredRows.length,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
    buttons: [
      {
        code: 'query',
        name: '查询',
        icon: 'Search',
        status: 'primary',
      },
      {
        code: 'reset',
        name: '重置',
        icon: 'Refresh',
      },
    ],
    onClick: (code: string) => {
      if (code === 'query') {
        // 执行查询操作
        basicTableApi.refresh();
      } else if (code === 'reset') {
        // 执行重置操作
        basicTableApi.resetForm();
      }
    },
  },
  id: 'system-checklis-taskProcessingDurationRecord-index',
};

// 创建表格实例
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});



// 导出数据
function handleExport() {
  // 这里可以添加实际的导出逻辑
  console.log('导出数据');
}

// 统计模块查询
function handleStatisticsQuery() {
  console.log('统计查询条件:', statisticsForm.value);
  // 这里可以添加实际的统计查询逻辑
  updateBarChart();
}

// 统计模块重置
function handleStatisticsReset() {
  statisticsForm.value = {
    station: '',
    startDate: '',
    endDate: '',
  };
}

// 更新柱状图 - 堆叠柱状图
function updateBarChart() {
  // 生成最近7天的日期
  const dates = [];
  const today = new Date();
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(today.getDate() - i);
    dates.push(date.toISOString().slice(0, 10));
  }
  
  // 模拟油站经理和非油站经理的数据
  const stationManagerData = dates.map(() => Math.floor(Math.random() * 100));
  const nonStationManagerData = dates.map(() => Math.floor(Math.random() * 200));
  
  renderBarEcharts({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: ['油站经理', '非油站经理'],
      top: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: dates,
        axisTick: {
          alignWithLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '时长(分钟)',
      },
    ],
    series: [
      {
        name: '油站经理',
        type: 'bar',
        stack: 'total',
        barWidth: '10%',
        data: stationManagerData,
        itemStyle: {
          color: '#5ab1ef',
        },
      },
      {
        name: '非油站经理',
        type: 'bar',
        stack: 'total',
        barWidth: '10%',
        data: nonStationManagerData,
        itemStyle: {
          color: '#faad14',
        },
      },
    ],
  });
}

// 组件初始化
onMounted(() => {
  updateBarChart();
});

</script>

<template>
  <Page :auto-content-height="true">
    <ElTabs v-model="activeTab" style="background-color: #fff;">
      <!-- 明细标签页 -->
      <ElTabPane label="明细" name="detail">
        <BasicTable table-title="任务处理时长记录列表">
          <template #toolbar-actions>
            <div class="text-sm text-gray-600 bg-gray-50 p-2 rounded-md ml-2">
              提示：导出必须选时间，并且开始时间和结束时间必须在同一个月
            </div>
          </template>
          <template #toolbar-tools>
            <ElSpace>
              <ElButton
                @click="handleExport"
                v-access:code="['system:taskProcessingDurationRecord:export']"
              >
                导出
              </ElButton>
            </ElSpace>
          </template>
        </BasicTable>
      </ElTabPane>
      
      <!-- 统计标签页 -->
      <ElTabPane label="统计" name="statistics">
        <div class="statistics-container">
          <!-- 统计搜索区域 -->
          <div class="statistics-search">
            <ElForm :model="statisticsForm" label-width="80px" inline>
              <ElFormItem label="油站">
                <ElSelect v-model="statisticsForm.station" placeholder="请选择油站" style="width: 200px;">
                  <ElOption label="全部" value="" />
                  <ElOption label="龙飞加油站" value="龙飞加油站" />
                  <ElOption label="未来城加油站" value="未来城加油站" />
                  <ElOption label="阳光加油站" value="阳光加油站" />
                  <ElOption label="星光加油站" value="星光加油站" />
                  <ElOption label="大地加油站" value="大地加油站" />
                </ElSelect>
              </ElFormItem>
              <ElFormItem label="开始日期">
                <ElDatePicker
                  v-model="statisticsForm.startDate"
                  type="date"
                  placeholder="请选择开始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 200px;"
                />
              </ElFormItem>
              <ElFormItem label="结束日期">
                <ElDatePicker
                  v-model="statisticsForm.endDate"
                  type="date"
                  placeholder="请选择结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 200px;"
                />
              </ElFormItem>
              <ElFormItem>
                <ElButton type="primary" @click="handleStatisticsQuery">查询</ElButton>
              </ElFormItem>
              <ElFormItem>
                <ElButton @click="handleStatisticsReset">重置</ElButton>
              </ElFormItem>
            </ElForm>
          </div>
          
          <!-- 提示文字 -->
          <div class="statistics-tip">
            <p class="text-sm text-gray-600">如果任务时长超过90分钟的，按90分钟统计，便于查看数据的合理性。</p>
          </div>
          
          <!-- 柱状图区域 -->
          <div class="bar-chart">
            <EchartsUI ref="barChartRef" style="width: 100%; height: 400px;" />
          </div>
        </div>
      </ElTabPane>
    </ElTabs>
  </Page>
</template>

<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}

.statistics-container {
  padding: 16px;
  
  .statistics-search {
    padding: 16px;
    margin-bottom: 16px;
    background-color: #fff;
    border-radius: 8px;
  }
  
  .statistics-tip {
    padding: 8px 16px;
    margin-bottom: 24px;
    background-color: #f5f7fa;
    border-left: 4px solid #e6a23c;
    border-radius: 4px;
  }
  
  .bar-chart {
    margin-top: 24px;
  }
}

// 调整标签页文字位置，使其向右移动
:deep(.el-tabs__item) {
  padding-left: 15px !important; // 增加左侧内边距，使文字向右移动
}
</style>
