<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <BasicTableErp @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> {{ 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 == 'purchaseDetail'">
          <a-dropdown v-if="record.purchaseDetail">
            <span>
              {{ record.purchaseDetail.split(',')[0]?.split(':')[0] }}
              <DownOutlined />
            </span>
            <template #overlay>
              <a-menu>
                <a-menu-item v-for="(item, index) in record.purchaseDetail.split(',')" :key="index">
                  <a href="javascript:;">{{ item }}</a>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-if="['inStoreState', 'ticketState', 'payState'].includes(column.dataIndex)">
          <Icon icon="ant-design:check-circle-filled" :size="20" v-if="record[column.dataIndex]" />
          <Icon icon="ant-design:exclamation-circle-filled" color="#FF1A2E" :size="20" v-else />
        </template>
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:eye-outlined',
                onClick: handleView.bind(null, record),
              },
              {
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTableErp>
    <OrderModal @register="registerModal" @success="reload" />
    <OrderInfoModal @register="registerInfoModal" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode } from 'vue';
  import { useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';
  import BasicTableErp from '/@/components/Table/src/BasicTableErp.vue';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { getPurchasePageList, deletePurchase, exportInfo } from '/@/api/erp/purchase/order';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined, DownOutlined } from '@ant-design/icons-vue';
  import Icon from '/@/components/Icon/index';
  import { downloadByData } from '/@/utils/file/download';
  import OrderModal from './components/OrderModal.vue';
  import OrderInfoModal from './components/OrderInfoModal.vue';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '采购编码',
      dataIndex: 'purchaseNumber',
      width: 100,
    },
    {
      title: '采购订单名称',
      dataIndex: 'theme',
      width: 100,
    },
    {
      title: '供应商',
      dataIndex: 'supplierName',
      width: 100,
    },
    {
      title: '采购日期',
      dataIndex: 'purchaseDate',
      width: 100,
    },
    {
      title: '采购部门',
      dataIndex: 'purchaseDeptName',
      width: 100,
    },
    {
      title: '采购人员',
      dataIndex: 'purchasePersonName',
      width: 100,
    },
    {
      title: '采购物品',
      dataIndex: 'purchaseDetail',
      width: 100,
    },
    {
      title: '总金额',
      dataIndex: 'amountSum',
      width: 100,
    },
    {
      title: '已收金额',
      dataIndex: 'alreadyAmount',
      width: 100,
    },
    {
      title: '已到票金额',
      dataIndex: 'alreadyTicket',
      width: 100,
    },
    {
      title: '入库',
      dataIndex: 'inStoreState',
      width: 70,
    },
    {
      title: '到票',
      dataIndex: 'ticketState',
      width: 70,
    },
    {
      title: '付款',
      dataIndex: 'payState',
      width: 70,
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'theme',
      label: '订单名称',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入订单名称',
      },
    },
  ];

  const { notification } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerInfoModal, { openModal: openInfoModal }] = useModal();

  const customRow = (record) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...getSelectRowKeys()];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        setSelectedRowKeys(selectedRowKeys);
      },
    };
  };

  const [registerTable, { reload, setSelectedRowKeys, getSelectRowKeys }] = useTable({
    title: '采购订单',
    api: getPurchasePageList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 120,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      type: 'checkbox',
    },
    customRow,
  });

  const handleCreate = () => {
    openModal(true, {
      isUpdate: false,
    });
  };

  const handleView = (record) => {
    openInfoModal(true, {
      id: record.id,
    });
  };

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

  const handleDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deletePurchase(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };

  const handleExport = async () => {
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要导出的数据',
      });
      return false;
    }
    const res = await exportInfo(getSelectRowKeys());
    downloadByData(
      res.data,
      '采购订单.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };
</script>
