import { App, Button, Card, Input, Pagination, Popconfirm, Select, Table, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import style from '../bookLink/index.less'
import { useSize } from 'ahooks';
import { useAjax } from '@/Hook/useAjax';
import { delCorpUserChatApi, getCorpUserChatListApi, getCorpUserChatListProps } from '../../API/groupLeaderManage';
import { GroupLeaderTableConfig } from './tableConfig';
import SearchBox from '../../components/searchBox';
import { SearchOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { getAdAccountAllOfMember, getCorpAllListApi } from '@/API/global';
import './global.less'
import AddGL from './addGL';

export const STATUSENUM = {
    1: <Tag color="success">已激活</Tag>,
    2: <Tag color="error">已禁用</Tag>,
    4: <Tag color="warning">未激活</Tag>,
    5: <Tag color="error">退出企业</Tag>
}

/**
 * 群主号管理
 * @returns 
 */
const GroupLeaderManage: React.FC = () => {

    /*******************************************/
    const { message } = App.useApp();
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref)
    const [queryParams, setQueryParams] = useState<getCorpUserChatListProps>({ pageNum: 1, pageSize: 20 })
    const [queryParamsNew, setQueryParamsNew] = useState<getCorpUserChatListProps>({ pageNum: 1, pageSize: 20 })
    const [visible, setVisible] = useState<boolean>(false)
    const [selectedRows, setselectedRows] = useState<any[]>([])

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

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

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

    const handleDel = () => {
        delCorpUserChat.run(selectedRows.map(item => item.id)).then(res => {
            setselectedRows([])
            getCorpUserChatList.refresh()
            message.success('删除成功')
        })
    }

    return <Card
        styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: 'calc(100vh - 88px)' } }}
    >
        <div>
            <SearchBox
                bodyPadding={`10px 16px 4px`}
                buttons={<>
                    <Button type="primary" onClick={() => {
                        setQueryParamsNew({ ...queryParams, pageNum: 1 })
                    }} loading={getCorpUserChatList.loading} icon={<SearchOutlined />}>搜索</Button>
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => setVisible(true)}>新增群主号</Button>
                    <Popconfirm
                        title="确认删除?"
                        onConfirm={handleDel}
                        disabled={selectedRows.length === 0}
                    >
                        <Button type="primary" danger icon={<DeleteOutlined />} disabled={selectedRows.length === 0}>删除</Button>
                    </Popconfirm>

                </>}
            >
                <>
                    <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 onChange={(e) => setQueryParams({ ...queryParams, corpUserName: e.target.value as any })} value={queryParams?.corpUserName} placeholder="客服号名称" allowClear />
                    <Input 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 }]}
                    />
                </>
            </SearchBox>
        </div>
        <div className={style.bookLinkTable} ref={ref}>
            <Table
                dataSource={getCorpUserChatList?.data?.data?.records}
                columns={GroupLeaderTableConfig()}
                bordered
                className='resetTable'
                pagination={false}
                rowKey={'id'}
                size='small'
                loading={getCorpUserChatList?.loading}
                scroll={{ y: size?.height && ref.current ? size?.height - ref.current.querySelector('.ant-table-thead').clientHeight : 300 }}
                rowSelection={{
                    selectedRowKeys: selectedRows?.map((item: any) => item?.id),
                    onSelect: (record: { id: string }, selected: boolean) => {
                        let newData = JSON.parse(JSON.stringify(selectedRows))
                        if (selected) {
                            newData.push({ ...record })
                        } else {
                            newData = newData.filter((item: { id: string }) => item.id !== record.id)
                        }
                        setselectedRows(newData)
                    },
                    onSelectAll: (selected: boolean, _: { id: string }[], changeRows: { id: string }[]) => {
                        let newData = JSON.parse(JSON.stringify(selectedRows || '[]'))
                        if (selected) {
                            changeRows.forEach((item: { id: string }) => {
                                const index = newData.findIndex((ite: { id: string }) => ite.id === item.id)
                                if (index === -1) {
                                    newData.push(item)
                                }
                            })
                        } else {
                            const newSelectAccData = newData.filter((item: { id: string }) => {
                                const index = changeRows.findIndex((ite: { id: string }) => ite.id === item.id)
                                if (index !== -1) {
                                    return false
                                } else {
                                    return true
                                }
                            })
                            newData = newSelectAccData
                        }
                        setselectedRows(newData)
                    }
                }}
            />
        </div>
        <div className={style.bookLinkPagination}>
            <Pagination
                size="small"
                total={getCorpUserChatList?.data?.data?.total || 0}
                showSizeChanger
                showQuickJumper
                pageSize={getCorpUserChatList?.data?.data?.size || 20}
                current={getCorpUserChatList?.data?.data?.current || 1}
                onChange={(page: number, pageSize: number) => {
                    // ref.current?.scrollTo({ top: 0 })
                    setTimeout(() => {
                        setQueryParams({ ...queryParams, pageNum: page, pageSize })
                        setQueryParamsNew({ ...queryParamsNew, pageNum: page, pageSize })
                    }, 50)
                }}
                showTotal={(total: number) => <span style={{ fontSize: 12 }}>共 {total} 条</span>}
            />
        </div>

        {/* 新增群主号 */}
        {visible && <AddGL
            visible={visible}
            onChange={() => {
                setVisible(false)
                getCorpUserChatList.refresh()
            }}
            onClose={() => {
                setVisible(false)
            }}
        />}
    </Card>
};

export default GroupLeaderManage;