<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <CustomerInfo :id="recordId" @return-page="returnPage" :isCommon="true" v-if="isShowPage" />
    <BasicTable @register="registerTable" v-else>
      <template #toolbar>
        <a-button type="primary" v-auth="'common:add'" @click="handleCreate">
          {{ t('新增') }}
        </a-button>
        <a-button type="primary" v-auth="'common:import'" @click="handleImport" class="ml-4">
          {{ t('导入') }}
        </a-button>
        <a-button type="primary" v-auth="'common:export'" @click="handleExport" class="ml-4">
          {{ t('导出') }}
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                label: '领取',
                onClick: handleCustomer.bind(null, record),
              },
              {
                label: '详情',
                onClick: showPage.bind(null, record),
              },
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <CustomerModal @register="registerModal" @success="reload" />
    <ImportModal
      @register="registerImportModal"
      importUrl="/caseErpCustomer/caseErpCustomer/import-common"
      @success="reload"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { BasicTable, useTable, BasicColumn, FormSchema, TableAction } from '/@/components/Table';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { getCustomerPageList, deleteCustomer } from '/@/api/erp/customer/list';
  import { getFromCommon, exportInfo, downloadTemplate } from '/@/api/erp/customer/common';
  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 CustomerModal from './components/CustomerModal.vue';
  import CustomerInfo from './components/CustomerInfo.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '客户名称',
      dataIndex: 'name',
      resizable: true,
    },
    {
      title: '客户类型',
      dataIndex: 'typeName',
      resizable: true,
    },
    {
      title: '联系人',
      dataIndex: 'defaultName',
      resizable: true,
    },
    {
      title: '手机号码',
      dataIndex: 'defaultPhone',
      resizable: true,
    },
    {
      title: '所在行业',
      dataIndex: 'industry',
      resizable: true,
    },
    {
      title: '来源',
      dataIndex: 'sourceName',
      resizable: true,
    },
    {
      title: '加入公海日期',
      dataIndex: 'inOpenDate',
      resizable: true,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      resizable: true,
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'typeId',
      label: '客户类型',
      component: 'XjrSelect',
      colProps: { span: 8 },
      componentProps: {
        datasourceType: 'dic',
        params: { itemId: '1679007059387240450' },
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择客户类型',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'createDate',
      label: '加入时间',
      component: 'RangePicker',
      colProps: { span: 8 },
      componentProps: {
        format: 'YYYY-MM-DD',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'sourceId',
      label: '来源',
      component: 'XjrSelect',
      colProps: { span: 8 },
      componentProps: {
        datasourceType: 'dic',
        params: { itemId: '1679008505423876097' },
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择来源',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'name',
      label: '客户名称',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入客户名称',
      },
    },
  ];

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

  const [registerModal, { openModal }] = useModal();

  const [registerImportModal, { openModal: openImportModal }] = useModal();

  const recordId = ref('');
  const isShowPage = ref<boolean>(false);
  const [registerTable, { reload }] = useTable({
    title: '客户公海',
    api: getCustomerPageList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [['createDate', ['startTime', 'endTime'], 'YYYY-MM-DD', true]],
      showResetButton: false,
    },
    beforeFetch: (params) => {
      return { ...params, state: 1 };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 174,
      title: t('操作'),
      dataIndex: 'action',
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('common:edit')) {
            handleEdit(record);
          }
        },
      };
    },
    tableSetting: {
      size: false,
    },
  });

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

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

  const handleCustomer = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: '确认也要领取该客户吗？',
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await getFromCommon(record.id);
        notification.success({
          message: t('提示'),
          description: '领取成功',
        });
        reload();
      },
      onCancel() {},
    });
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteCustomer(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();
    downloadByData(
      res.data,
      '客户公海.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };

  const showPage = (record) => {
    isShowPage.value = true;
    recordId.value = record.id;
  };

  const returnPage = () => {
    isShowPage.value = false;
    reload();
  };
</script>
<style lang="less" scoped>
  .actionTxt {
    padding: 0 7px;

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