<template>
  <div v-if="columns?.length">
    <DynamicTable row-key="id"
      header-title="原材料出入库记录"
      title-tooltip="要创建入库记录，必须创建入库产品，产品所属公司。"
      :data-request="Api.materialsInOut.materialsInOutList"
      :columns="columns"
      bordered
      :scroll="{ x: 1920 }"
      size="small">
      <template #toolbar>
        <a-button type="primary"
          :disabled="!$auth('materials_inventory:history_in_out:create')"
          @click="openEditModal({})">
          新增
        </a-button> <a-button type="primary"
          @click="openExportModal">导出</a-button>
      </template>
    </DynamicTable>

  </div>
</template>

<script setup
  lang="tsx">
  import { useTable } from '@/components/core/dynamic-table';
  import {
    baseColumns,
    type TableColumnItem,
    type TableListItem,
  } from './columns';
  import Api from '@/api/';
  import { onMounted, ref, type FunctionalComponent } from 'vue';
  import { useFormModal, useModal } from '@/hooks/useModal';
  import { Button } from 'ant-design-vue';
  import { formSchemas } from './formSchemas';
  import AttachmentManage from '@/components/business/attachment-manage/index.vue';
  import AttachmentUpload from '@/components/business/attachment-upload/index.vue';
  import { useExportExcelModal, jsonToSheetXlsx } from '@/components/basic/excel';
  import { MaterialsInOutEnum } from '@/enums/materialsInventoryEnum';
  import { formatToDate } from '@/utils/dateUtil';
  defineOptions({
    name: 'MaterialsInOut',
  });

  const [DynamicTable, dynamicTableInstance] = useTable({ formProps: { autoSubmitOnEnter: true } });
  const [showModal] = useFormModal();
  const exportExcelModal = useExportExcelModal();
  const [fnModal] = useModal();
  const isUploadPopupVisiable = ref(false);

  let columns = ref<TableColumnItem[]>();
  onMounted(() => {
    columns.value = [
      ...baseColumns,
      {
        title: '附件',
        width: 40,
        maxWidth: 40,
        hideInSearch: true,
        fixed: 'right',
        dataIndex: 'files',
        customRender: ({ record }) => <FilesRender {...record} />,
      },
      {
        title: '操作',
        maxWidth: 80,
        width: 80,
        dataIndex: 'ACTION',
        hideInSearch: true,
        fixed: 'right',
        actions: ({ record }) => [
          {
            icon: 'ant-design:edit-outlined',
            tooltip: '编辑',
            auth: {
              perm: 'materials_inventory:history_in_out:update',
              effect: 'disable',
            },
            onClick: () => openEditModal(record),
          },
          {
            icon: 'ant-design:delete-outlined',
            color: 'red',
            tooltip: '删除此记录',
            auth: 'materials_inventory:history_in_out:delete',
            popConfirm: {
              title: '你确定要删除吗？',
              placement: 'left',
              onConfirm: () => delRowConfirm(record.id),
            },
          },
          {
            icon: 'ant-design:cloud-upload-outlined',
            tooltip: '上传附件',
            onClick: () => openAttachmentUploadModal(record),
          },
        ],
      },
    ];
  });

  const openExportModal = () => {
    exportExcelModal.openModal({
      formSchemas: [
        {
          field: 'time',
          component: 'RangePicker',
          label:'时间范围',
          rules: [{ required: true }],
        },
      ],
      onOk: ({ filename, bookType }) => {
        const tableData: TableListItem[] = dynamicTableInstance.tableData;
        let exportData: any[] = []
        for (let item of tableData) {
          exportData.push({
            projectName: item.project?.name,
            inOrOut: item.inOrOut === MaterialsInOutEnum.In ? '入库' : '出库',
            inventoryInOutNumber: item.inventoryInOutNumber,
            time: formatToDate(item.time),
            company: item.product?.company?.name,
            productName: item.product?.name,
            productSpecification: item.product?.productSpecification,
            unit: item.product?.unit?.label,
            quantity: item.quantity,
            unitPrice: parseFloat(item.unitPrice),
            amount: parseFloat(item.amount),
            agent: item.agent,
            issuanceNumber: item.issuanceNumber,
            remark: item.remark
          })
        }
        jsonToSheetXlsx({
          data: exportData,
          header: {
            inOrOut: '出/入库',
            inventoryInOutNumber: '出入库单号',
            time: '时间',
            projectName: '项目',
            company: '公司',
            productName: '产品名',
            productSpecification: "产品规格",
            unit: '单位',
            quantity: '数量',
            unitPrice: '单价',
            amount: '金额',
            agent: '经办人',
            issuanceNumber: '领料单号',
            remark: '备注'
          },
          filename,
          write2excelOpts: {
            bookType,
          },
          json2sheetOpts: {
            // 指定顺序
            header: [
              'inOrOut', 'inventoryInOutNumber', 'time', 'projectName', 'company', 'productName', 'productSpecification', 'unit', 'quantity',
              'unitPrice', 'amount', 'agent', 'issuanceNumber', 'remark'],
          },
        });
      },
    });
  };
  const openAttachmentUploadModal = async (record: TableListItem) => {
    isUploadPopupVisiable.value = true;
    fnModal.show({
      width: 800,
      title: `上传附件: ${record.id}`,
      content: () => {
        return (
          <AttachmentUpload
            onClose={handleUploadClose}
            bussinessModule="materialsInOut"
            bussinessRecordId={record.id}
            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.materialsInOut.materialsInOutUpdate(
      { 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) => {
          const params = {
            ...values,
            // signingDate: formatToDate(values.signingDate),
            // deliveryDeadline: formatToDate(values.deliveryDeadline),
          };
          if (record.id) {
            await Api.materialsInOut.materialsInOutUpdate(
              { id: record.id },
              params as API.MaterialsInOutUpdateDto,
            );
          } else {
            await Api.materialsInOut.materialsInOutCreate(params as API.MaterialsInOutDto);
          }
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: formSchemas(!!record.id),
      },
    });
    // 如果是编辑的话，需要获取详情
    if (record.id) {
      const info = await Api.materialsInOut.materialsInOutInfo({ id: record.id });
      formRef?.setFieldsValue({
        ...info,
      });
    }
  };
  const delRowConfirm = async (record) => {
    await Api.materialsInOut.materialsInOutDelete({ id: record });
    dynamicTableInstance?.reload();
  };

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

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

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