import { useAjax } from '@/Hook/useAjax';
import { delLocalCorpCsgroupUserApi, GetCustomerServiceGroupUserListProps, getLocalCorpCsgroupUserAllListApi, getLocalCorpCsgroupUserListApi, getUserlogListApi, putUserDecodeApi } from '@/services/adqV3/global';
import { DeleteOutlined, DownOutlined, EditOutlined, PlusOutlined, SearchOutlined, TeamOutlined } from '@ant-design/icons';
import { Button, Card, Drawer, Dropdown, Input, message, Modal, Popconfirm, Select, Space, Table } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import '../../../../../tencentAdPutIn/index.less';
import SettingsEnterprise from './settingsEnterprise';
import style from '@/pages/launchSystemV3/tencentAdPutIn/create/index.less';
import { POOLTYPE, POOLTYPEEle } from '../../const';
import GroupUserEdit from './groupUserEdit';
import UserDecodeLog from './userDecodeLog';

interface GroupUserInfoProps {
    groupData: { [x: string]: any };
    adAccountId?: number;
}

/**
 * 客服组成员信息组件
 * @param param0 
 * @returns 
 */
const GroupUserInfo: React.FC<GroupUserInfoProps> = ({ groupData: { id: localCsgroupId, localCorpId, csgroupName, tencentCorpName, tencentCorpId }, adAccountId }) => {

    /********************************************/
    const [visible, setVisible] = React.useState<boolean>(false);
    const [addData, setAddData] = React.useState<{ visible: boolean, data: any }>({ visible: false, data: undefined });
    const [queryForm, setQueryForm] = useState<GetCustomerServiceGroupUserListProps>({ pageNum: 1, pageSize: 20, localCsgroupId, localCorpId });
    const [queryParamsNew, setQueryParamsNew] = useState<GetCustomerServiceGroupUserListProps>({ pageNum: 1, pageSize: 20, localCsgroupId, localCorpId });
    const [selectedRows, setSelectedRows] = useState<any[]>([])
    const [userEditData, setUserEditData] = useState<{ visible: boolean, idList: number[] }>();
    const [logData, setLogData] = useState<{ visible: boolean, data: any }>();
    const [logParams, setLogParams] = useState<{ pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 20 })
    const [decodeVisible, setDecodeVisible] = useState<boolean>(false)

    const getLocalCorpCsgroupUserList = useAjax((params) => getLocalCorpCsgroupUserListApi(params))
    const getUserlogList = useAjax((params) => getUserlogListApi(params))
    const getLocalCorpCsgroupUserAllList = useAjax((params) => getLocalCorpCsgroupUserAllListApi(params))
    const delLocalCorpCsgroupUser = useAjax((params) => delLocalCorpCsgroupUserApi(params))
    const putUserDecode = useAjax((params) => putUserDecodeApi(params))
    /********************************************/

    const handleUser = useCallback(() => {
        setVisible(true)
    }, [])

    useEffect(() => {
        if (visible) {
            getLocalCorpCsgroupUserList.run({ ...queryParamsNew, localCsgroupId, localCorpId })
        }
    }, [visible, localCsgroupId, localCorpId, queryParamsNew])

    const add = useCallback(() => {
        getLocalCorpCsgroupUserAllList.run({ localCsgroupId }).then((res) => {
            console.log('获取客服组成员列表', res);
            setAddData({
                visible: true,
                data: {
                    corpName: tencentCorpName,
                    tencentCorpId,
                    groupId: localCsgroupId,
                    groupName: csgroupName,
                    userInfoList: res?.map((item: { localCorpUserName: any; tencentCorpUserId: any; }) => ({ userName: item.localCorpUserName, userId: item.tencentCorpUserId })) || []
                }
            });
        })
    }, [csgroupName, tencentCorpName, tencentCorpId, localCsgroupId, csgroupName])

    /** 删除客服 */
    const delUser = (idList: number[], groupId?: number) => {
        delLocalCorpCsgroupUser.run({ localCsgroupId: localCsgroupId || groupId, idList }).then((res) => {
            if (res) {
                message.success('删除成功');
                getLocalCorpCsgroupUserList.refresh();
                setSelectedRows([]);
            }
        })
    }

    const userEdit = () => {
        setUserEditData({ visible: true, idList: selectedRows.map(item => item.id) });
    }

    const handleLog = (data: any) => {
        setLogData({ visible: true, data })
    }

    useEffect(() => {
        if (logData?.visible) {
            getUserlogList.run({ ...logParams, id: logData.data.id })
        }
    }, [logParams, logData])

    const handleSync = () => {
        const hide = message.loading({ content: '操作中...', key: 'sync' });
        putUserDecode.run({ localCsgroupId }).then((res) => {
            hide();
            if (res) {
                message.success('操作成功');
            }
        }).catch(() => hide())
    }

    return <>
        <Button icon={<TeamOutlined />} style={{ border: 'none', fontSize: 12, padding: 0 }} size='small' onClick={() => handleUser()}>成员</Button>
        {visible && <Drawer
            title={<strong style={{ fontSize: 20 }}>{csgroupName} 客服组成员</strong>}
            open={visible}
            onClose={() => setVisible(false)}
            width={1200}
            headerStyle={{ padding: '10px 16px' }}
            maskClosable={false}
            className={`modalResetCss targetingSelect`}
        >
            <Card className="cardResetCss" bodyStyle={{ padding: 0, height: 'calc(100vh - 70px)', overflow: 'hidden', overflowY: 'auto' }}>
                <div className={style.template} style={{ height: '100%' }}>
                    <div className={style.template_center}>
                        <div className="flexSpaceBetween" style={{ marginBottom: 10 }}>
                            <Space>
                                <Input
                                    placeholder="请输入客服名称"
                                    value={queryForm?.localCorpUserName}
                                    allowClear
                                    onChange={(e) => setQueryForm({ ...queryForm, localCorpUserName: e.target.value })}
                                />
                                <Select
                                    showSearch
                                    placeholder="归属客服池"
                                    filterOption={(input, option) =>
                                        ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                    }
                                    style={{ width: 140 }}
                                    allowClear
                                    value={queryForm?.poolType}
                                    onChange={(e) => {
                                        setQueryForm({ ...queryForm, poolType: e, pageNum: 1 })
                                    }}
                                    options={Object.keys(POOLTYPE).map((key) => ({ label: POOLTYPE[key as keyof typeof POOLTYPE], value: key }))}
                                />
                                <Button type="primary" icon={<SearchOutlined />} loading={getLocalCorpCsgroupUserList.loading} onClick={() => setQueryParamsNew({ ...queryForm, pageNum: 1 })}>搜索</Button>
                            </Space>
                            <Space>
                                <Dropdown menu={{
                                    items: [
                                        {
                                            label: '解密同步',
                                            key: '1'
                                        },
                                        {
                                            label: '解密查询',
                                            key: '2'
                                        }
                                    ],
                                    onClick: ({ key }) => {
                                        switch (key) {
                                            case '1':
                                                handleSync()
                                                break
                                            case '2':
                                                setDecodeVisible(true)
                                                break
                                            default:
                                                break
                                        }
                                    }
                                }}>
                                    <Button>
                                        <Space>
                                            服务商授权
                                            <DownOutlined />
                                        </Space>
                                    </Button>
                                </Dropdown>
                                <Button type="primary" disabled={selectedRows.length === 0} icon={<EditOutlined />} onClick={userEdit}>修改</Button>
                                <Popconfirm
                                    title="确定删除?"
                                    onConfirm={() => {
                                        delUser(selectedRows.map(item => item.id), selectedRows[0]?.localCsgroupId)
                                    }}
                                    disabled={selectedRows.length === 0}
                                >
                                    <Button type="primary" disabled={selectedRows.length === 0} danger icon={<DeleteOutlined />} loading={delLocalCorpCsgroupUser.loading}>删除</Button>
                                </Popconfirm>
                                {localCsgroupId && <Button type="primary" icon={<PlusOutlined />} loading={getLocalCorpCsgroupUserAllList.loading} onClick={add}>成员加减</Button>}
                            </Space>
                        </div>
                        <Table
                            columns={[
                                {
                                    title: '客服名称',
                                    dataIndex: 'localCorpUserName',
                                    key: 'localCorpUserName',
                                    width: 250,
                                    ellipsis: true,
                                    fixed: 'left',
                                    render(value, records) {
                                        return <span style={{ fontSize: 12 }}>{value}（{records.localCorpUserId}）</span>
                                    }
                                },
                                {
                                    title: '腾讯端客服ID',
                                    dataIndex: 'tencentCorpUserId',
                                    key: 'tencentCorpUserId',
                                    width: 150,
                                    ellipsis: true,
                                    render(value) {
                                        return <span style={{ fontSize: 12 }}>{value}</span>
                                    }
                                },
                                {
                                    title: '归属客服池',
                                    dataIndex: 'poolType',
                                    key: 'poolType',
                                    width: 120,
                                    align: 'center',
                                    render(value) {
                                        return <span style={{ fontSize: 12 }}>{POOLTYPEEle[value as keyof typeof POOLTYPEEle]}</span>
                                    }
                                },
                                {
                                    title: '客服号单日限制加粉数量',
                                    dataIndex: 'limitAddFansOfDay',
                                    key: 'limitAddFansOfDay',
                                    width: 110,
                                    align: 'center',
                                    render(value) {
                                        return <span style={{ fontSize: 12 }}>{(value || value === 0) ? value : '--'}</span>
                                    }
                                },
                                {
                                    title: '归属客服组',
                                    dataIndex: 'localCsgroupName',
                                    key: 'localCsgroupName',
                                    width: 200,
                                    ellipsis: true,
                                    render(value) {
                                        return <span style={{ fontSize: 12 }}>{value}</span>
                                    }
                                },
                                {
                                    title: '归属客服组ID',
                                    dataIndex: 'localCsgroupId',
                                    key: 'localCsgroupId',
                                    width: 90,
                                    ellipsis: true,
                                    render(value) {
                                        return <span style={{ fontSize: 12 }}>{value}</span>
                                    }
                                },
                                {
                                    title: '创建时间',
                                    dataIndex: 'createTime',
                                    key: 'createTime',
                                    width: 140,
                                    render(value) {
                                        return <span style={{ fontSize: 12 }}>{value}</span>
                                    }
                                },
                                {
                                    title: '更新时间',
                                    dataIndex: 'updateTime',
                                    key: 'updateTime',
                                    width: 140,
                                    render(value) {
                                        return <span style={{ fontSize: 12 }}>{value}</span>
                                    }
                                },
                                {
                                    title: '操作',
                                    dataIndex: 'cz',
                                    key: 'cz',
                                    width: 85,
                                    align: 'center',
                                    fixed: 'right',
                                    render(_, records) {
                                        return <Space>
                                            <a onClick={() => { handleLog(records) }}>日志</a>
                                            <Popconfirm
                                                title="确定删除?"
                                                onConfirm={() => {
                                                    delUser([records.id], records.localCsgroupId)
                                                }}
                                            >
                                                <a style={{ color: 'red' }}>删除</a>
                                            </Popconfirm>
                                        </Space>
                                    }
                                },
                            ]}
                            dataSource={getLocalCorpCsgroupUserList.data?.records}
                            size="small"
                            loading={getLocalCorpCsgroupUserList?.loading}
                            scroll={{ y: 600 }}
                            rowKey={'id'}
                            pagination={{
                                total: getLocalCorpCsgroupUserList.data?.total,
                                defaultPageSize: 20,
                                current: getLocalCorpCsgroupUserList.data?.current,
                                pageSize: getLocalCorpCsgroupUserList.data?.size
                            }}
                            rowSelection={{
                                selectedRowKeys: selectedRows.map(item => item.id),
                                onSelect: (record, selected) => {
                                    if (selected) {
                                        selectedRows.push({ ...record })
                                        setSelectedRows([...selectedRows])
                                    } else {
                                        let newSelectAccData = selectedRows.filter((item) => item.id !== record.id)
                                        setSelectedRows([...newSelectAccData])
                                    }
                                },
                                onSelectAll: (selected, _, changeRows) => {
                                    if (selected) {
                                        let newSelectAccData = [...selectedRows]
                                        changeRows.forEach((item) => {
                                            let index = newSelectAccData.findIndex((ite) => ite.id === item.id)
                                            if (index === -1) {
                                                let data: any = { ...item }
                                                newSelectAccData.push(data)
                                            }
                                        })
                                        setSelectedRows([...newSelectAccData])
                                    } else {
                                        let newSelectAccData = selectedRows.filter((item) => {
                                            let index = changeRows.findIndex((ite) => ite.id === item.id)
                                            if (index !== -1) {
                                                return false
                                            } else {
                                                return true
                                            }
                                        })
                                        setSelectedRows([...newSelectAccData])
                                    }
                                }
                            }}
                            onChange={(pagination) => {
                                const { current, pageSize } = pagination
                                setQueryForm({ ...queryForm, pageNum: current as number, pageSize: pageSize as number || 20 })
                                setQueryParamsNew({ ...queryParamsNew, pageNum: current as number, pageSize: pageSize as number || 20 })
                            }}
                        />
                    </div>
                </div>
            </Card>

            {/* 设置修改 */}
            {addData.visible && <SettingsEnterprise
                {...addData}
                adAccountId={adAccountId as number}
                onClose={() => setAddData({ visible: false, data: undefined })}
                onChange={() => {
                    getLocalCorpCsgroupUserList.refresh()
                    setAddData({ visible: false, data: undefined })
                }}
            />}

            {/* 修改客服 */}
            {userEditData?.visible && <GroupUserEdit
                {...userEditData}
                onChange={() => {
                    setUserEditData(undefined)
                    getLocalCorpCsgroupUserList.refresh();
                }}
                onClose={() => setUserEditData(undefined)}
            />}
        </Drawer>}

        {logData?.visible && <Modal
            title={<strong>{logData?.data?.localCorpUserName} 日志</strong>}
            open={logData?.visible}
            onCancel={() => setLogData(undefined)}
            footer={null}
            className='modalResetCss'
        >
            <Table
                columns={[
                    {
                        title: '客服名称',
                        dataIndex: 'localCorpUserName',
                        key: 'localCorpUserName',
                        width: 220,
                        ellipsis: true,
                        render(value, records) {
                            return <span style={{ fontSize: 12 }}>{value}（{records.localCorpUserId}）</span>
                        }
                    },
                    {
                        title: '归属客服池',
                        dataIndex: 'poolType',
                        key: 'poolType',
                        width: 100,
                        align: 'center',
                        render(value) {
                            return <span style={{ fontSize: 12 }}>{POOLTYPEEle[value as keyof typeof POOLTYPEEle]}</span>
                        }
                    },
                    {
                        title: '创建时间',
                        dataIndex: 'createTime',
                        key: 'createTime',
                        width: 140,
                        render(value) {
                            return <span style={{ fontSize: 12 }}>{value}</span>
                        }
                    }
                ]}
                dataSource={getUserlogList.data?.records}
                size="small"
                loading={getUserlogList?.loading}
                scroll={{ y: 500 }}
                rowKey={'id'}
                pagination={{
                    total: getUserlogList.data?.total,
                    defaultPageSize: 20,
                    current: getUserlogList.data?.current,
                    pageSize: getUserlogList.data?.size
                }}
                onChange={(pagination) => {
                    const { current, pageSize } = pagination
                    setLogParams({ ...logParams, pageNum: current as number, pageSize: pageSize as number || 20 })
                }}
            />
        </Modal>}

        {decodeVisible && <UserDecodeLog
            visible={decodeVisible}
            onClose={() => setDecodeVisible(false)}
            localCsgroupId={localCsgroupId}
        />}
    </>
};

export default React.memo(GroupUserInfo);