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 { getCorpUserChatListApi, getCorpUserChatListProps } from '../../API/groupLeaderManage';
import { getAdAccountAllOfMember, getCorpAllListApi } from '@/API/global';
import { STATUSENUM } from '.';

interface SelectCorpUserChatUserProps {
    value?: { label: string, value: number, name: string, corpName: string, corpId: string, corpUserId: string }[];
    onChange?: (value: { label: string, value: number, name: string, corpName: string, corpId: string, corpUserId: string }[]) => void;
    placeholder?: React.ReactNode
}

/**
 * 选择群主
 * @returns 
 */
const SelectGroupLeader: 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.value !== value?.[0]?.value))
                        }}
                    >
                        {value?.[0]?.label || value?.[0]?.value}
                    </Tag>
                    {value?.length > 1 && <Tooltip
                        color="#FFF"
                        title={<span style={{ color: '#000' }}>
                            {value?.filter((_, index) => index !== 0)?.map((item) => <Tag
                                key={item.value}
                                closable
                                onClick={(e) => e.stopPropagation()}
                                onClose={(e) => {
                                    e.stopPropagation()
                                    onChange(value?.filter(item1 => item1.value !== item.value))
                                }}
                            >{item.label || item?.value}</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, visible, onClose, onChange, value }) => {

    /**********************************************/
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])
    const { message } = App.useApp()
    const [queryParams, setQueryParams] = useState<getCorpUserChatListProps>({ pageNum: 1, pageSize: 20 })
    const [queryParamsNew, setQueryParamsNew] = useState<getCorpUserChatListProps>({ pageNum: 1, pageSize: 20 })


    const getCorpUserChatList = useAjax((params) => getCorpUserChatListApi(params))
    const allOfMember = useAjax(() => getAdAccountAllOfMember())
    const getCorpAllList = useAjax((params) => getCorpAllListApi(params))
    /**********************************************/

    useEffect(() => {
        allOfMember.run()
        getCorpAllList.run({})
    }, [])

    useEffect(() => {
        getCorpUserChatList.run(queryParamsNew)
    }, [queryParamsNew])

    useEffect(() => {
        if (visible) {
            setEditSelectedRow(value?.length ? value.map(item => ({
                id: item.value,
                name: item.name,
                corpName: item.corpName,
                corpId: item.corpId,
                corpUserId: item.corpUserId
            })) : [])
        }
    }, [visible, value])

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

    return <Modal
        title={<strong>{placeholder}</strong>}
        open={visible}
        width={900}
        onCancel={onClose}
        onOk={handleOk}
    >
        <div className='selectCorpUserBody' style={{ width: '100%' }}>
            <div className='selectCorpUserBody_search'>
                <Select
                    value={queryParams?.corpIds}
                    onChange={(e) => setQueryParams({ ...queryParams, corpIds: e })}
                    showSearch
                    mode='multiple'
                    style={{ minWidth: 110 }}
                    maxTagCount={1}
                    placeholder="主体"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    options={getCorpAllList?.data?.data?.map((item: any) => ({ label: item.corpName, value: item.corpId }))}
                />
                <Input style={{ width: 150 }} onChange={(e) => setQueryParams({ ...queryParams, corpUserName: e.target.value as any })} value={queryParams?.corpUserName} placeholder="客服号名称" allowClear />
                <Input style={{ width: 150 }} onChange={(e) => setQueryParams({ ...queryParams, corpUserIds: e.target.value as any })} value={queryParams?.corpUserIds} placeholder="客服ID（多个，,空格换行）" allowClear />
                <Select
                    value={queryParams?.operUserId}
                    onChange={(e) => setQueryParams({ ...queryParams, operUserId: e })}
                    showSearch
                    style={{ width: 110 }}
                    placeholder="运营"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    options={allOfMember?.data?.data?.map((item: any) => ({ label: item.nickname, value: item.userId }))}
                />
                <Select
                    value={queryParams?.putUserId}
                    onChange={(e) => setQueryParams({ ...queryParams, putUserId: e })}
                    showSearch
                    style={{ width: 110 }}
                    placeholder="投手"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    options={allOfMember?.data?.data?.map((item: any) => ({ label: item.nickname, value: item.userId }))}
                />
                <Select
                    style={{ width: 90 }}
                    showSearch
                    placeholder="状态"
                    value={queryParams?.status}
                    onChange={(value) => setQueryParams({ ...queryParams, status: value })}
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    options={[{ label: '已激活', value: 1 }, { label: '已禁用', value: 2 }, { label: '未激活', value: 4 }, { label: '退出企业', value: 5 }]}
                />
                <Button type="primary" onClick={() => {
                    setQueryParamsNew({ ...queryParams, pageNum: 1 })
                }} loading={getCorpUserChatList.loading} icon={<SearchOutlined />}>搜索</Button>
            </div>
            <div className='selectCorpUserBody_content'>
                <Table
                    columns={[
                        {
                            title: '群主主体',
                            dataIndex: 'corpName',
                            key: 'corpName',
                            align: 'center',
                            width: 70,
                            ellipsis: true,
                        },
                        {
                            title: '群主企微主体ID',
                            dataIndex: 'corpId',
                            key: 'corpId',
                            align: 'center',
                            width: 70,
                            ellipsis: true,
                        },
                        {
                            title: '群主企微号',
                            dataIndex: 'name',
                            key: 'name',
                            align: 'center',
                            width: 70,
                            ellipsis: true,
                        },
                        {
                            title: '群主企微号ID',
                            dataIndex: 'corpUserId',
                            key: 'corpUserId',
                            align: 'center',
                            width: 70,
                            ellipsis: true,
                        },
                        {
                            title: '主运营',
                            dataIndex: 'operUser',
                            key: 'operUser',
                            align: 'center',
                            width: 70,
                            ellipsis: true,
                            render: (value) => {
                                return value?.nickname || '--'
                            }
                        },
                        {
                            title: '投手',
                            dataIndex: 'putUser',
                            key: 'putUser',
                            align: 'center',
                            width: 70,
                            ellipsis: true,
                            render: (value) => {
                                return value?.nickname || '--'
                            }
                        },
                        {
                            title: '运营助理',
                            dataIndex: 'userList',
                            key: 'userList',
                            width: 120,
                            ellipsis: true,
                            render: (value) => {
                                return value?.map(item => item.nickname)?.join('、') || '--'
                            }
                        },
                        {
                            title: '状态',
                            dataIndex: 'status',
                            key: 'status',
                            width: 70,
                            align: 'center',
                            render: (value) => {
                                return STATUSENUM[value]
                            }
                        }
                    ]}
                    dataSource={getCorpUserChatList?.data?.data?.records}
                    scroll={{ y: 350 }}
                    rowKey={'id'}
                    size='small'
                    loading={getCorpUserChatList?.loading}
                    pagination={{
                        total: getCorpUserChatList?.data?.data?.total,
                        showTotal: (total) => `共 ${total} 条数据`,
                        showQuickJumper: true,
                        showSizeChanger: true,
                        pageSizeOptions: ['10', '20', '50', '100'],
                        onChange: (pageNum, pageSize) => {
                            setQueryParams({ ...queryParams, pageNum, pageSize })
                            setQueryParamsNew({ ...queryParamsNew, pageNum, pageSize })
                        }
                    }}
                    rowSelection={{
                        type: 'checkbox',
                        selectedRowKeys: editSelectedRow?.map(item => item.id),
                        onSelect: (record, selected: any) => {
                            if (selected) {
                                setEditSelectedRow([...editSelectedRow, record])
                            } else {
                                setEditSelectedRow(editSelectedRow?.filter(item => item.id !== record.id))
                            }
                        },
                        onSelectAll: (selected: any, rows: any, changeRows: any[]) => {
                            if (selected) {
                                setEditSelectedRow([...editSelectedRow, ...changeRows])
                            } else {
                                let newArr = editSelectedRow?.filter(item => changeRows.every(i => i?.id !== item?.id))
                                setEditSelectedRow(newArr)
                            }
                        }
                    }}
                />
            </div>
        </div>
    </Modal>
});

export default SelectGroupLeader;