import useNewToken from '@/Hook/useNewToken';
import { App, Button, Input, Modal, 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';
import { RowSelectionType } from 'antd/es/table/interface';

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

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

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

    return <>
        <div
            className='selectCorpUser'
            style={{
                border: `1px solid ${token.colorBorder}`,
                padding: `0px ${token.paddingXS}px`,
                borderRadius: token.borderRadius,
                height: token.controlHeight,
                width: width || '100%',
            }}
            onClick={() => setOpen(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>

        {open && <SelectCorpUserModal
            {...itr}
            value={value}
            open={open}
            placeholder={placeholder}
            onClose={() => setOpen(false)}
            onChange={(values) => {
                onChange?.(values)
                setOpen(false)
            }}
        />}
    </>
};

interface SelectCorpUserModalProps extends Props {
    open?: boolean
    onClose?: () => void
}

const SelectCorpUserModal: React.FC<SelectCorpUserModalProps> = React.memo(({ open, type = 'checkbox', value, corpId, onClose, onChange, placeholder }) => {

    /*******************************************/
    const [queryForm, setQueryForm] = useState<CORP_USER_ASSIGN_API.GetCorpUserProps>({ pageNum: 1, pageSize: 20, status: 1 })
    const [queryFormNew, setQueryFormNew] = useState<CORP_USER_ASSIGN_API.GetCorpUserProps>({ pageNum: 1, pageSize: 20, status: 1 })
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])
    const { message } = App.useApp()

    const allOfMember = useAjax(() => getAdAccountAllOfMember())
    const getCorpUser = useAjax((params) => getCorpUserApi(params))
    const getGroupList = useAjax(() => getGroupListApi())
    /*******************************************/

    useEffect(() => {
        if (corpId) {
            setQueryFormNew({ ...queryFormNew, corpIds: corpId as any })
            setQueryForm({ ...queryForm, corpIds: corpId as any })
        }
    }, [corpId])

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

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

    useEffect(() => {
        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
        }
        if (corpId && !(queryForm?.corpIds?.length > 0)) {
            return
        }
        getCorpUser.run(params)

    }, [queryForm, corpId])

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

    return <Modal
        title={<strong>{placeholder}</strong>}
        open={open}
        width={1050}
        onCancel={onClose}
        onOk={handleOk}
    >
        <div className='selectCorpUserBody' style={{ width: '100%' }}>
            <div className='selectCorpUserBody_search'>
                <Input style={{ width: 150 }} disabled={!!corpId} onChange={(e) => setQueryFormNew({ ...queryFormNew, corpIds: e.target.value as any })} value={queryFormNew?.corpIds} placeholder="企微ID（多个，,空格换行）" allowClear />
                <Input style={{ width: 150 }} onChange={(e) => setQueryFormNew({ ...queryFormNew, corpUserName: e.target.value as any })} value={queryFormNew?.corpUserName} placeholder="客服号名称" 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: 250 }}
                    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' ? {
                        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)
                            }
                        }
                    } : {
                        type: 'radio',
                        selectedRowKeys: editSelectedRow?.map(item => item.corpUserId),
                        onChange(_, selectedRows) {
                            setEditSelectedRow(selectedRows)
                        },
                    }}
                    onChange={(pagination) => {
                        setQueryForm({ ...queryForm, pageNum: pagination.current || 1, pageSize: pagination.pageSize || 20 })
                    }}
                />
            </div>
        </div>
    </Modal>
});

export default React.memo(SelectCorpUser);