<template>
  <div class="info-box">
    <a-button @click="emit('returnPage')">返回</a-button>
    <span class="text-base font-bold pl-5">供货清单({{ name }})</span>
    <a-divider />
    <PageWrapper dense fixedHeight contentFullHeight>
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" @click="handleCreate"> {{ t('新增') }} </a-button>
          <a-button type="primary" @click="handleImport"> {{ t('导入') }} </a-button>
          <a-button type="primary" @click="handleExport"> {{ t('导出') }} </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'state'">
            <a-switch
              v-model:checked="record.state"
              :checkedValue="1"
              :unCheckedValue="0"
              disabled
            />
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-button type="link" class="actionTxt" @click="handleEdit(record)">编辑</a-button>
            <a-button type="link" class="actionTxt" @click="handleHistory(record)">
              历史价格对比
            </a-button>
            <a-button type="link" class="actionTxt" @click="handleDelete(record)">删除</a-button>
          </template>
        </template>
      </BasicTable>
    </PageWrapper>
  </div>
  <ListModal @register="registerModal" @success="reload" />
  <ImportModal
    @register="registerImportModal"
    importUrl="/caseErpSupplier/caseErpSupplyMaterial/import"
    @success="reload"
  />
  <HistoryPriceModal @register="registerHistoryModal" />
</template>
<script lang="ts" setup>
  import { createVNode } from 'vue';
  import { BasicTable, useTable, BasicColumn, FormSchema } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import {
    getSupplyMaterialPageList,
    deleteSupplyMaterial,
    exportInfo,
    downloadTemplate,
  } from '/@/api/erp/supplier/material';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { ImportModal } from '/@/components/Import';
  import { downloadByData } from '/@/utils/file/download';
  import ListModal from './ListModal.vue';
  import HistoryPriceModal from './HistoryPriceModal.vue';

  const props = defineProps({
    id: String,
    name: String,
  });
  const { t } = useI18n();

  const columns: BasicColumn[] = [
    {
      title: '物料编码',
      dataIndex: 'code',
    },
    {
      title: '物料名称',
      dataIndex: 'name',
    },
    {
      title: '规格型号',
      dataIndex: 'model',
    },
    {
      title: '当前采购单价(元)',
      dataIndex: 'price',
    },
    {
      title: '单位',
      dataIndex: 'unitName',
    },
    {
      title: '添加时间',
      dataIndex: 'createDate',
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 100,
    },
    {
      title: '操作人',
      dataIndex: 'createUserName',
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '物料名称',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入物料名称',
      },
    },
    {
      field: 'state',
      label: '状态',
      component: 'Select',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请选择状态',
        options: [
          { label: '启用', value: 1 },
          { label: '未启用', value: 0 },
        ],
      },
    },
    {
      field: 'createDate',
      label: '添加时间',
      component: 'RangePicker',
      colProps: { span: 8 },
      componentProps: {
        format: 'YYYY-MM-DD',
      },
    },
  ];
  const emit = defineEmits(['returnPage']);

  const { notification } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();
  const [registerHistoryModal, { openModal: openHistoryModal }] = useModal();

  const [registerTable, { reload }] = useTable({
    api: getSupplyMaterialPageList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [['createDate', ['startTime', 'endTime'], 'YYYY-MM-DD', true]],
    },
    beforeFetch: (paramas) => {
      return { ...paramas, supplierId: props.id };
    },
    useSearchForm: true,
    striped: false,
    actionColumn: {
      width: 180,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  const handleCreate = () => {
    openModal(true, {
      isUpdate: false,
      supplierId: props.id,
    });
  };

  const handleEdit = (record) => {
    openModal(true, {
      id: record.id,
      isUpdate: true,
      supplierId: props.id,
    });
  };

  const handleHistory = (record) => {
    openHistoryModal(true, {
      id: record.id,
    });
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteSupplyMaterial(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };
  const handleImport = () => {
    openImportModal(true, {
      title: t('快速导入'),
      api: downloadTemplate,
      templateTitle: '供货清单模板',
    });
  };
  const handleExport = async () => {
    const res = await exportInfo(props.id);
    downloadByData(
      res.data,
      '供货清单.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };
</script>
<style lang="less" scoped>
  .info-box {
    background-color: #fff;
    width: 100%;
    height: 100%;
    padding: 16px;
    margin-right: 8px;
  }

  .actionTxt {
    padding: 4px 2px;

    &:last-child {
      color: #f56c6c;
    }
  }
</style>
