import {useContext, useEffect, useRef, useState} from "react";
import {GlobalContext} from "../../context/GlobalContext.ts";
import {put, WebSocketBaseUrl} from "../../util/AjaxUtils.ts";
import {Button, Col, Divider, Empty, Row, Space, Spin, Table, TableProps} from "antd";
import {CheckOutlined, ReloadOutlined} from "@ant-design/icons";
import useMessage from "antd/es/message/useMessage";

type PropsType = {
    projId: string;
    projIntroduction?: string;
    projDesc?: string;
}

type ProjModType = {
    name: string,
    desc: string
}

export default function AiHelper(props: PropsType) {
    const globalContext = useContext(GlobalContext);
    const pingTimeout = useRef(-1);
    const ws = useRef<WebSocket | null>(null);
    const [messageApi, messageApiHolder] = useMessage();
    const [projIntroduction, setProjIntroduction] = useState<string>(props.projIntroduction ? props.projIntroduction : '');
    const [newProjIntroduction, setNewProjIntroduction] = useState<string>('');
    const [isProjIntroductionLoading, setIsProjIntroductionLoading] = useState(false);
    const [projDesc, setProjDesc] = useState<string>(props.projDesc ? props.projDesc : '');
    const [newProjDesc, setNewProjDesc] = useState<string>('');
    const [isProjDescLoading, setIsProjDescLoading] = useState(false);
    const [projModArray, setProjModArray] = useState<ProjModType[]>([]);
    const [newProjModArray, setNewProjModArray] = useState<ProjModType[]>([]);
    const [isProjModArrayLoading, setIsProjModArrayLoading] = useState(false);

    const ping = () => {
        clearTimeout(pingTimeout.current);
        pingTimeout.current = setTimeout(() => {
            if (!ws.current) {
                return;
            }
            ws.current.send("PING");
            ping();
        }, 3000);
    }

    const websocket = () => {
        ws.current = new WebSocket(`${WebSocketBaseUrl}/ws/ai/${globalContext.user.userId}`);
        ws.current.onopen = (event) => {
            console.log('打开', event);
            ping();
        }
        ws.current.onmessage = (event) => {
            if (event.data == 'PONE') {
                return;
            }
            const data = JSON.parse(event.data);
            if (data.projId != props.projId) {
                return;
            }
            if (data.type == 'REFRESH_PROJ_INTRODUCTION') {
                setIsProjIntroductionLoading(false);
                setNewProjIntroduction(data.content);
            } else if (data.type == 'REFRESH_PROJ_DESC') {
                setIsProjDescLoading(false);
                setNewProjDesc(data.content);
            } else if (data.type == 'REFRESH_PROJ_MODS') {
                setIsProjModArrayLoading(false);
                const projMods = JSON.parse(data.content) as ProjModType[];
                setNewProjModArray(projMods);
            }
        }
        ws.current.onerror = (event) => {
            console.log('error', event);
        }
        ws.current.onclose = (event) => {
            console.log('close', event);
            websocket()
        }
    }

    const projModColumnArray: TableProps<ProjModType>['columns'] = [
        {title: '序号', dataIndex: 'index', key: 'index', width: 60, align: 'center', render: (value, record, index) => {return index + 1}},
        {title: '模块名称', dataIndex: 'name', key: 'name', width: 200, align: 'center'},
        {title: '模块描述', dataIndex: 'desc', key: 'desc', align: 'center'},
    ];

    const generateProjIntroduction = () => {
        ws.current?.send(JSON.stringify({
            type: 'REFRESH_PROJ_INTRODUCTION',
            projId: props.projId
        }));
        ping();
        setIsProjIntroductionLoading(true);
    }

    const generateProjDesc = () => {
        ws.current?.send(JSON.stringify({
            type: 'REFRESH_PROJ_DESC',
            projId: props.projId
        }));
        ping();
        setIsProjDescLoading(true);
    }

    const generateProjModArray = () => {
        ws.current?.send(JSON.stringify({
            type: 'REFRESH_PROJ_MODS',
            projId: props.projId
        }));
        ping();
        setIsProjModArrayLoading(true);
    }

    /**
     * 保存简介
     */
    const updateProjIntroduction = () => {
        put<any>({
            messageApi,
            url: `/api/proj/update-introduction/${props.projId}`,
            body: {
                content: newProjIntroduction
            },
            onBefore() {
                setIsProjIntroductionLoading(true);
            },
            onSuccess() {
                messageApi.success('保存成功');
                setProjIntroduction(newProjIntroduction);
                setNewProjIntroduction('');
            },
            onFinally() {
                setIsProjIntroductionLoading(false)
            }
        })
    }

    /**
     * 保存详情
     */
    const updateProjDesc = () => {
        put<any>({
            messageApi,
            url: `/api/proj/update-desc/${props.projId}`,
            body: {
                content: newProjDesc
            },
            onBefore() {
                setIsProjDescLoading(true);
            },
            onSuccess() {
                messageApi.success('保存成功').then();
                setProjDesc(newProjDesc);
                setNewProjDesc('');
            },
            onFinally() {
                setIsProjDescLoading(false)
            }
        })
    }

    useEffect(() => {
        if (!props.projId) {
            return;
        }
        websocket();
    }, [globalContext.user.userId, props.projId]);

    return (
        <>
            {messageApiHolder}
            <Row>
                <Col span={24}>
                    <div style={{padding: '5px 0 0 0', fontWeight: 'bold'}}>项目简介</div>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjIntroductionLoading}>
                        <div style={{padding: '5px 0 0 0'}}>
                            {newProjIntroduction ? <Divider orientation="right" plain>原简介</Divider> : <></>}
                            {projIntroduction ? <div>{projIntroduction}</div> : <Empty description="暂无内容"/>}
                            {
                                newProjIntroduction ? (
                                    <>
                                        <Divider orientation="right" plain>新简介</Divider>
                                        <div>{newProjIntroduction}</div>
                                    </>
                                ) : <></>
                            }
                        </div>
                        <div style={{padding: '5px 0 0 0', textAlign: 'center'}}>
                            {
                                newProjIntroduction ? (
                                    <Space>
                                        <Button type="link" style={{cursor: 'pointer'}}
                                                onClick={updateProjIntroduction}><CheckOutlined/> 保存结果</Button>
                                        <Button type="link" style={{cursor: 'pointer'}}
                                                onClick={generateProjIntroduction}><ReloadOutlined/> 重新生成</Button>
                                    </Space>
                                ) : <Button type="link" style={{cursor: 'pointer'}}
                                            onClick={generateProjIntroduction}>AI生成</Button>
                            }
                        </div>
                    </Spin>
                </Col>
                <Col span={24}>
                    <Divider dashed/>
                    <div style={{padding: '5px 0 0 0', fontWeight: 'bold'}}>项目详情</div>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjDescLoading}>
                        <div style={{padding: '5px 0 0 0'}}>
                            {newProjDesc ? <Divider orientation="right" plain>原详情</Divider> : <></>}
                            {projDesc ? <div>{projDesc}</div> : <Empty description="暂无内容"/>}
                            {
                                newProjDesc ? (
                                    <>
                                        <Divider orientation="right" plain>新详情</Divider>
                                        <div>{newProjDesc}</div>
                                    </>
                                ) : <></>
                            }
                        </div>
                        <div style={{padding: '5px 0 0 0', textAlign: 'center'}}>
                            {
                                newProjDesc ? (
                                    <Space>
                                        <Button type="link" style={{cursor: 'pointer'}}
                                                onClick={updateProjDesc}><CheckOutlined/> 保存结果</Button>
                                        <Button type="link" style={{cursor: 'pointer'}}
                                                onClick={generateProjDesc}><ReloadOutlined/> 重新生成</Button>
                                    </Space>
                                ) : <Button type="link" style={{cursor: 'pointer'}}
                                            onClick={generateProjDesc}>AI生成</Button>
                            }
                        </div>
                    </Spin>
                </Col>
                <Col span={24}>
                    <Divider dashed/>
                    <div style={{padding: '5px 0 0 0', fontWeight: 'bold'}}>项目模块</div>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjModArrayLoading}>
                        <div style={{padding: '5px 0 0 0'}}>
                            {newProjModArray.length > 0 ? <Divider orientation="right" plain>原模块</Divider> : <></>}
                            <Table columns={projModColumnArray} dataSource={projModArray} size="small" bordered={true} scroll={{y: 240}} pagination={{pageSize: 20}}/>
                            {
                                newProjModArray.length > 0 ? (
                                    <>
                                        <Divider orientation="right" plain>新模块</Divider>
                                        <Table columns={projModColumnArray} dataSource={newProjModArray} size="small" bordered={true} scroll={{y: 240}} pagination={{pageSize: 20}}/>
                                    </>
                                ) : <></>
                            }
                        </div>
                        <div style={{padding: '5px 0 0 0', textAlign: 'center'}}>
                            {
                                newProjModArray.length > 0 ? (
                                    <Space>
                                        <Button type="link" style={{cursor: 'pointer'}}
                                                onClick={generateProjModArray}><CheckOutlined/> 保存结果</Button>
                                        <Button type="link" style={{cursor: 'pointer'}}
                                                onClick={generateProjModArray}><ReloadOutlined/> 重新生成</Button>
                                    </Space>
                                ) : <Button type="link" style={{cursor: 'pointer'}}
                                            onClick={generateProjModArray}>AI生成</Button>
                            }
                        </div>
                    </Spin>
                </Col>
            </Row>
        </>
    )
}