import useNewToken from '@/Hook/useNewToken';
import { App, Button, Input, Popover, Select, Table, Tag, Tooltip } from 'antd';
import React, { useEffect, useState } from 'react';
import './global.less'
import { CloseCircleFilled, SearchOutlined } from '@ant-design/icons';
import { useAjax } from '@/Hook/useAjax';
import { getAdAccountAllOfMember } from '../../API/global';
import { getCorpUserApi, getGroupListApi } from '../../API/corpUserManage';
import { WeTableSelectConfig } from './tableConfig';

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

/**
 * 选择企业微信用户
 * @param param0 
 * @returns 
 */
const SelectCorpUser: React.FC<Props> = ({ value = [], onChange, placeholder }) => {

    /************************************************************/
    const { token } = useNewToken()
    const { message } = App.useApp()
    const [open, setOpen] = useState<boolean>(false);
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])
    const [openNew, setOpenNew] = useState<number>(0);

    const [queryForm, setQueryForm] = useState<CORP_USER_ASSIGN_API.GetCorpUserProps>({ pageNum: 1, pageSize: 20, stopUse: false, status: 1 })
    const [queryFormNew, setQueryFormNew] = useState<CORP_USER_ASSIGN_API.GetCorpUserProps>({ pageNum: 1, pageSize: 20, stopUse: false, status: 1 })
    const allOfMember = useAjax(() => getAdAccountAllOfMember())
    const getCorpUser = useAjax((params) => getCorpUserApi(params))
    const getGroupList = useAjax(() => getGroupListApi())
    /************************************************************/

    useEffect(() => {
        if (open && !openNew) {
            setOpenNew(1)
            console.log('editSelectedRow')
            setEditSelectedRow(value?.length ? [...value] : [])
        }
    }, [open, value, openNew])

    useEffect(() => {
        if (open) {
            allOfMember.run()
            getGroupList.run()
        }
    }, [open])

    useEffect(() => {
        if (open) {
            const params = { ...queryForm }
            if (params?.corpIds) {
                params.corpIds = (params.corpIds as any).split(/[\s,，\n]/).filter((item: string) => item)
            } else {
                delete params?.corpIds
            }
            if (params?.corpUserIds) {
                params.corpUserIds = (params.corpUserIds as any).split(/[\s,，\n]/).filter((item: string) => item)
            } else {
                delete params?.corpUserIds
            }
            getCorpUser.run(params)
        }
    }, [queryForm, open])

    const handleOk = () => {
        if (editSelectedRow.length) {
            onChange?.([...editSelectedRow])
        } else {
            message.error('请至少选择一条数据')
        }
        setOpen(false)
    }

    return <Popover
        placement="bottomLeft"
        content={<div className='selectCorpUserBody'>
            <div className='selectCorpUserBody_search'>
                <Input style={{ width: 150 }} onChange={(e) => setQueryFormNew({ ...queryFormNew, corpIds: e.target.value as any })} value={queryFormNew?.corpIds} placeholder="企微ID（多个，,空格换行）" allowClear />
                <Input style={{ width: 150 }} onChange={(e) => setQueryFormNew({ ...queryFormNew, corpUserIds: e.target.value as any })} value={queryFormNew?.corpUserIds} placeholder="客服ID（多个，,空格换行）" allowClear />
                <Select
                    value={queryFormNew?.groupId}
                    onChange={(e) => setQueryFormNew({ ...queryFormNew, groupId: e })}
                    showSearch
                    style={{ width: 100 }}
                    placeholder="分组"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    options={getGroupList?.data?.data?.map((item: any) => ({ label: item.groupName, value: item.groupId }))}
                />
                <Select
                    value={queryFormNew?.operUserId}
                    onChange={(e) => setQueryFormNew({ ...queryFormNew, operUserId: e })}
                    showSearch
                    style={{ width: 100 }}
                    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={queryFormNew?.groupOwner}
                    onChange={(e) => setQueryFormNew({ ...queryFormNew, groupOwner: e })}
                    showSearch
                    style={{ width: 100 }}
                    placeholder="是否群主号"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    options={[{ label: '是', value: 1 }, { label: '否', value: 0 }]}
                />
                <Select
                    value={queryFormNew?.machine}
                    onChange={(e) => setQueryFormNew({ ...queryFormNew, machine: e })}
                    showSearch
                    style={{ width: 100 }}
                    placeholder="是否机器号"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    options={[{ label: '是', value: 1 }, { label: '否', value: 0 }]}
                />
                <Button type="primary" onClick={() => {
                    setQueryForm({ ...queryFormNew, pageNum: 1 })
                }} loading={getCorpUser.loading} icon={<SearchOutlined />}>搜索</Button>
            </div>
            <div className='selectCorpUserBody_content'>
                <Table
                    columns={WeTableSelectConfig()}
                    dataSource={getCorpUser?.data?.data?.records}
                    size='small'
                    scroll={{ y: 300 }}
                    rowKey={'corpUserId'}
                    loading={getCorpUser.loading}
                    pagination={{
                        current: getCorpUser?.data?.data?.current || 1,
                        pageSize: getCorpUser?.data?.data?.size || 20,
                        total: getCorpUser?.data?.data?.total,
                        showTotal: (total) => `共 ${total} 条数据`,
                        showSizeChanger: true
                    }}
                    rowSelection={{
                        type: 'checkbox',
                        selectedRowKeys: editSelectedRow?.map(item => item.corpUserId),
                        onSelect: (record: { corpUserId: any; }, selected: any) => {
                            if (selected) {
                                setEditSelectedRow([...editSelectedRow, record])
                            } else {
                                setEditSelectedRow(editSelectedRow?.filter(item => item.corpUserId !== record.corpUserId))
                            }
                        },
                        onSelectAll: (selected: any, rows: any, changeRows: any[]) => {
                            if (selected) {
                                setEditSelectedRow([...editSelectedRow, ...changeRows])
                            } else {
                                let newArr = editSelectedRow?.filter(item => changeRows.every(i => i?.corpUserId !== item?.corpUserId))
                                setEditSelectedRow(newArr)
                            }
                        }
                    }}
                    onChange={(pagination) => {
                        setQueryForm({ ...queryForm, pageNum: pagination.current || 1, pageSize: pagination.pageSize || 20 })
                    }}
                />
            </div>
            <div className='selectCorpUserBody_footer'>
                <Button onClick={() => { setOpen(false) }}>取消</Button>
                <Button type='primary' onClick={handleOk}>确定</Button>
            </div>
        </div>}
        arrow={false}
        open={open}
        trigger={'click'}
        onOpenChange={(e) => {
            setOpen(e)
            setOpenNew(0)
        }}
    >
        <div
            className='selectCorpUser'
            style={{
                border: `1px solid ${token.colorBorder}`,
                padding: `0px ${token.paddingXS}px`,
                borderRadius: token.borderRadius,
                height: token.controlHeight,
            }}
        >
            <div className='selectCorpUserContent'>
                {open ? <>
                    {(editSelectedRow && editSelectedRow?.length > 0) ? <>
                        <Tag
                            closable
                            onClose={(e) => {
                                e.preventDefault();
                                setEditSelectedRow(editSelectedRow?.filter(item => item.corpUserId !== editSelectedRow?.[0]?.corpUserId))
                            }}
                        >
                            {editSelectedRow?.[0]?.name || editSelectedRow?.[0]?.corpUserId}
                        </Tag>
                        {editSelectedRow?.length > 1 && <Tooltip
                            color="#FFF"
                            title={<span style={{ color: '#000' }}>
                                {editSelectedRow?.filter((_, index) => index !== 0)?.map((item) => <Tag
                                    key={item.corpUserId}
                                    closable
                                    onClose={(e) => {
                                        e.stopPropagation()
                                        setEditSelectedRow(editSelectedRow?.filter(item1 => item1.corpUserId !== item.corpUserId))
                                    }}
                                >{item.name || item?.corpUserId}</Tag>)}</span>
                            }
                        >
                            <Tag>+{editSelectedRow.length - 1} ...</Tag>
                        </Tooltip>}
                    </> : <span style={{ color: token.colorTextDisabled }}>{placeholder || '请选择客服号'}</span>}
                </> : <>
                    {(value && value?.length > 0) ? <>
                        <Tag
                            closable
                            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
                                    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) || (editSelectedRow && editSelectedRow?.length > 0)) && <div className='selectCorpUserIcon'>
                <CloseCircleFilled
                    className='selectCorpUserIconClear'
                    style={{ fontSize: token.fontSizeIcon, color: token.colorTextSecondary }}
                    onClick={(e) => {
                        e.stopPropagation()
                        if (open) {
                            setEditSelectedRow([])
                        } else {
                            onChange?.([])
                        }
                    }}
                />
            </div>}
        </div>
    </Popover>;
};

export default React.memo(SelectCorpUser);