<script setup lang="ts">
import { Page } from '@vben/common-ui';
import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import { onMounted, ref, watch } from 'vue';
import { generateColumns, querySchema } from './config-data';
import { queryGasStationList } from '#/api/schedule/index';
//@ts-ignore
import type { VbenFormProps } from '@vben/common-ui';
import { queryrallotApilist } from '#/api/schedule/allot/index';
// const mockData = [
//   {
//     roleId: 2,
//     Name: '王保瑞',
//     Position: '当班经理',
//     roleSort: 1,
//     status: '0',
//     createTime: '2024-01-15 10:00:00',
//     remark: '当班',
//     isEditing: false,
//   },
//   {
//     roleId: 2,
//     Name: '王凯',
//     Position: '当班经理',
//     roleSort: 1,
//     status: '0',
//     createTime: '2024-01-15 10:00:00',
//     remark: '当班',
//     isEditing: false,
//   },
//   {
//     roleId: 2,
//     Name: '威威',
//     Position: '当班经理',
//     roleSort: 1,
//     status: '0',
//     createTime: '2024-01-15 10:00:00',
//     remark: '当班',
//     isEditing: false,
//   },
// ];

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',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

// 获取当前月份作为默认值
const now = new Date();
const defaultMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;

// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
    checkMethod: ({ row }) => row?.roleId !== 1,
  },
  columns: generateColumns(defaultMonth), // 直接使用生成的列配置
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await queryrallotApilist({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'roleId',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-role-index',
};
const [BasicTable, BasicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 在点击“搜索”提交时更新表格列（包装 reload），避免在切换月份时立即更新
if (BasicTableApi) {
  const _origReload = BasicTableApi.reload.bind(BasicTableApi);
  BasicTableApi.reload = async (params: Record<string, any> = {}) => {
    const month = params?.month;
    if (month) {
      BasicTableApi.setGridOptions({ columns: generateColumns(month) });
      // 等待下一次 microtask，让表格完成列更新（可选）
      await Promise.resolve();
    }
    return _origReload(params);
  };

  // 自定义重置逻辑：重置表单后把月份设为当前月份（避免清空日期选择器），然后触发查询
  BasicTableApi.setState((prev) => ({
    formOptions: {
      ...(prev.formOptions || {}),
      handleReset: async () => {
        try {
          // 先执行默认的重置行为
          if (BasicTableApi?.formApi) {
            await BasicTableApi.formApi.resetForm();
            // 将月份设为当前默认月份
            await BasicTableApi.formApi.setValues({ month: defaultMonth });
            const vals = await BasicTableApi.formApi.getValues();
            // 触发 reload，触发时会走我们包装后的 reload，从而更新列
            await BasicTableApi.reload(vals);
          }
        } catch (err) {
          // 忽略错误，防止阻塞 UI
          // console.error(err);
        }
      },
    },
  }));
}

// 在页面加载时设置默认月份
onMounted(() => {
  // 添加安全检查，确保BasicTableApi.formApi可用
  if (BasicTableApi?.formApi) {
    BasicTableApi.formApi.setValues({
      month: defaultMonth,
    });
  }
  // 请求油站列表，默认选择第一个油站（如果存在）
  (async () => {
    try {
      const res = await queryGasStationList({});
      console.log(res);
      
      const first = Array.isArray(res) ? res[0] : undefined;
      const firstId = first?.stationId;
      if (firstId && BasicTableApi?.formApi) {
        // 仅在未设置 stationId 时设置默认值
        const values = await BasicTableApi.formApi.getValues();
        if (!values?.stationId) {
          await BasicTableApi.formApi.setValues({ stationId: firstId });
        }
      }
    } catch (err) {
      // 忽略请求错误
    }
  })();
});
</script>
<template>
  <Page :auto-content-height="true">
    <BasicTable
      table-title="请把当天不执行任务的人员选【不带】，选择【不带】后系统自动取消该岗位任务频率为每天一次的任务。此操作仅用于配合任务处理，不代表真实的考勤。"
    >
      <template #action="{ row }">
        <el-button
          v-if="!row.isEditing"
          size="small"
          type="primary"
          plain
          @click="() => (row.isEditing = true)"
          >编辑</el-button
        >
        <template v-else>
          <el-button
            size="small"
            type="primary"
            @click="() => (row.isEditing = false)"
            >保存</el-button
          >
          <el-button size="small" plain @click="() => (row.isEditing = false)"
            >取消</el-button
          >
        </template>
      </template>
      <template #Select="{ row }">
        <el-select
          v-model="row.remark"
          v-if="row.isEditing"
          placeholder="Select"
        >
          <!-- <el-options
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="row.remark"
          /> -->
        </el-select>
        <span v-else>{{ row.remark }}</span>
      </template>
    </BasicTable>
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
