<script lang="ts" setup>
  import { Button } from 'ant-design-vue';
  import { columns, ModalPassRecord, OtaPermissionKey, searchFormSchema } from './config/config';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import PackageDetailModal from './components/PackageDetailModal.vue';
  import { useModal } from '/@/components/Modal';
  import { deleteOtaPackage, getOtaPackagesList } from '/@/api/ota';
  import { GetOtaPackagesParams, OtaRecordDatum } from '/@/api/ota/model/index';
  import PackagesDetailDrawer from './components/PackagesDetailDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDownload } from './hook/useDownload';
  import { computed } from 'vue';
  import { useSyncConfirm } from '/@/hooks/component/useSyncConfirm';
  import { Authority } from '/@/components/Authority';

  const [register, { reload, getSelectRowKeys, getRowSelection, setSelectedRowKeys }] = useTable({
    columns,
    title: '包仓库',
    bordered: true,
    api: async (params: GetOtaPackagesParams) => {
      const data = await getOtaPackagesList({
        ...params,
        page: params.page - 1,
        sortOrder: 'DESC',
        sortProperty: 'createdTime',
        textSearch: params.title,
      });
      return { ...data, page: params.page };
    },
    pagination: {
      showSizeChanger: true,
      pageSizeOptions: ['1', '2', '3', '4'],
    },
    fetchSetting: {
      totalField: 'totalElements',
      listField: 'data',
    },
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    rowKey: (record: OtaRecordDatum) => record.id.id,
    showIndexColumn: false,
    useSearchForm: true,
    showTableSetting: true,
    rowSelection: {
      type: 'checkbox',
    },
  });

  const { createConfirm, createMessage } = useMessage();

  const [registerModal, { openModal }] = useModal();

  const [registerDrawer, { openDrawer }] = useDrawer();

  const handleCreatePackage = () => {
    openModal(true, { isUpdate: false } as ModalPassRecord);
  };

  const handleOpenDetailDrawer = (record: OtaRecordDatum, isUpdate: boolean) => {
    openDrawer(true, { id: record.id.id, isUpdate });
  };

  const downloadFile = async (record: OtaRecordDatum) => {
    await useDownload(record);
  };

  const deletePackage = (record: OtaRecordDatum) => {
    createConfirm({
      iconType: 'warning',
      content: '是否确认删除操作？',
      onOk: async () => {
        try {
          await deleteOtaPackage(record.id.id);
          createMessage.success('删除成功');
          reload();
        } catch (error) {}
      },
    });
  };

  const canDelete = computed(() => {
    const rowSelection = getRowSelection();
    return !rowSelection.selectedRowKeys?.length;
  });

  const { createSyncConfirm } = useSyncConfirm();
  const handleBatchDelete = async () => {
    const rowKeys = getSelectRowKeys();
    try {
      await createSyncConfirm({ iconType: 'warning', content: '确认后所有选中的OTA升级将被删除' });
      for (const key of rowKeys) {
        await deleteOtaPackage(key);
      }
      createMessage.success('批量删除成功');
      setSelectedRowKeys([]);
      reload();
    } catch (error) {}
  };
</script>

<template>
  <PageWrapper dense contentFullHeight contentClass="flex flex-col">
    <BasicTable @register="register" @row-click="handleOpenDetailDrawer" class="ota-list">
      <template #toolbar>
        <Authority :value="OtaPermissionKey.CREATE">
          <Button @click="handleCreatePackage" type="primary">新增包</Button>
        </Authority>
        <Authority :value="OtaPermissionKey.DELETE">
          <Button @click="handleBatchDelete" :disabled="canDelete" type="primary" danger>
            批量删除
          </Button>
        </Authority>
      </template>
      <template #action="{ record }">
        <TableAction
          @click.stop
          :actions="[
            {
              label: '详情',
              icon: 'ant-design:eye-outlined',
              auth: OtaPermissionKey.DETAIL,
              onClick: handleOpenDetailDrawer.bind(null, record, false),
            },
            {
              label: '编辑',
              icon: 'clarity:note-edit-line',
              auth: OtaPermissionKey.UPDATE,
              onClick: handleOpenDetailDrawer.bind(null, record, true),
            },
          ]"
          :drop-down-actions="[
            {
              label: '下载',
              icon: 'ant-design:download-outlined',
              auth: OtaPermissionKey.DOWNLOAD,
              onClick: downloadFile.bind(null, record),
            },
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              color: 'error',
              auth: OtaPermissionKey.DELETE,
              popConfirm: {
                title: '是否确认删除',
                confirm: deletePackage.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <PackageDetailModal @register="registerModal" @update:list="reload" />
    <PackagesDetailDrawer @register="registerDrawer" @update:list="reload" />
  </PageWrapper>
</template>

<style scoped lang="less">
  .ota-list:deep(.ant-table-tbody > tr > td:last-of-type) {
    width: 100%;
    height: 100%;
    padding: 0 !important;
  }
</style>
