<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <BasicTable @register="registerTable" :isMenuTable="true">
      <template #toolbar>
        <a-button type="primary" v-auth="'salesOrder:add'" @click="handleCreate">
          {{ t('新增') }}
        </a-button>
        <a-button type="primary" v-auth="'salesOrder:export'" @click="handleExport" class="ml-4">
          {{ 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 == 'saleDetail'">
          <a-dropdown v-if="record.saleDetail">
            <span>
              {{ record.saleDetail.split(',')[0]?.split(':')[0] }}
              <DownOutlined />
            </span>
            <template #overlay>
              <a-menu>
                <a-menu-item v-for="(item, index) in record.saleDetail.split(',')" :key="index">
                  <a href="javascript:;">{{ item }}</a>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-if="['outStoreState', '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="[
              {
                label: '查看',
                auth: 'salesOrder:view',
                onClick: handleView.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'salesOrder:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'salesOrder:delete',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <OrderModal @register="registerModal" @success="reload" />
    <OrderInfoModal @register="registerInfoModal" @success="reload" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { getSalePageList, deleteSale, exportInfo } from '/@/api/erp/sale/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';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '销售单号',
      dataIndex: 'saleNumber',
      width: 100,
      resizable: true,
    },
    {
      title: '销售订单主题',
      dataIndex: 'theme',
      width: 100,
      resizable: true,
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      width: 100,
      resizable: true,
    },
    {
      title: '销售日期',
      dataIndex: 'saleDate',
      width: 100,
      resizable: true,
    },
    {
      title: '产品概要',
      dataIndex: 'saleDetail',
      resizable: true,
    },
    {
      title: '总金额',
      dataIndex: 'amountSum',
      width: 100,
      resizable: true,
    },
    {
      title: '优惠后金额',
      dataIndex: 'discount',
      width: 100,
      resizable: true,
    },
    {
      title: '已收金额',
      dataIndex: 'alreadyAmount',
      width: 100,
      resizable: true,
    },
    {
      title: '已到票金额',
      dataIndex: 'alreadyTicket',
      width: 100,
      resizable: true,
    },
    {
      title: '出库',
      dataIndex: 'outStoreState',
      width: 80,
      resizable: true,
    },
    {
      title: '开票',
      dataIndex: 'ticketState',
      width: 80,
      resizable: true,
    },
    {
      title: '收款',
      dataIndex: 'payState',
      width: 80,
      resizable: true,
    },
  ];

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

  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  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);
      },
      ondblclick: () => {
        if (hasPermission('salesOrder:edit')) {
          handleEdit(record);
        }
      },
    };
  };

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

  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 deleteSale(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>
