import useNewToken from '@/Hook/useNewToken';
import React, { useEffect, useState } from 'react';
import { App, Button, Input, Modal, Select, Table, Tag, Tooltip, Typography } from 'antd';
import { CloseCircleFilled, SearchOutlined } from '@ant-design/icons';
import '../corpUserManage/global.less'
import { useAjax } from '@/Hook/useAjax';
import { getCorpUserChatCorpUserListApi } from '../../API/groupLeaderManage';
import { RowSelectionType } from 'antd/es/table/interface';
const { Paragraph } = Typography;

interface SelectCorpUserChatUserProps {
    // 这里可以添加选择成员组件的属性
    bindType: 1 | 2
    corpUserChatIds: number[]
    value?: { corpUserId: string, name: string, corpName: string, corpId: string }[];
    onChange?: (value: { corpUserId: string, name: string, corpName: string, corpId: string }[]) => void;
    placeholder?: React.ReactNode
    type?: RowSelectionType
}

/**
 * 选择群主下客服号 机器人号
 * @returns 
 */
const SelectCorpUserChatUser: React.FC<SelectCorpUserChatUserProps> = ({ value, onChange, placeholder, ...its }) => {

    /************************************************************/
    const { token } = useNewToken()
    const [visible, setVisible] = useState<boolean>(false);
    /************************************************************/

    return <>
        <div
            className='selectCorpUser'
            style={{
                border: `1px solid ${token.colorBorder}`,
                padding: `0px ${token.paddingXS}px`,
                borderRadius: token.borderRadius,
                height: token.controlHeight,
            }}
            onClick={() => setVisible(true)}
        >
            <div className='selectCorpUserContent'>
                {(value && value?.length > 0) ? <>
                    <Tag
                        closable
                        onClick={(e) => e.stopPropagation()}
                        onClose={(e) => {
                            e.preventDefault();
                            onChange(value?.filter(item => item.corpUserId !== value?.[0]?.corpUserId))
                        }}
                    >
                        {value?.[0]?.name || value?.[0]?.corpUserId}
                    </Tag>
                    {value?.length > 1 && <Tooltip
                        color="#FFF"
                        title={<span style={{ color: '#000' }}>
                            {value?.filter((_, index) => index !== 0)?.map((item) => <Tag
                                key={item.corpUserId}
                                closable
                                onClick={(e) => e.stopPropagation()}
                                onClose={(e) => {
                                    e.stopPropagation()
                                    onChange(value?.filter(item1 => item1.corpUserId !== item.corpUserId))
                                }}
                            >{item.name || item?.corpUserId}</Tag>)}</span>
                        }
                    >
                        <Tag>+{value.length - 1} ...</Tag>
                    </Tooltip>}
                </> : <span style={{ color: token.colorTextDisabled }}>{placeholder || '请选择客服号'}</span>}
            </div>
            {(value && value?.length > 0) && <div className='selectCorpUserIcon'>
                <CloseCircleFilled
                    className='selectCorpUserIconClear'
                    style={{ fontSize: token.fontSizeIcon, color: token.colorTextSecondary }}
                    onClick={(e) => {
                        e.stopPropagation()
                        onChange?.([])
                    }}
                />
            </div>}
        </div>

        {visible && <SelectCorpUserChatUserModal
            {...its}
            value={value}
            visible={visible}
            placeholder={placeholder}
            onClose={() => setVisible(false)}
            onChange={(values) => {
                onChange?.(values)
                setVisible(false)
            }}
        />}
    </>
};

interface SelectCorpUserChatUserModalProps extends SelectCorpUserChatUserProps {
    visible?: boolean
    onClose?: () => void
}

const SelectCorpUserChatUserModal: React.FC<SelectCorpUserChatUserModalProps> = React.memo(({ placeholder, bindType, corpUserChatIds, visible, onClose, onChange, value, type = 'checkbox' }) => {

    /**********************************************/
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])
    const { message } = App.useApp()

    const getCorpUserChatCorpUserList = useAjax((params) => getCorpUserChatCorpUserListApi(params))
    /**********************************************/

    useEffect(() => {
        if (bindType && corpUserChatIds?.length > 0) {
            getCorpUserChatCorpUserList.run({ bindType, corpUserChatIds })
        }
    }, [bindType, corpUserChatIds])

    useEffect(() => {
        if (visible) {
            setEditSelectedRow(value?.length ? [...value] : [])
        }
    }, [visible, value])

    const handleOk = () => {
        if (editSelectedRow.length) {
            onChange?.(editSelectedRow.map(item => ({
                corpUserId: item.corpUserId,
                name: item.name,
                corpName: item.corpName,
                corpId: item.corpId
            })))
        } else {
            message.error('请至少选择一条数据')
        }
    }

    return <Modal
        title={<strong>{placeholder}</strong>}
        open={visible}
        width={800}
        onCancel={onClose}
        onOk={handleOk}
    >
        <div className='selectCorpUserBody' style={{ width: '100%' }}>
            <div className='selectCorpUserBody_search'>
                <Button type="primary" onClick={() => {
                    getCorpUserChatCorpUserList.refresh()
                }} loading={getCorpUserChatCorpUserList.loading} icon={<SearchOutlined />}>刷新</Button>
            </div>
            <div className='selectCorpUserBody_content'>
                <Table
                    columns={[
                        {
                            title: (bindType === 1 ? '客服号' : '机器人号'),
                            dataIndex: 'corpUser',
                            key: 'name',
                            width: 150,
                            render: (value) => {
                                return <div>
                                    <Paragraph style={{ margin: 0 }} ellipsis>{value?.name || '--'}（{value?.corpUserId || '--'}）</Paragraph>
                                </div>
                            }
                        },
                        {
                            title: (bindType === 1 ? '客服号' : '机器人号') + '企业',
                            dataIndex: 'corpUser',
                            key: 'corpUser',
                            width: 150,
                            render: (value) => {
                                return <div>
                                    <Paragraph style={{ margin: 0 }} ellipsis>{value?.corpName || '--'}（{value?.corpId || '--'}）</Paragraph>
                                </div>
                            }
                        }
                    ]}
                    dataSource={getCorpUserChatCorpUserList?.data?.data}
                    size='small'
                    scroll={{ y: 350 }}
                    rowKey={'corpUserId'}
                    loading={getCorpUserChatCorpUserList.loading}
                    rowSelection={type === 'checkbox' ? {
                        type: 'checkbox',
                        selectedRowKeys: editSelectedRow?.map(item => item.corpUserId),
                        onSelect: (record: { corpUserId: any; corpUser: any }, selected: any) => {
                            if (selected) {
                                setEditSelectedRow([...editSelectedRow, { ...record, ...record?.corpUser }])
                            } else {
                                setEditSelectedRow(editSelectedRow?.filter(item => item.corpUserId !== record.corpUserId))
                            }
                        },
                        onSelectAll: (selected: any, rows: any, changeRows: any[]) => {
                            if (selected) {
                                setEditSelectedRow([...editSelectedRow, ...changeRows.map(item => ({ ...item, ...item?.corpUser }))])
                            } else {
                                let newArr = editSelectedRow?.filter(item => changeRows.every(i => i?.corpUserId !== item?.corpUserId))
                                setEditSelectedRow(newArr)
                            }
                        }
                    } : {
                        type: 'radio',
                        selectedRowKeys: editSelectedRow?.map(item => item.corpUserId),
                        onChange(_, selectedRows) {
                            setEditSelectedRow(selectedRows)
                        },
                    }}
                />
            </div>
        </div>
    </Modal>
});

export default SelectCorpUserChatUser;