<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="查看订单详情">
    <div class="info-box">
      <a-card :bordered="false">
        <div class="title-name">{{ baseInfo?.theme }}</div>
        <div class="title-info">
          <span>创建人：{{ baseInfo?.createUserName }}</span>
          <span>创建时间：{{ baseInfo?.createDate }}</span>
          <span>最后修改人：{{ baseInfo?.modifyUserName }}</span>
          <span>修改时间：{{ baseInfo?.modifyDate }}</span>
        </div>
        <div>
          <a-button size="small" class="title-btn" @click="handleEdit">编辑</a-button>
          <a-button size="small" class="title-btn" @click="handleDelete">删除</a-button>
          <a-button size="small" class="title-btn" @click="handlePrint">打印</a-button>
        </div>
      </a-card>
      <a-card :bordered="false">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="1" tab="订单信息">
            <a-row>基础信息</a-row>
            <a-row>
              <a-col :span="12">销售单号：{{ baseInfo?.saleNumber }}</a-col>
              <a-col :span="12">销售订单主题：{{ baseInfo?.theme }}</a-col>
            </a-row>
            <a-row>
              <a-col :span="12">销售日期：{{ baseInfo?.saleDate }}</a-col>
              <a-col :span="12">客户名称：{{ baseInfo?.customerName }}</a-col>
            </a-row>
            <a-row>
              <a-col :span="12">联系人：{{ baseInfo?.clientPerson }}</a-col>
              <a-col :span="12">联系方式：{{ baseInfo?.clientWay }}</a-col>
            </a-row>
            <a-row>
              <a-col :span="12">客户经理：{{ baseInfo?.manager }}</a-col>
              <a-col :span="12">所属部门：{{ baseInfo?.depName }}</a-col>
            </a-row>
            <a-row>
              <a-col :span="12">联系电话：{{ baseInfo?.phone }}</a-col>
              <a-col :span="12">关联项目：{{ baseInfo?.relatedProjectName }}</a-col>
            </a-row>
            <a-row>
              <a-col :span="12">结算方式：{{ baseInfo?.payTypeName }}</a-col>
              <a-col :span="12">客户订单号：{{ baseInfo?.clientNumber }}</a-col>
            </a-row>
            <a-row> 交货地址：{{ baseInfo?.payAddress }} </a-row>
            <a-row> 备注：{{ baseInfo?.remark }} </a-row>
            <BasicTable @register="registerSaleTable">
              <template #toolbar>
                <a-button type="primary" @click="handleExport('sale')" class="!mr-4">导出</a-button>
              </template>
            </BasicTable>
            <div class="table-bottom">
              <span>合计</span>
              <div>
                <span>总量：{{ baseInfo?.countSum }}</span>
                <span> 总金额：{{ baseInfo?.amountSum }}</span>
                <span> 优惠金额：{{ baseInfo?.discount }}</span>
              </div>
            </div>
            <div>
              附件：
              <Upload
                v-if="baseInfo?.filePath"
                v-model:value="baseInfo.filePath"
                listType="dragger"
                :style="{ width: '200px', display: 'none' }"
                :showRemoveIcon="false"
              />
            </div>
          </a-tab-pane>
          <a-tab-pane key="2">
            <template #tab>
              <span>
                出库记录
                <Icon
                  icon="ant-design:check-circle-filled"
                  :size="20"
                  v-if="baseInfo?.outStoreState === 1"
                />
                <Icon
                  icon="ant-design:exclamation-circle-filled"
                  color="#FF1A2E"
                  :size="20"
                  v-else
                />
              </span>
            </template>

            <BasicTable @register="registerOutstoreTable">
              <template #toolbar>
                <a-button type="primary" @click="handleExport('outstore')" class="!mr-4"
                  >导出</a-button
                >
              </template>
            </BasicTable>
          </a-tab-pane>
          <a-tab-pane key="3">
            <template #tab>
              <span>
                开票记录
                <Icon
                  icon="ant-design:check-circle-filled"
                  :size="20"
                  v-if="baseInfo?.ticketState === 1"
                />
                <Icon
                  icon="ant-design:exclamation-circle-filled"
                  color="#FF1A2E"
                  :size="20"
                  v-else
                />
              </span>
            </template>
            <BasicTable @register="registerInvoiceTable">
              <template #toolbar>
                <a-button type="primary" @click="handleExport('invoice')" class="!mr-4"
                  >导出</a-button
                >
              </template>
            </BasicTable>
          </a-tab-pane>
          <a-tab-pane key="4">
            <template #tab>
              <span>
                收款记录
                <Icon
                  icon="ant-design:check-circle-filled"
                  :size="20"
                  v-if="baseInfo?.payState === 1"
                />
                <Icon
                  icon="ant-design:exclamation-circle-filled"
                  color="#FF1A2E"
                  :size="20"
                  v-else
                />
              </span>
            </template>
            <BasicTable @register="registerCollectionTable">
              <template #toolbar>
                <a-button type="primary" @click="handleExport('collection')" class="!mr-4"
                  >导出</a-button
                >
              </template>
            </BasicTable>
          </a-tab-pane>
          <a-tab-pane key="5" tab="生产记录">
            <BasicTable @register="registerProductTable">
              <template #toolbar>
                <a-button type="primary" @click="handleExport('product')" class="!mr-4"
                  >导出</a-button
                >
              </template>
            </BasicTable>
          </a-tab-pane>
          <a-tab-pane key="6" tab="操作记录">
            <BasicTable @register="registerLogTable">
              <template #toolbar>
                <a-button type="primary" @click="handleExport('log')" class="!mr-4">导出</a-button>
              </template>
            </BasicTable>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>
  </BasicModal>
  <OrderModal @register="registerOrderModal" @success="handleSuccess" />
</template>
<script lang="ts" setup>
  import { ref, createVNode } from 'vue';
  import { BasicTable, useTable, BasicColumn, FormSchema } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {
    getSaleCheckInfo,
    deleteSale,
    exportSaleInfo,
    exportOutstoreInfo,
    exportInvoiceInfo,
    exportProductInfo,
    exportCollectionInfo,
    exportLogInfo,
  } from '/@/api/erp/sale/order';
  import { getFileList } from '/@/api/system/file';
  import { useModal } from '/@/components/Modal';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  import { downloadByData } from '/@/utils/file/download';
  import OrderModal from './OrderModal.vue';
  import Icon from '/@/components/Icon/index';
  import Upload from '/@/components/Form/src/components/Upload.vue';
  import printJS from 'print-js';
  import domtoimage from 'dom-to-image';
  import { isNil } from 'lodash-es';
  import { getFileUrl } from '/@/utils/event/design';

  const saleColumns: BasicColumn[] = [
    {
      title: '产品编码',
      dataIndex: 'code',
    },
    {
      title: '产品名称',
      dataIndex: 'name',
    },
    {
      title: '规格型号',
      dataIndex: 'model',
    },
    {
      title: '单位',
      dataIndex: 'unitName',
    },
    {
      title: '单价',
      dataIndex: 'price',
    },
    {
      title: '销售数量',
      dataIndex: 'count',
    },
    {
      title: '折扣',
      dataIndex: 'discount',
    },
    {
      title: '税率',
      dataIndex: 'taxRate',
    },
    {
      title: '税费',
      dataIndex: 'taxBreak',
    },
    {
      title: '税后金额',
      dataIndex: 'afterTaxAmount',
    },
    {
      title: '交付日期',
      dataIndex: 'deliveryDate',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
  ];
  const outstoreColumns: BasicColumn[] = [
    {
      dataIndex: 'code',
      title: '出库单号',
      align: 'center',
      width: 100,
    },

    {
      dataIndex: 'theme',
      title: '出库订单主题',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'date',
      title: '出库日期',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'name',
      title: '客户名称',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'person',
      title: '出库人员',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'store',
      title: '出库仓库',
      align: 'center',
      width: 100,
    },
  ];
  const invoiceColumns: BasicColumn[] = [
    {
      dataIndex: 'code',
      title: '开票编号',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'theme',
      title: '开票主题',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'date',
      title: '开票日期',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'invoiceName',
      title: '发票类型',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'ticketNum',
      title: '发票号码',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'ticketAmout',
      title: '发票金额',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'ticketName',
      title: '收款方',
      align: 'center',
      width: 100,
    },
  ];
  const collectionColumns: BasicColumn[] = [
    {
      dataIndex: 'code',
      title: '收款编号',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'theme',
      title: '收入主题',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'date',
      title: '收入日期',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'amount',
      title: '收款总额',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'payer',
      title: '付款方',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'account',
      title: '银行账号',
      align: 'center',
      width: 100,
    },
  ];
  const productColumns: BasicColumn[] = [
    {
      dataIndex: 'code',
      title: '生产编号',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'theme',
      title: '生产主题',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'type',
      title: '生产类型',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'date',
      title: '单据日期',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'person',
      title: '负责人',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'dep',
      title: '生产部门',
      align: 'center',
      width: 100,
    },
    {
      dataIndex: 'state',
      title: '状态',
      align: 'center',
      width: 100,
    },
  ];
  const logColumns: BasicColumn[] = [
    {
      dataIndex: 'operateUserAccount',
      title: '操作人',
      align: 'center',
    },
    {
      dataIndex: 'createDate',
      title: '操作时间',
      align: 'center',
    },
    {
      dataIndex: 'executeResultJson',
      title: '操作类型',
      align: 'center',
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入要查询的关键字',
      },
    },
  ];

  const { t } = useI18n();

  const emit = defineEmits(['success']);

  const saleInfoDataSource = ref<any>([]);
  const outstoreDataSource = ref<any>([]);
  const invoiceDataSource = ref<any>([]);
  const collectionDataSource = ref<any>([]);
  const productDataSource = ref<any>([]);
  const logInfoDataSource = ref<any>([]);

  const rowId = ref('');
  const activeKey = ref('1');
  const baseInfo = ref();
  const imgList = ref<any>([]);
  const { notification } = useMessage();

  const [registerOrderModal, { openModal: openOrderModal }] = useModal();

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({
      confirmLoading: false,
      destroyOnClose: true,
      showCancelBtn: false,
      showOkBtn: false,
      width: 1000,
      fixedHeight: true,
      footer: null,
    });
    rowId.value = data.id;
    getInfo();
  });

  const [registerSaleTable, { getSelectRowKeys: getSaleRowKeys }] = useTable({
    title: '产品明细',
    dataSource: saleInfoDataSource,
    rowKey: 'id',
    columns: saleColumns,
    pagination: false,
    rowSelection: {
      type: 'checkbox',
    },
  });
  const [
    registerOutstoreTable,
    { getSelectRowKeys: getOutstoreRowKeys, setProps: setOutstoreProps },
  ] = useTable({
    dataSource: outstoreDataSource,
    rowKey: 'id',
    columns: outstoreColumns,
    handleSearchInfoFn(info) {
      const filterData = outstoreDataSource.value.filter((item) => {
        for (const key in item) {
          if (!isNil(item[key]) && item[key].toString().indexOf(info.keyword) > -1) {
            return item;
          }
        }
      });
      setOutstoreProps({ dataSource: filterData });
      return info;
    },
    formConfig: {
      schemas: searchFormSchema,
    },
    pagination: false,
    useSearchForm: true,
    rowSelection: {
      type: 'checkbox',
    },
  });
  const [registerInvoiceTable, { getSelectRowKeys: getInvoiceRowKeys, setProps: setInvoiceProps }] =
    useTable({
      dataSource: invoiceDataSource,
      rowKey: 'id',
      columns: invoiceColumns,
      handleSearchInfoFn(info) {
        const filterData = invoiceDataSource.value.filter((item) => {
          for (const key in item) {
            if (!isNil(item[key]) && item[key].toString().indexOf(info.keyword) > -1) {
              return item;
            }
          }
        });
        setInvoiceProps({ dataSource: filterData });
        return info;
      },
      formConfig: {
        schemas: searchFormSchema,
      },
      pagination: false,
      useSearchForm: true,
      rowSelection: {
        type: 'checkbox',
      },
    });
  const [
    registerCollectionTable,
    { getSelectRowKeys: getCollectionRowKeys, setProps: setCollectionProps },
  ] = useTable({
    dataSource: collectionDataSource,
    rowKey: 'id',
    columns: collectionColumns,
    handleSearchInfoFn(info) {
      const filterData = collectionDataSource.value.filter((item) => {
        for (const key in item) {
          if (!isNil(item[key]) && item[key].toString().indexOf(info.keyword) > -1) {
            return item;
          }
        }
      });
      setCollectionProps({ dataSource: filterData });
      return info;
    },
    formConfig: {
      schemas: searchFormSchema,
    },
    pagination: false,
    useSearchForm: true,
    rowSelection: {
      type: 'checkbox',
    },
  });
  const [registerProductTable, { getSelectRowKeys: getProductRowKeys, setProps: setProductProps }] =
    useTable({
      dataSource: productDataSource,
      rowKey: 'id',
      columns: productColumns,
      handleSearchInfoFn(info) {
        const filterData = productDataSource.value.filter((item) => {
          for (const key in item) {
            if (!isNil(item[key]) && item[key].toString().indexOf(info.keyword) > -1) {
              return item;
            }
          }
        });
        setProductProps({ dataSource: filterData });
        return info;
      },
      formConfig: {
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      pagination: false,
      rowSelection: {
        type: 'checkbox',
      },
    });
  const [registerLogTable, { setProps: setLogProps }] = useTable({
    dataSource: logInfoDataSource,
    rowKey: 'id',
    columns: logColumns,
    handleSearchInfoFn(info) {
      const filterData = logInfoDataSource.value.filter((item) => {
        for (const key in item) {
          if (!isNil(item[key]) && item[key].toString().indexOf(info.keyword) > -1) {
            return item;
          }
        }
      });
      setLogProps({ dataSource: filterData });
      return info;
    },
    formConfig: {
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    pagination: false,
  });

  const getInfo = async () => {
    const res = await getSaleCheckInfo(rowId.value);
    baseInfo.value = res;
    saleInfoDataSource.value = res?.caseErpSaleDetailList;
    outstoreDataSource.value = res?.outstoreList.map((x) => {
      return {
        code: x.code,
        theme: x.theme,
        date: x.date,
        name: x.name,
        count: x.count,
        person: x.person,
        store: x.store,
      };
    });
    invoiceDataSource.value = res?.invoiceList.map((x) => {
      return {
        code: x.code,
        theme: x.theme,
        date: x.date,
        invoiceName: x.invoiceName,
        ticketNum: x.ticketNum,
        ticketAmout: x.ticketAmout,
        ticketName: x.ticketName,
      };
    });
    collectionDataSource.value = res?.collectionList.map((x) => {
      return {
        code: x.code,
        theme: x.theme,
        date: x.date,
        amount: x.amount,
        payer: x.payer,
        account: x.account,
      };
    });
    productDataSource.value = res?.productList.map((x) => {
      return {
        code: x.code,
        theme: x.theme,
        date: x.date,
        type: x.type,
        person: x.person,
        dep: x.dep,
        state: x.state,
      };
    });
    logInfoDataSource.value = res?.logList.map((x) => {
      return {
        operateUserAccount: x.operateUserAccount,
        createDate: x.createDate,
        executeResultJson: x.executeResultJson,
      };
    });
    if (baseInfo.value.filePath) {
      imgList.value = await getFileList({ folderId: baseInfo.value.filePath });
      imgList.value?.forEach((x) => {
        x.url = getFileUrl(x);
      });
    }
  };

  const handleExport = async (type) => {
    const params: any = {
      saleId: rowId.value,
    };
    let title = '';
    let res;
    switch (type) {
      case 'sale':
        if (!notice(getSaleRowKeys().length)) return;
        title = '订单信息';
        params.ids = getSaleRowKeys();
        res = await exportSaleInfo(params);
        break;
      case 'outstore':
        if (!notice(getOutstoreRowKeys().length)) return;
        title = '出库记录';
        params.ids = getOutstoreRowKeys();
        res = await exportOutstoreInfo(params);
        break;
      case 'invoice':
        if (!notice(getInvoiceRowKeys().length)) return;
        title = '开票记录';
        params.ids = getInvoiceRowKeys();
        res = await exportInvoiceInfo(params);
        break;
      case 'collection':
        if (!notice(getCollectionRowKeys().length)) return;
        title = '收款记录';
        params.ids = getCollectionRowKeys();
        res = await exportCollectionInfo(params);
        break;
      case 'product':
        if (!notice(getProductRowKeys().length)) return;
        title = '生产记录';
        params.ids = getProductRowKeys();
        res = await exportProductInfo(params);
        break;
      case 'log':
        title = '操作记录';
        res = await exportLogInfo(params);
        break;
    }
    downloadByData(
      res.data,
      `${title}.xlsx`,
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };

  const notice = (length) => {
    if (!length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要导出的数据',
      });
      return false;
    }
    return true;
  };

  const handleEdit = () => {
    openOrderModal(true, {
      id: rowId.value,
      isUpdate: true,
    });
  };

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

  const handleSuccess = () => {
    closeModal();
    emit('success');
  };

  const handlePrint = async () => {
    const element: HTMLElement = window.document.querySelector('.info-box')!;
    const url = await domtoimage.toPng(element);
    printJS({
      printable: url,
      type: 'image',
      documentTitle: '打印',
    });
  };
</script>
<style lang="less" scoped>
  .info-box {
    background-color: #fff;
    width: 100%;
    padding: 16px;

    .title-name {
      font-size: 18px;
      color: #444;
      font-weight: 700;
    }

    .title-info {
      margin: 10px 0;

      span {
        margin-right: 40px;
      }
    }

    .table-bottom {
      display: flex;
      justify-content: space-between;
      margin: 10px 0;

      & > div > span {
        margin-left: 40px;
      }
    }

    .title-btn {
      margin-right: 5px;
    }
  }

  .ant-row {
    margin-bottom: 15px;
  }

  :deep(.vben-basic-table) {
    height: 300px;
  }

  :deep(.ant-table-wrapper),
  :deep(.ant-table-title) {
    background-color: #f8f8f8;
  }

  :deep(.ant-card-body) {
    background-color: #f8f8f8;
    margin-bottom: 12px;
    padding: 15px;
  }

  :deep(.ant-tabs) {
    height: 70%;
  }

  :deep(.ant-tabs-content) {
    height: 100%;
  }

  :deep(.vben-basic-table-header__toolbar) {
    min-width: 30%;
  }
</style>
