import React, { useEffect, useState } from 'react';
import { getBindDetailListApi, syncCorpChatRobotApi, unbindCorpUserChatApi } from '../../API/groupLeaderManage';
import { useAjax } from '@/Hook/useAjax';
import { App, Button, Flex, Modal, Popconfirm, Table, Typography } from 'antd';
import { ForkOutlined, PullRequestOutlined, RetweetOutlined } from '@ant-design/icons';
import BindUser from './bindUser';
const { Paragraph } = Typography;

interface BindDetailsProps {
    bindType: 1 | 2  // 1 客服号 2 机器人号
    data: any
}


/**
 * 绑定详情
 * @param param0 
 * @returns 
 */
const BindDetails: React.FC<BindDetailsProps> = ({ bindType, data }) => {

    /***********************************************/
    const [visible, setVisible] = useState<boolean>(false)
    /***********************************************/


    return <>
        <a onClick={() => setVisible(true)}>详情</a>
        {visible && <BindDetailsModal
            bindType={bindType}
            data={data}
            visible={visible}
            onClose={() => setVisible(false)}
        />}
    </>
};


interface BindDetailsModalProps extends BindDetailsProps {
    visible?: boolean
    onClose?: () => void
}

const BindDetailsModal: React.FC<BindDetailsModalProps> = React.memo(({ visible, onClose, bindType, data }) => {

    /*********************************/
    const { message } = App.useApp()
    const [bindVisible, setBindVisible] = useState<boolean>(false)
    const [editSelectedRow, setEditSelectedRow] = useState<any[]>([])

    const getBindDetailList = useAjax((params) => getBindDetailListApi(params))
    const unbindCorpUserChat = useAjax((params) => unbindCorpUserChatApi(params))
    const syncCorpChatRobot = useAjax((params) => syncCorpChatRobotApi(params))
    /*********************************/

    useEffect(() => {
        getBindDetailList.run({
            corpUserChatId: data.id,
            bindType
        })
    }, [])

    const handleUnbind = () => {
        unbindCorpUserChat.run({
            bindType,
            corpUserChatId: data.id,
            corpUserList: editSelectedRow.map(item => {
                const { corpId, corpUserId, transferExternalUserId } = item
                return { corpId, corpUserId, transferExternalUserId }
            })
        }).then((res) => {
            if (res?.data) {
                message.success('解绑成功')
                getBindDetailList.refresh()
                setEditSelectedRow([])
            }
        })
    }

    // 同步
    const syncRobot = () => {
        syncCorpChatRobot.run({ corpId: data.corpId, corpUserId: data.corpUserId, robotIdList: editSelectedRow.map(item => item?.transferExternalUser?.externalUserId) }).then((res) => {
            if (res?.data) {
                message.success('同步成功')
                setEditSelectedRow([])
            }
        })
    }

    return <Modal
        title={<strong>《{data.corpName}》群主《{data.name}》{bindType === 1 ? '客服号' : '机器人号'}详情</strong>}
        open={visible}
        onCancel={onClose}
        width={900}
        footer={null}
    >
        <Flex style={{ marginBottom: 10 }} gap={10}>
            <Button loading={getBindDetailList.loading} onClick={() => getBindDetailList.refresh()}>刷新</Button>
            <Button type="primary" icon={<ForkOutlined />} onClick={() => setBindVisible(true)}>绑定{bindType === 1 ? '客服号' : '机器人号'}</Button>
            {bindType === 2 && <Button type="primary" disabled={editSelectedRow?.length === 0} icon={<RetweetOutlined />} onClick={() => syncRobot()}>同步机器人号</Button>}
            <Popconfirm
                title="确定解绑？"
                onConfirm={handleUnbind}
                disabled={editSelectedRow?.length === 0}
            >
                <Button type="primary" danger disabled={editSelectedRow?.length === 0} icon={<PullRequestOutlined />}>解绑{bindType === 1 ? '客服号' : '机器人号'}</Button>
            </Popconfirm>
        </Flex>
        <Table
            columns={[
                {
                    title: (bindType === 1 ? '客服号' : '机器人号') + '企业',
                    dataIndex: 'corpUser',
                    key: 'corpUser',
                    width: 150,
                    render: (value) => {
                        return <div>
                            <Paragraph style={{ margin: 0 }} ellipsis>{value?.corpName || '--'}（{value?.corpId || '--'}）</Paragraph>
                        </div>
                    }
                },
                {
                    title: (bindType === 1 ? '客服号' : '机器人号'),
                    dataIndex: 'corpUser',
                    key: 'name',
                    width: 150,
                    render: (value) => {
                        return <div>
                            <Paragraph style={{ margin: 0 }} ellipsis>{value?.name || '--'}（{value?.corpUserId || '--'}）</Paragraph>
                        </div>
                    }
                },
                {
                    title: '外部联系人',
                    dataIndex: 'transferExternalUser',
                    key: 'transferExternalUser',
                    width: 150,
                    render: (value) => {
                        return <div>
                            <Paragraph style={{ margin: 0 }} ellipsis>{value?.remark || '--'}（{value?.externalUserId || '--'}）</Paragraph>
                        </div>
                    }
                },
            ]}
            dataSource={getBindDetailList?.data?.data}
            rowKey="id"
            loading={getBindDetailList.loading}
            scroll={{ y: 400 }}
            rowSelection={{
                type: 'checkbox',
                selectedRowKeys: editSelectedRow?.map(item => item.id),
                onSelect: (record: { id: any; }, selected: any) => {
                    if (selected) {
                        setEditSelectedRow([...editSelectedRow, record])
                    } else {
                        setEditSelectedRow(editSelectedRow?.filter(item => item.id !== record.id))
                    }
                },
                onSelectAll: (selected: any, _: any, changeRows: any[]) => {
                    if (selected) {
                        setEditSelectedRow([...editSelectedRow, ...changeRows])
                    } else {
                        let newArr = editSelectedRow?.filter(item => changeRows.every(i => i?.id !== item?.id))
                        setEditSelectedRow(newArr)
                    }
                }
            }}
        />
        {/* 绑定用户 */}
        {bindVisible && <BindUser
            bindType={bindType}
            data={data}
            visible={bindVisible}
            onChange={() => {
                setBindVisible(false)
                getBindDetailList.refresh()
            }}
            onClose={() => {
                setBindVisible(false)
            }}
        />}
    </Modal>
})

export default React.memo(BindDetails);