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

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

import { onMounted, ref } from 'vue';

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

import { ElMessageBox } from 'element-plus';
import { useAccess } from '@vben/access';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
// 将模拟API替换为实际API
import {
  deleteIdPhoto,
  exportIdPhoto,
  idPhotoList,
} from '#/api/oilstation/idphoto/idphoto';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { queryFormSchema, tableColumns } from './idphoto-data';
import IdPhotoDrawerComp from './idphoto-drawer.vue';

// 字典标识常量
const DICT_KEYS = {
  // 驾照字典标识
  ID_PAPERS_NAME: 'id_papers_name',
  // 机构字典标识
  ID_PAPERS_ORGANIZATION: 'id_papers_organization',
  // 存放处字典标识
  ID_PAPERS_STORAGE: 'id_papers_storage',
  // 状态字典标识
  STATUS: 'status',
};

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
  fieldMappingTime: [
    [
      'validDate',
      ['validStartTime', 'validEndTime'],
      ['YYYY-MM-DD', 'YYYY-MM-DD'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await idPhotoList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'oilstation-idphoto-index',
};

const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [IdPhotoDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: IdPhotoDrawerComp,
});

// 字典数据引用
const certificateTypes = ref<any[]>([]);
const organizationTypes = ref<any[]>([]);
const storageLocations = ref<any[]>([]);
const statusOptions = ref<any[]>([]);
const { hasAccessByCodes } = useAccess();

// 加载字典数据
onMounted(() => {
  // 获取各字典数据
  certificateTypes.value = getDictOptions(DICT_KEYS.ID_PAPERS_NAME);
  organizationTypes.value = getDictOptions(DICT_KEYS.ID_PAPERS_ORGANIZATION);
  storageLocations.value = getDictOptions(DICT_KEYS.ID_PAPERS_STORAGE);
  statusOptions.value = getDictOptions(DICT_KEYS.STATUS) || [
    { label: '启用', value: 'enabled' },
    { label: '禁用', value: 'disabled' },
  ];

});

// 新增证照
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑证照
function handleEdit(row: any) {
  console.log(drawerApi);
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除证照
async function confirmEvent(row: any) {
  await deleteIdPhoto([row.id]);
  await basicTableApi.reload();
}

// 批量删除证照
function deleteHandle() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const ids = checkRecords.map((item: any) => item.id);
  if (ids.length <= 0) {
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteIdPhoto(ids);
    await basicTableApi.reload();
  });
}

// 导出证照数据
async function exportHandle() {
  await commonDownloadExcel(
    exportIdPhoto,
    '证照档案数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="证照档案列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
            v-access:code="['oilstation:idphoto:remove']"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
             v-access:code="['oilstation:idphoto:add']"
            
          >
            新增证照
          </ElButton>
        </ElSpace>
      </template>
      <template #organizationType="{ row }">
        <ElTag v-if="row.organizationType">
          {{
            dictOrganizationRef.find((item) => item.value === row.orgTypeCode)
              ?.label || row.orgTypeCode
          }}
        </ElTag>
      </template>
      <template #storageLocation="{ row }">
        <ElTag v-if="row.storageLocation">
          {{
            dictStorageRef.find(
              (item) => item.value === row.storageLocationCode,
            )?.label || row.storageLocationCode
          }}
        </ElTag>
      </template>
      <template #status="{ row }">
        <ElTag
          v-if="row.status"
          :type="row.statusCode === 'enabled' ? 'success' : 'danger'"
        >
          {{
            dictStatusRef.find((item) => item.value === row.statusCode)
              ?.label || row.statusCode
          }}
        </ElTag>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['oilstation:idphoto:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['oilstation:idphoto:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <IdPhotoDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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