import { Avatar, Button, Input, Modal, Space, Table, Tag, Typography } from "antd"
import React, { useCallback, useEffect, useState } from "react"
import { UserAddOutlined, UserOutlined } from '@ant-design/icons';
import { useAjax } from "@/Hook/useAjax";
import { getCorpExternalUserListApi } from "@/API/global";
import SearchBox from "../../components/searchBox";
import { copy } from "@/utils/utils";



interface Props {
    corpId: string,
    corpUserIds?: string[],
    value?: any
    onChange?: (value?: any) => void
}
const SelectGDUser: React.FC<Props> = ({ corpId, corpUserIds = [], value, onChange }) => {

    /******************************/
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])
    const [showOpen, set_ShowOpen] = useState(false)
    const [queryForm2, setQueryForm2] = useState<any>({ pageNum: 1, pageSize: 20, corpId: '', deleted: false })
    const getCorpExternalUserList = useAjax((params) => getCorpExternalUserListApi(params))
    /******************************/

    // 查固定客户
    useEffect(() => {
        if (corpId && corpUserIds?.length > 0 && showOpen) {
            getCorpExternalUserList.run({ ...queryForm2, corpId, corpUserIds })
        }
    }, [queryForm2, corpId, corpUserIds, showOpen])

    useEffect(() => {
        setEditSelectedRow(value || [])
    }, [value])

    const setFieldValue1 = useCallback((e: any, field: string, f?: any, field1?: string) => {
        let newQueryForm = JSON.parse(JSON.stringify(queryForm2))
        newQueryForm['pageNum'] = 1
        newQueryForm['pageSize'] = 20
        if (field === 'platformKey') {
            newQueryForm[field] = e
        } else {
            newQueryForm[field] = e
            if (field1) {
                newQueryForm[field1] = f
            }
            newQueryForm['platformKey'] = newQueryForm['platformKey'] || undefined
        }
        setQueryForm2(newQueryForm)
    }, [queryForm2])

    const handleOk = () => {
        onChange?.(editSelectedRow)
        set_ShowOpen(false)
    }
    return <>
        <Space style={{ width: '100%' }}>
            <Space>
                {editSelectedRow?.map(item => {
                    return <div key={item.id} style={{ maxWidth: 70 }}><Typography.Text ellipsis={{ tooltip: true }}>{item.name}</Typography.Text></div>
                })}
            </Space>
            <Button type="primary" disabled={!corpId || corpUserIds?.length === 0} onClick={() => { set_ShowOpen(true) }}><UserAddOutlined />{editSelectedRow?.length > 0 ? '重新选择' : '选择客户'}</Button>
        </Space>

        <Modal
            width={900}
            open={showOpen}
            onCancel={() => { set_ShowOpen(false) }}
            onOk={handleOk}
            zIndex={2000}
        >
            <SearchBox buttons={<>
                <Button icon={getCorpExternalUserList.loading} onClick={() => getCorpExternalUserList.refresh()}>刷新</Button>
            </>}>
                <>
                    <Input placeholder="客户名称" style={{ width: 125 }} allowClear value={queryForm2?.name} onChange={(e) => setFieldValue1(e.target.value, 'name')} />
                    <Input placeholder="客户ID" style={{ width: 125 }} allowClear value={queryForm2?.externalUserId} onChange={(e) => setFieldValue1(e.target.value, 'externalUserId')} />
                </>
            </SearchBox>
            <Table
                tableLayout='fixed'
                dataSource={getCorpExternalUserList.data?.data?.records?.map((item: any, index: number) => ({ ...item, id: item.externalUserId + '_' + item.corpUserId }))}
                columns={[
                    {
                        title: '客户ID',
                        dataIndex: 'externalUserId',
                        key: 'externalUserId',
                        align: 'center',
                        width: 140,
                        ellipsis: true,
                        render: (a: string) => {
                            return <a onClick={() => copy(a)}>{a}</a>
                        },
                    },
                    {
                        title: '客户',
                        dataIndex: 'name',
                        key: 'name',
                        width: 80,
                        ellipsis: true,
                        render: (a: string, b: any) => {
                            return <Space style={{ width: '100%' }}>
                                <Avatar shape="square" size="small" icon={<UserOutlined />} src={b?.avatar} />
                                <Typography.Paragraph style={{ marginBottom: 0, width: 250 }} ellipsis={{ rows: 1, tooltip: true }}>{a}</Typography.Paragraph>
                            </Space>
                        }
                    },
                    {
                        title: '通讯录成员名称',
                        dataIndex: 'corpUserName',
                        key: 'corpUserName',
                        align: 'center',
                        width: 80,
                        ellipsis: true
                    },
                ]}
                loading={getCorpExternalUserList.loading}
                scroll={{ y: 'calc(100vh - 17.8125rem)' }}
                rowKey={(r) => {
                    return r.id
                }}
                size='small'
                rowSelection={{
                    type: 'radio',
                    selectedRowKeys: editSelectedRow?.map(item => item.id),
                    getCheckboxProps: (record: any) => ({
                        name: record.name,
                    }),
                    onChange(_selectedRowKeys, selectedRows) {
                        setEditSelectedRow(selectedRows)
                    }
                }}
                pagination={{
                    total: getCorpExternalUserList.data?.data?.total,
                    showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                    showSizeChanger: true,
                    showLessItems: true,
                    defaultCurrent: 1,
                    defaultPageSize: 20,//默认初始的每页条数
                    current: getCorpExternalUserList?.data?.data?.current || 1,
                    pageSize: getCorpExternalUserList?.data?.data?.size || 20,
                    onChange: (page, pageSize) => {
                        setQueryForm2({ ...queryForm2, pageNum: page, pageSize })
                    }
                }}
            />
        </Modal>
    </>
}

export default React.memo(SelectGDUser)