import React, { useEffect, useState } from 'react';
import { Modal, Button, App, Input, Select, Table } from 'antd';
import { getCorpUserChatListApi, getCorpUserChatListProps } from '../../API/groupLeaderManage';
import { useAjax } from '@/Hook/useAjax';
import { SearchOutlined } from '@ant-design/icons';
import { getAdAccountAllOfMember } from '@/API/global';
import { STATUSENUM } from '.';

interface SelectGroupLeaderModalProps {
    corpIds: string[]
    visible?: boolean;
    value?: any[]
    onChange?: (value: any[]) => void;
    onClose?: () => void;
}

const SelectGroupLeaderModal: React.FC<SelectGroupLeaderModalProps> = ({ corpIds, visible, value, onChange, onClose }) => {

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

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

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

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

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

    return <Modal
        title={<strong>请选择群主</strong>}
        open={visible}
        width={900}
        onCancel={onClose}
        onOk={handleOk}
    >
        <div className='selectCorpUserBody' style={{ width: '100%' }}>
            <div className='selectCorpUserBody_search'>
                <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={'corpUserId'}
                    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.corpUserId),
                        onSelect: (record, 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)
                            }
                        }
                    }}
                />
            </div>
        </div>
    </Modal>;
};

export default SelectGroupLeaderModal;