<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { StaffingPlanDataApi } from '#/api/hr/staffingPlanData';

import { onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

import { Page, useVbenModal } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { ExportOutlined, SaveOutlined } from '@ant-design/icons-vue';
import { Button, message, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { apiExport, apiPage, apiUpdate } from '#/api/hr/staffingPlanData';
import { apiDetail as recordInfo } from '#/api/hr/staffingPlanRecords';
import { commonDownloadExcel } from '#/utils/file/download';

import { useColumns } from './data';
import staffingImportModal from './staffing-import-modal.vue';
// import Form from './form.vue';

const route = useRoute();
const recordId = route.params.recordId ? Number(route.params.recordId) : 0;
const initFlagRef = ref('N');
const staffingRecords = reactive({
  lastYearTitle: '',
  currentYearTitle: '',
  nextYearTitle: '',
});

watch(
  () => staffingRecords,
  () => {
    const cols = useColumns(staffingRecords) as any;
    gridApi.grid?.reloadColumn?.(cols);
  },
  { deep: true },
);

onMounted(async () => {
  const records = await recordInfo(recordId);
  initFlagRef.value = records.initFlag;
  staffingRecords.lastYearTitle = records.lastYearTitle;
  staffingRecords.currentYearTitle = records.currentYearTitle;
  staffingRecords.nextYearTitle = records.nextYearTitle;
});

/**
 * 导入
 */
const [StaffingImportModal, staffingImportModalApi] = useVbenModal({
  connectedComponent: staffingImportModal,
});
function handleImport() {
  staffingImportModalApi.setData({ recordId }).open();
}

// 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 [FormDrawer, formDrawerApi] = useVbenDrawer({
//   connectedComponent: Form,
// });

const [Grid, gridApi] = useVbenVxeGrid({
  // formOptions,
  gridOptions: {
    columns: useColumns(staffingRecords) as any,
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
      pageSize: 20,
    },
    editConfig: {
      mode: 'cell',
      trigger: 'click',
      // activeMethod({ row }) {
      //   return !row.summary;
      // },
      // beforeEditMethod({ row }) {
      //   // name 为 'x' 开头的列禁止编辑
      //   console.log('[row]', row);
      //   return true;
      // },
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues = {}) => {
          return await apiPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            recordId,
            ...formValues,
          });
        },
      },
    },
    border: true,
    columnConfig: {
      resizable: false,
    },
    showCustomHeader: true,
    spanMethod({ row, column }) {
      if (row.summary === 'Y') {
        const mergeFields = [
          'plate',
          'firstLevelDepartment',
          'secondLevelDepartment',
          'thirdLevelDepartment',
        ];
        if (mergeFields.includes(column.field as string)) {
          if (column.field === 'plate') {
            return { rowspan: 1, colspan: 4 } as any;
          }
          return { rowspan: 0, colspan: 0 } as any;
        }
      }
      return undefined as any;
    },
    rowClassName: ({ row }) => {
      if (row.summary === 'Y') {
        return row.plate === '片区合计'
          ? 'bg-red-500 text-white'
          : 'bg-red-100';
      }
      return '';
    },
    mergeHeaderCells: [
      { row: 0, col: 0, rowspan: 2, colspan: 1 },
      { row: 0, col: 1, rowspan: 2, colspan: 1 },
      { row: 0, col: 2, rowspan: 2, colspan: 1 },
      { row: 0, col: 3, rowspan: 2, colspan: 1 },
      { row: 0, col: 4, rowspan: 2, colspan: 1 },
      { row: 0, col: 5, rowspan: 2, colspan: 1 },
      { row: 0, col: 6, rowspan: 2, colspan: 1 },
      { row: 0, col: 7, rowspan: 2, colspan: 1 },
      { row: 0, col: 8, rowspan: 1, colspan: 48 },
      { row: 0, col: 56, rowspan: 2, colspan: 1 },
    ],
    rowConfig: {
      keyField: 'id',
      // 高亮当前行
      isCurrent: false,
    },
  } as VxeTableGridOptions,
});

// function onActionClick({
//   code,
//   row,
// }: OnActionClickParams<StaffingPlanDataApi.StaffingPlanData>) {
//   switch (code) {
//     case 'delete': {
//       onDelete(row);
//       break;
//     }
//     case 'edit': {
//       onEdit(row);
//       break;
//     }
//     default: {
//       break;
//     }
//   }
// }

async function onEdit() {
  const full =
    (await gridApi.grid?.getUpdateRecords()) as StaffingPlanDataApi.StaffingPlanData[];
  if (full && full.length > 0) {
    await apiUpdate(full);
    message.success('已保存编制计划');
  } else {
    message.error('无修改，请检查');
  }
}
function onRefresh() {
  gridApi.query();
  initFlagRef.value = 'Y';
}
// function onDelete(row: StaffingPlanDataApi.StaffingPlanData) {
//   const hideLoading = message.loading({
//     content: `正在删除${row.name}...`,
//     duration: 0,
//     key: 'action_process_msg',
//   });
//   apiDelete(row.id || 0)
//     .then(() => {
//       message.success({
//         content: `${row.name}删除成功`,
//         key: 'action_process_msg',
//       });
//       onRefresh();
//     })
//     .catch(() => {
//       hideLoading();
//     });
// }
function handleDownloadExcel() {
  commonDownloadExcel(apiExport, '编制规划记录明细', recordId);
}
</script>
<template>
  <Page auto-content-height>
    <!-- <FormDrawer @success="onRefresh" /> -->
    <StaffingImportModal @reload="onRefresh" />
    <Grid table-title="编制规划记录明细列表">
      <template #toolbar-tools>
        <Space>
          <Button
            type="primary"
            ghost
            v-access:code="['employee:staffingPlanData:edit']"
            @click="onEdit"
          >
            <template #icon>
              <SaveOutlined />
            </template>
            保存修改
          </Button>
          <Button
            type="primary"
            danger
            v-access:code="['employee:staffingPlanData:export']"
            @click="handleDownloadExcel"
          >
            <template #icon>
              <ExportOutlined />
            </template>
            导出
          </Button>
          <Button
            v-access:code="['employee:staffingPlanData:add']"
            v-if="initFlagRef === 'N'"
            type="primary"
            @click="handleImport"
          >
            <Plus class="size-5" />
            导入明细
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
