<template>
    <PageWrapper dense fixedHeight contentFullHeight>
        <CustomerInfo :id="recordId" @return-page="returnPage" v-if="isShowPage" />
        <BasicTableErp @register="registerTable" v-else>
            <template #toolbar>
                <a-button type="primary" @click="handleCreate"> {{ t('新增') }} </a-button>
                <a-button type="primary" @click="handleImport"> {{ t('导入') }} </a-button>
                <a-button type="primary" @click="handleExport"> {{ t('导出') }} </a-button>
                <a-button type="primary" @click="handleTransfer"> 移入公海 </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" @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" @click="handleDelete(record)">删除</a-button>
                </template>
            </template>
        </BasicTableErp>
        <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 { useTable, 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 { 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';

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

    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 [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);
            }
        };
    };
    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]]
        },
        beforeFetch: (params) => {
            return { ...params, state: 0 };
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        actionColumn: {
            width: 220,
            title: t('操作'),
            dataIndex: 'action'
        },
        rowSelection: {
            type: 'checkbox'
        },
        customRow
    });

    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: 4px 2px;

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