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, EditOutlined, ReloadOutlined} from "@ant-design/icons";
import useMessage from "antd/es/message/useMessage";
import TextArea from "antd/es/input/TextArea";

type PropsType = {
    projId: string;
    projIntroduction?: string;
    projDesc?: string;
    projMods?: ProjModType[];
}

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 [isProjIntroductionEdit, setIsProjIntroductionEdit] = useState<boolean>(false);
    const [isNewProjIntroductionEdit, setIsNewProjIntroductionEdit] = useState<boolean>(false);
    const [isProjIntroductionLoading, setIsProjIntroductionLoading] = useState(false);

    const [projDesc, setProjDesc] = useState<string>(props.projDesc ? props.projDesc : '');
    const [newProjDesc, setNewProjDesc] = useState<string>('');
    const [isProjDescEdit, setIsProjDescEdit] = useState<boolean>(false);
    const [isNewProjDescEdit, setIsNewProjDescEdit] = useState<boolean>(false);
    const [isProjDescLoading, setIsProjDescLoading] = useState(false);

    const [projModArray, setProjModArray] = useState<ProjModType[]>(props.projMods ? props.projMods : []);
    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 = (content: string) => {
        put<any>({
            messageApi,
            url: `/api/proj/update-introduction/${props.projId}`,
            body: {
                content: content
            },
            onBefore() {
                setIsProjIntroductionLoading(true);
            },
            onSuccess() {
                messageApi.success('保存成功');
                setProjIntroduction(content);
                setNewProjIntroduction('');
            },
            onFinally() {
                setIsProjIntroductionLoading(false)
            }
        })
    }

    /**
     * 保存详情
     */
    const updateProjDesc = (content: string) => {
        put<any>({
            messageApi,
            url: `/api/proj/update-desc/${props.projId}`,
            body: {
                content: content
            },
            onBefore() {
                setIsProjDescLoading(true);
            },
            onSuccess() {
                messageApi.success('保存成功').then();
                setProjDesc(content);
                setNewProjDesc('');
            },
            onFinally() {
                setIsProjDescLoading(false)
            }
        })
    }
    /**
     * 保存模块
     */
    const updateProjModArray = () => {
        put<any>({
            messageApi,
            url: `/api/proj-mod/update-mods/${props.projId}`,
            body: {
                list: newProjModArray
            },
            onBefore() {
                setIsProjModArrayLoading(true);
            },
            onSuccess() {
                messageApi.success('保存成功').then();
                setProjModArray(newProjModArray);
                setNewProjModArray([]);
            },
            onFinally() {
                setIsProjModArrayLoading(false)
            }
        })
    }

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

    /**
     * 项目简介按钮
     */
    const renderNewProjIntroductionBtn = () => {
        if(!newProjIntroduction) {
            if(!isProjIntroductionEdit) {
                return (
                    <Space>
                        <Button type="link" style={{cursor: 'pointer'}} onClick={generateProjIntroduction}>AI生成</Button>
                        {
                            projIntroduction ? (
                                <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                                    setIsProjIntroductionEdit(true);
                                }}><EditOutlined /> 编辑</Button>
                            ) : <></>
                        }
                    </Space>
                )
            }
            return (
                <Space>
                    <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                        setIsProjIntroductionEdit(false);
                        updateProjIntroduction(projIntroduction);
                    }}><CheckOutlined/> 保存结果</Button>
                </Space>
            )
        }
        if(!isNewProjIntroductionEdit) {
            return (
                <Space>
                    <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                        updateProjIntroduction(newProjIntroduction);
                    }}><CheckOutlined/> 保存结果</Button>
                    <Button type="link" style={{cursor: 'pointer'}} onClick={generateProjIntroduction}><ReloadOutlined/> 重新生成</Button>
                    <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                        setIsNewProjIntroductionEdit(true);
                    }}><EditOutlined /> 编辑</Button>
                </Space>
            )
        }
        return (
            <Space>
                <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                    setIsNewProjIntroductionEdit(false);
                }}><CheckOutlined/> 确定</Button>
            </Space>
        )
    }
    /**
     * 项目简介按钮
     */
    const renderNewProjDescBtn = () => {
        if(!newProjDesc) {
            if(!isProjDescEdit) {
                return (
                    <Space>
                        <Button type="link" style={{cursor: 'pointer'}} onClick={generateProjDesc}>AI生成</Button>
                        {
                            projIntroduction ? (
                                <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                                    setIsProjDescEdit(true);
                                }}><EditOutlined /> 编辑</Button>
                            ) : <></>
                        }
                    </Space>
                )
            }
            return (
                <Space>
                    <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                        setIsProjDescEdit(false);
                        updateProjDesc(projDesc);
                    }}><CheckOutlined/> 保存结果</Button>
                </Space>
            )
        }
        if(!isNewProjDescEdit) {
            return (
                <Space>
                    <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                        updateProjDesc(newProjDesc);
                    }}><CheckOutlined/> 保存结果</Button>
                    <Button type="link" style={{cursor: 'pointer'}} onClick={generateProjDesc}><ReloadOutlined/> 重新生成</Button>
                    <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                        setIsNewProjDescEdit(true);
                    }}><EditOutlined /> 编辑</Button>
                </Space>
            )
        }
        return (
            <Space>
                <Button type="link" style={{cursor: 'pointer'}} onClick={() => {
                    setIsNewProjDescEdit(false);
                }}><CheckOutlined/> 确定</Button>
            </Space>
        )
    }

    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 ? (
                                isProjIntroductionEdit ? <TextArea rows={10} value={projIntroduction} placeholder="请编辑简介" maxLength={1500} onChange={(e) => {
                                        setProjIntroduction(e.currentTarget.value);
                                    }}/> 
                                : <div>{projIntroduction}</div>
                            ) : <Empty description="暂无内容"/>}
                            {
                                newProjIntroduction ? (
                                    <>
                                        <Divider orientation="right" plain>新简介</Divider>
                                        {
                                            isNewProjIntroductionEdit ? (
                                                <TextArea rows={10} value={newProjIntroduction} placeholder="请编辑简介" maxLength={1500} onChange={(e) => {
                                                    setNewProjIntroduction(e.currentTarget.value);
                                                }}/>
                                            ) : <div>{newProjIntroduction}</div>
                                        }
                                    </>
                                ) : <></>
                            }
                        </div>
                        <div style={{padding: '5px 0 0 0', textAlign: 'center'}}>
                            {renderNewProjIntroductionBtn()}
                        </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 ? (
                                isProjDescEdit ?
                                    <TextArea rows={10} value={projDesc} placeholder="请编辑详情"
                                              maxLength={1500} onChange={(e) => {
                                        setProjDesc(e.currentTarget.value);
                                    }}/>
                                    : <div>{projDesc}</div>
                            ) : <Empty description="暂无内容"/>}
                            {
                                newProjDesc ? (
                                    <>
                                        <Divider orientation="right" plain>新详情</Divider>
                                        {
                                            isNewProjDescEdit ? (
                                                <TextArea rows={10} value={newProjDesc} placeholder="请编辑简介"
                                                          maxLength={1500} onChange={(e) => {
                                                    setNewProjDesc(e.currentTarget.value);
                                                }}/>
                                            ) : <div>{newProjDesc}</div>
                                        }
                                    </>
                                ) : <></>
                            }
                        </div>
                        <div style={{padding: '5px 0 0 0', textAlign: 'center'}}>
                            {renderNewProjDescBtn()}
                        </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={updateProjModArray}><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>
        </>
    )
}