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

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

import { useRouter } from 'vue-router';

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
// 导入API
import { assetList, deleteAsset, exportAsset } from '#/api/system/asset/asset';
import { commonDownloadExcel } from '#/utils/file/download';

import { queryFormSchema, tableColumns } from './archivesManage-data';
import ArchivesManageDrawerComp from './archivesManage-drawer.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
  fieldMappingTime: [
    [
      'productionDate',
      ['productionDateStart', 'productionDateEnd'],
      ['YYYY-MM-DD', 'YYYY-MM-DD'],
    ],
    ['useDate', ['useDateStart', 'useDateEnd'], ['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 assetList({
          ...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: 'system-assetManage-archivesManage-index',
};

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

const [ArchivesManageDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: ArchivesManageDrawerComp,
});

const router = useRouter();

// 新增资产档案
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑资产档案
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除资产档案
async function confirmEvent(row: any) {
  await deleteAsset([row.id.toString()]);
  await basicTableApi.reload();
}

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

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

// 导出资产档案数据
async function exportHandle() {
  await commonDownloadExcel(
    (params: any) => exportAsset(params),
    '资产档案数据',
    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="['system:assetManage:archivesManage:remove']"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['system:assetManage:archivesManage:add']"
          >
            新增资产档案
          </ElButton>
          <!-- <ElButton
            type="success"
            @click="exportHandle"
            v-access:code="['system:assetManage:archivesManage:export']"
          >
            导出数据
          </ElButton> -->
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="info"
            plain
            @click="
              () =>
                router.push(
                  `/system/assetManage/archivesManage/detail/${row.id}`,
                )
            "
          >
            详情
          </ElButton>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:assetManage:archivesManage:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:assetManage:archivesManage:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <ArchivesManageDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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