<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <CustomerInfo :id="recordId" @return-page="returnPage" v-if="isShowPage" />
    <BasicTable @register="registerTable" v-else>
      <template #toolbar>
        <a-button type="primary" v-auth="'customerList:add'" @click="handleCreate">
          {{ t('新增') }}
        </a-button>
        <a-button type="primary" v-auth="'customerList:import'" @click="handleImport" class="ml-4">
          {{ t('导入') }}
        </a-button>
        <a-button type="primary" v-auth="'customerList:export'" @click="handleExport" class="ml-4">
          {{ t('导出') }}
        </a-button>
        <a-button type="primary" @click="handleTransfer" class="ml-4"> 移入公海 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'action'">
          <a-button type="link" class="actionTxt" @click="handleFollow(record)">跟进</a-button>
          <a-button type="link" class="actionTxt" @click="showPage(record)"> 详情查看 </a-button>
          <a-button
            type="link"
            class="actionTxt"
            v-auth="'customerList:edit'"
            @click="handleEdit(record)"
          >
            编辑
          </a-button>
          <SelectUser
            :selectedIds="userIds"
            :multiple="false"
            @change="(ids) => handleTransferUser(ids, record)"
            :style="{ display: 'inline' }"
          >
            <a-button type="link" class="actionTxt" :style="{ color: '#5e95ff' }">转移</a-button>
          </SelectUser>
          <a-button
            type="link"
            class="actionTxt"
            v-auth="'customerList:delete'"
            @click="handleDelete(record)"
          >
            删除
          </a-button>
        </template>
      </template>
    </BasicTable>
    <CustomerModal @register="registerModal" @success="reload" />
    <FollowModal @register="registerFollowModal" @success="reload" />
    <ImportModal
      @register="registerImportModal"
      importUrl="/caseErpCustomer/caseErpCustomer/import"
      @success="reload"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode, ref } 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 {
    getCustomerPageList,
    deleteCustomer,
    transferCommon,
    exportInfo,
    downloadTemplate,
    transferUser,
  } from '/@/api/erp/customer/list';
  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 { SelectUser } from '/@/components/SelectOrganizational/index';
  import CustomerModal from './components/CustomerModal.vue';
  import CustomerInfo from './components/CustomerInfo.vue';
  import FollowModal from './components/FollowModal.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

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

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

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

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

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

  const recordId = ref('');
  const isShowPage = ref<boolean>(false);
  const userIds = ref([]);

  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('customerList:edit')) {
          handleEdit(record);
        }
      },
    };
  };
  const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys }] = 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: 0 };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 280,
      title: t('操作'),
      dataIndex: 'action',
    },
    rowSelection: {
      type: 'checkbox',
    },
    customRow,
    tableSetting: {
      size: false,
    },
  });

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

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

  const handleFollow = (record) => {
    openFollowModal(true, {
      record,
    });
  };

  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 () => {
    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',
    );
  };

  const handleTransfer = async () => {
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要移入公海的数据',
      });
      return false;
    }
    await transferCommon(getSelectRowKeys());
    notification.success({
      message: t('提示'),
      description: '移入公海',
    });
    reload();
  };

  const handleTransferUser = async (ids, record) => {
    const params = {
      id: record.id,
      saleIds: ids.length ? ids[0] : '',
    };
    await transferUser(params);
    notification.success({
      message: t('提示'),
      description: '转移成功',
    });
    reload();
  };
  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>
