<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

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

import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getManagementPlanList } from '#/api/archive/operationsManagement/operationsManagement';

import { columns, querySchema } from './config-data';

const showSearchForm = ref(true) as any;
const router = useRouter();
const route = useRoute();

// 表单字段到 API 字段的映射
function mapFormToApi(formValues: any, page: any) {
  const apiParams = {
    pageNum: page.currentPage,
    pageSize: page.pageSize,
    type: route.query.type || '',
    directoryType: route.query.directoryType || '',
  };

  // 处理调查开始时间
  if (formValues.surveyStartTime) {
    apiParams.processStartTime = formValues.surveyStartTime[0];
    apiParams.processEndTime = formValues.surveyStartTime[1];
  }

  // 其他字段
  Object.keys(formValues).forEach((key) => {
    if (key !== 'surveyStartTime') {
      apiParams[key] = formValues[key];
    }
  });

  return apiParams;
}

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 映射表单字段到 API 字段
        const apiParams = mapFormToApi(formValues, page);

        // 调用API
        const response = await getManagementPlanList(apiParams);

        // 映射 API 响应数据到页面显示字段
        const items = response.rows;

        return {
          items,
          total: response.total,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'management-plan-index',
};
const [BasicTable, BasicTableApi] = useVbenVxeGrid({
  showSearchForm,
  formOptions,
  gridOptions,
});
const handleTaskClick = (row: any) => {
  // 跳转到任务详情页面
  router.push(`/schedule/detail/${row.taskId}`);
};
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="管理计划列表">
      <template #action="{ row }">
        <el-button
          size="small"
          type="primary"
          plain
          @click="() => handleTaskClick(row)"
        >
          查看
        </el-button>
        <el-button size="small" type="primary" plain>打印清洁计划</el-button>
      </template>
    </BasicTable>
  </Page>
</template>

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