<template>
  <div v-if="columns?.length">
    <DynamicTable
      row-key="id"
      header-title="车辆使用管理"
      title-tooltip=""
      :data-request="Api.vehicleUsage.vehicleUsageList"
      :columns="columns"
      :exportFileName="'车辆使用'"
      bordered
      :scroll="{ x: 1920 }"
      size="small"
    >
      <template #toolbar>
        <a-button
          type="primary"
          :disabled="!$auth('app:vehicle_usage:create')"
          @click="openEditModal({})"
        >
          新增
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script setup lang="tsx">
  import { useTable, type LoadDataParams, type TableColumn } from '@/components/core/dynamic-table';
  import { baseColumns, type TableColumnItem, type TableListItem } from './columns';
  import Api from '@/api/';
  import { useFormModal, useModal } from '@/hooks/useModal';
  import { formSchemas } from './formSchemas';
  import { Button } from 'ant-design-vue';
  import AttachmentManage from '@/components/business/attachment-manage/index.vue';
  import AttachmentUpload from '@/components/business/attachment-upload/index.vue';
  import { ref, onMounted, type FunctionalComponent } from 'vue';
  import { useDictStore } from '@/store/modules/dict';
  defineOptions({
    name: 'VehicleUsage',
  });
  const [DynamicTable, dynamicTableInstance] = useTable();
  const [showModal] = useFormModal();
  const [fnModal] = useModal();
  const isUploadPopupVisiable = ref(false);
  let columns = ref<TableColumnItem[]>();
  onMounted(() => {
    columns.value = [
      ...baseColumns,
      {
        title: '附件',
        width: 50,
        maxWidth: 50,
        fixed: 'right',
        hideInSearch: true,
        hideInExport: true,
        dataIndex: 'files',
        customRender: ({ record }) => <FilesRender {...record} />,
      },
      {
        title: '操作',
        maxWidth: 150,
        width: 150,
        minWidth: 150,
        fixed: 'right',
        dataIndex: 'ACTION',
        hideInSearch: true,
        actions: ({ record }) => [
          {
            icon: 'ant-design:edit-outlined',
            tooltip: '编辑',
            auth: {
              perm: 'app:vehicle_usage:update',
              effect: 'disable',
            },
            onClick: () => openEditModal(record),
          },
          {
            icon: 'ant-design:delete-outlined',
            color: 'red',
            tooltip: '删除此车辆使用',
            auth: 'app:vehicle_usage:delete',
            popConfirm: {
              title: '你确定要删除吗？',
              placement: 'left',
              onConfirm: () => delRowConfirm(record.id),
            },
          },
          {
            icon: 'ant-design:cloud-upload-outlined',
            tooltip: '上传附件',
            onClick: () => openAttachmentUploadModal(record),
          },
        ],
      },
    ];
  });

  const openAttachmentUploadModal = async (record: TableListItem) => {
    isUploadPopupVisiable.value = true;
    fnModal.show({
      width: 800,
      title: `车辆使用: ${record.vehicleId}`,
      content: () => {
        return (
          <AttachmentUpload
            bussinessModule="vehicleUsage"
            bussinessRecordId={record.id}
            onClose={handleUploadClose}
            afterUploadCallback={(files) => {
              afterUploadCallback(files, record.id);
            }}
          ></AttachmentUpload>
        );
      },
      destroyOnClose: true,
      open: isUploadPopupVisiable.value,
      footer: null,
    });
  };
  const handleUploadClose = (hasSuccess: boolean) => {
    fnModal.hide();
    isUploadPopupVisiable.value = false;
  };
  const afterUploadCallback = async (
    files: { filename: { path: string; id: number } }[],
    id: number,
  ) => {
    await Api.vehicleUsage.vehicleUsageUpdate(
      { id },
      { fileIds: files.map((item) => item.filename.id) },
    );
    dynamicTableInstance?.reload();
  };

  /**
   * @description 打开新增/编辑弹窗
   */
  const openEditModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}车辆使用`,
        width: '50%',
        onFinish: async (values) => {
          if (record.id) {
            await Api.vehicleUsage.vehicleUsageUpdate({ id: record.id }, values);
          } else {
            await Api.vehicleUsage.vehicleUsageCreate(values);
          }
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: formSchemas(!!record.id),
      },
    });

    // 如果是编辑的话，需要获取角色详情
    if (record.id) {
      const info = await Api.vehicleUsage.vehicleUsageInfo({ id: record.id });
      formRef?.setFieldsValue({
        ...info,
      });
    }
  };
  const delRowConfirm = async (record) => {
    await Api.vehicleUsage.vehicleUsageDelete({ id: record });
    dynamicTableInstance?.reload();
  };

  const FilesRender: FunctionalComponent<TableListItem> = (vehicleUsage: TableListItem) => {
    const [fnModal] = useModal();
    return (
      <Button
        type="link"
        onClick={() => {
          openFilesManageModal(fnModal, vehicleUsage);
        }}
      >
        {vehicleUsage.files?.length || 0}
      </Button>
    );
  };

  const openFilesManageModal = (fnModal, vehicleUsage: TableListItem) => {
    const fileIds = vehicleUsage.files?.map((item) => item.id) || [];
    fnModal.show({
      width: 1200,
      title: `附件管理`,
      content: () => {
        return (
          <AttachmentManage
            fileIds={fileIds}
            onDelete={(unlinkIds) => unlinkAttachments(vehicleUsage.id, unlinkIds)}
          ></AttachmentManage>
        );
      },
      destroyOnClose: true,
      footer: null,
    });
  };
  const unlinkAttachments = async (id: number, unlinkIds: number[]) => {
    await Api.vehicleUsage.unlinkAttachments({ id }, { fileIds: unlinkIds });
    dynamicTableInstance?.reload();
  };
</script>

<style lang="less" scoped></style>
