import './ai-helper.css'
import { useContext, useEffect, useRef, useState } from "react";
import { GlobalContext } from "../../context/GlobalContext.ts";
import { del, get, post, put, websocketUrl, Axios } from "../../util/AjaxUtils.ts";
import {
    // Col, Divider, Row,
    Spin, Image, Pagination
} from "antd";
import { AxiosResponse } from "axios";
import useMessage from "antd/es/message/useMessage";
import AiHelperText from "./text/AiHelperText.tsx";
import AiHelperMod from "./mod/AiHelperMod.tsx";
import { IProjMod } from "../../interfaces/proj/IProj.ts";
import { MAX_MOD_SIZE } from "../../route/proj/edit/ProjConfigModList.tsx";
import {
    useNavigate,
    // useParams 
} from "react-router-dom";
import { uuid } from "../../util/CommonUtil.ts";

type PropsType = {
    projId: string;
    projIntroduction?: string;
    projDesc?: string;
    isFree: boolean;
    renderData: any
}

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

export default function AiHelper(props: PropsType) {
    // 页面样式相关
    const [pageImgArray, setpageImgArray] = useState<any[]>([])
    const [pageTotal, setPageTotal] = useState(0)
    const [codeTypePageId, setcodeTypePageId] = useState('')
    // 获取页面样式数据
    const getData = () => {
        get({
            messageApi,
            url: `/api/proj/get/edit-step1/${props.projId}`,
            onSuccess({ data }: AxiosResponse) {
                // console.log('嘻嘻', data);


                setcodeTypePageId(data.codeTypePage.codeTypePageId)

            }
        })
    }
    // const [selectedImg,setSelectedImg] = useState('')
    // 获取页面样式图片等信息
    const getPageImgData = (page: number) => {
        get({
            messageApi,
            url: `/api/code/type/page/listpage`,
            config: {
                params: {
                    page: page,
                    rows: 10
                }
            },
            onSuccess(data: any) {
                // console.log(data);
                setPageTotal(data.data.total)
                setpageImgArray(data.data.rows)
            }
        })
    }
    const height = window.innerHeight - 265;

    // const pathParams = useParams();
    // const [openModal ,setOpenModal] = useState(false) //是提示替换弹框
    // const height = window.innerHeight - 280;
    const globalContext = useContext(GlobalContext);
    const pingTimeout = useRef(-1);
    const ws = useRef<WebSocket | null>(null);
    const [messageApi, messageApiHolder] = useMessage();

    const [activeTab, setActiveTab] = useState('简介') //tab栏选中

    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<IProjMod[]>([]);
    const [newProjModArray, setNewProjModArray] = useState<ProjModType[]>([]);
    const [isProjModArrayLoading, setIsProjModArrayLoading] = useState(false);
    const nav = useNavigate();
    // const [showText,setShowText] = useState('保存成功') //提示信息

    // // 获取项目信息
    // const renderData = () => {
    //     get<any>({
    //         messageApi: messageApi,
    //         url: `/api/proj/get/${pathParams.projId}`,
    //         onSuccess({ data }) {
    //             setProjIntroduction(data.projIntroduction)
    //             setProjDesc(data.projDesc)
    //         }
    //     })

    // }





    // 选择页面id和img(初始化用)
    // const [modalId, setModalId] = useState('')
    // const [modalImg, setModalImg] = useState('')
    // 登录页面
    const [total, setTotal] = useState(0)
    const [loginpageId, setloginpageId] = useState('');
    // 获取登录页面信息
    const getLoginPageInfo = () => {
        get<any>({
            messageApi,
            url: `/api/proj/get/config-loginpage/${props.projId}`,
            onSuccess({ data }) {
                // console.log('北京信息',data);
                setloginpageId(data.loginpageId)
            }
        })
    }

    // 登陆页面数组
    const [loginpageArray, setloginpageArray] = useState<any[]>([])
    // 获取登录页面数组
    const getlistLoginpage = (page: number) => {
        get<any>({
            messageApi,
            url: '/api/loginpage/listpage',
            config: {
                params: {
                    page: page,
                    rows: 10
                }
            },
            onSuccess({ data }) {
                // console.log('登录页图片列表', data);
                setloginpageArray(data.rows)

                setTotal(data.total)

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

    const websocket = () => {
        ws.current = new WebSocket(`${websocketUrl()}/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);
                // if (!projIntroduction) {
                //     setProjIntroduction(data.content)
                //     updateProjIntroduction(data.content);

                // }
            } else if (data.type == 'REFRESH_PROJ_DESC') {
                setIsProjDescLoading(false);
                setNewProjDesc(data.content);
                // if (!projDesc) {
                //     setProjDesc(data.content)
                //     updateProjDesc(data.content)

                // }
            } else if (data.type == 'REFRESH_PROJ_MODS') {
                setIsProjModArrayLoading(false);
                const projMods = JSON.parse(data.content) as ProjModType[];
                projMods.forEach(projMod => projMod.id = uuid())
                setNewProjModArray(projMods);
            } else if (data.type == 'REFRESH_PROJ_MOD_FIELDS') {
                listMods();
            }
        }
        ws.current.onerror = (event) => {
            console.log('error', event);
        }
        ws.current.onclose = (event) => {
            console.log('close', event);
            websocket()
        }
    }

    const listMods = () => {
        get<IProjMod[]>({
            messageApi,
            url: `/api/proj-mod/list/proj-id/${props.projId}`,
            onBefore() {
                setIsProjModArrayLoading(true);
            },
            onSuccess({ data }) {
                setProjModArray(data);
            },
            onFinally() {
                setIsProjModArrayLoading(false);
            }
        })
    }

    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(data) {
                messageApi.success('保存成功,点击编辑按钮可继续修改项目简介');
                setProjIntroduction(content);
                setNewProjIntroduction('');
                console.log('更新成功', data);

            },
            onFinally() {
                setIsProjIntroductionLoading(false)
                // renderData()
            }
        })
    }

    /**
     * 保存详情
     */
    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)
                // renderData()
            }
        })
    }

    useEffect(() => {
        if (!props.projId) {
            return;
        }

        listMods();
        websocket();

    }, [globalContext.user.userId, props.projId]);
    useEffect(() => {
        // getLoginPageInfo()
        getlistLoginpage(1)
        // getData()
        getPageImgData(1)
    }, [])
    return (
        <div className='aiTab'>
            {messageApiHolder}
            {/* <Row>
                <Col span={24}>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjIntroductionLoading}>
                        <AiHelperText title="项目简介"
                                      text={projIntroduction}
                                      newText={newProjIntroduction}
                                      maxLength={1500}
                                      handleGenerate={() => {
                                          generateProjIntroduction();
                                      }}
                                      handleSave={(text) => {
                                          updateProjIntroduction(text);
                                      }}
                        />
                    </Spin>
                </Col>
                <Col span={24}>
                    <Divider dashed/>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjDescLoading}>
                        <AiHelperText title="项目详情"
                                      text={projDesc}
                                      newText={newProjDesc}
                                      maxLength={1500}
                                      handleGenerate={() => {
                                          generateProjDesc();
                                      }}
                                      handleSave={(text) => {
                                          updateProjDesc(text);
                                      }}
                        />
                    </Spin>
                </Col>
                <Col span={24}>
                    <Divider dashed/>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjModArrayLoading}>
                        <AiHelperMod mods={projModArray}
                                     newMods={newProjModArray}
                                     handleGenerate={() => {
                                         generateProjModArray();
                                     }}
                                     handleSave={(index, mod) => {
                                         if(projModArray.length > MAX_MOD_SIZE) {
                                            messageApi.error(`模块最大数量为${MAX_MOD_SIZE}`);
                                            return;
                                         }
                                         post<any>({
                                             messageApi,
                                             url: `/api/proj-mod/save-ai/${props.projId}`,
                                             body: {
                                                name: mod.name,
                                                desc: mod.desc,
                                             },
                                             onBefore() {
                                                 setIsProjModArrayLoading(true);
                                             },
                                             onSuccess() {
                                                messageApi.success('提交成功')
                                                listMods();
                                                newProjModArray.splice(index, 1);
                                                setNewProjModArray([
                                                    ...newProjModArray
                                                ]);
                                             },
                                             onFinally() {
                                                 setIsProjModArrayLoading(false);
                                             }
                                         })
                                     }}
                                     handleResaveField={(_index, projModId) => {
                                         post<any>({
                                             messageApi,
                                             url: `/api/proj-mod/resave-ai-field/${props.projId}/${projModId}`,
                                             onBefore() {
                                                 setIsProjModArrayLoading(true);
                                             },
                                             onSuccess() {
                                                 messageApi.success('提交成功')
                                                 listMods();
                                             },
                                             onFinally() {
                                                 setIsProjModArrayLoading(false);
                                             }
                                         })
                                     }}
                                     handleEdit={(_index, projModId, item) => {
                                         if(item.aiFieldStatus != 'SUCCESS') {
                                             messageApi.error('模块未处理完毕不能编辑');
                                             return;
                                         }
                                         if(props.isFree) {
                                             nav(`/proj-edit/config-mod-fedit/${props.projId}/${projModId}`)
                                         } else {
                                             nav(`/proj-edit/config-mod-edit/${props.projId}/${projModId}`)
                                         }
                                     }}
                                     handleRemove={(_index, projModId, item) => {
                                         if(item.aiFieldStatus != 'SUCCESS') {
                                            messageApi.error('模块未处理完毕不能删除');
                                            return;
                                         }
                                         del<any>({
                                             messageApi,
                                             url: `/api/proj-mod/remove/proj-id/${props.projId}/${projModId}`,
                                             onBefore() {
                                                 setIsProjModArrayLoading(true);
                                             },
                                             onSuccess() {
                                                 messageApi.success('删除成功');
                                                 listMods();
                                             },
                                             onFinally() {
                                                 setIsProjModArrayLoading(false);
                                             }
                                         })
                                     }}
                        />
                    </Spin>
                </Col>

            </Row> */}
            <div className="aiTabBtnBox">
                <div className={activeTab == '简介' ? 'tabActive' : "aiTabBtn"}
                    onClick={() => {
                        setActiveTab('简介')
                    }}
                >
                    系统简介
                </div>
                <div className={activeTab == '详情' ? 'tabActive' : "aiTabBtn"}
                    onClick={() => {
                        setActiveTab('详情')
                    }}
                >
                    系统详情
                </div>
                <div className={activeTab == '模块' ? 'tabActive' : "aiTabBtn"}
                    onClick={() => {
                        setActiveTab('模块')
                    }}
                >
                    功能列表
                </div>
                <div className={activeTab == '登录' ? 'tabActive' : "aiTabBtn"}
                    onClick={() => {
                        setActiveTab('登录')
                        getLoginPageInfo()
                    }}
                >
                    登录页面
                </div>
                <div className={activeTab == '页面' ? 'tabActive' : "aiTabBtn"}
                    onClick={() => {
                        setActiveTab('页面')
                        getData()

                    }}
                >
                    页面样式
                </div>
            </div>

            <div className='aiTabContent'>
                <div style={{ display: activeTab == '简介' ? 'block' : 'none' }}>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjIntroductionLoading}>
                        <AiHelperText
                            title="项目简介"
                            text={projIntroduction}
                            newText={newProjIntroduction}
                            maxLength={1500}
                            handleGenerate={() => {
                                generateProjIntroduction();
                                // setProjIntroduction(newProjIntroduction)
                            }}
                            handleSave={(text) => {
                                updateProjIntroduction(text);
                            }}


                        ></AiHelperText>
                    </Spin>
                </div>

                <div style={{ display: activeTab == '详情' ? 'block' : 'none' }}>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjDescLoading}>
                        <AiHelperText title="项目详情"
                            text={projDesc}
                            newText={newProjDesc}
                            maxLength={1500}
                            handleGenerate={() => {
                                generateProjDesc();
                            }}
                            handleSave={(text) => {
                                updateProjDesc(text);
                            }}

                        />
                    </Spin>
                </div>
                <div style={{ display: activeTab == '模块' ? 'block' : 'none' }}>
                    <Spin tip="正在处理，请稍后..." size="small" spinning={isProjModArrayLoading}>
                        <AiHelperMod mods={projModArray}
                            newMods={newProjModArray}
                            handleGenerate={() => {
                                generateProjModArray();
                            }}
                            handleSave={(index, mod) => {
                                if (projModArray.length > MAX_MOD_SIZE) {
                                    messageApi.error(`模块最大数量为${MAX_MOD_SIZE}`);
                                    return;
                                }
                                post<any>({
                                    messageApi,
                                    url: `/api/proj-mod/save-ai/${props.projId}`,
                                    body: {
                                        name: mod.name,
                                        desc: mod.desc,
                                    },
                                    onBefore() {
                                        setIsProjModArrayLoading(true);
                                    },
                                    onSuccess() {
                                        messageApi.success('提交成功')
                                        listMods();
                                        newProjModArray.splice(index, 1);
                                        setNewProjModArray([
                                            ...newProjModArray
                                        ]);
                                    },
                                    onFinally() {
                                        setIsProjModArrayLoading(false);
                                    }
                                })
                            }}
                            handleResaveField={(_index, projModId) => {
                                post<any>({
                                    messageApi,
                                    url: `/api/proj-mod/resave-ai-field/${props.projId}/${projModId}`,
                                    onBefore() {
                                        setIsProjModArrayLoading(true);
                                    },
                                    onSuccess() {
                                        messageApi.success('提交成功')
                                        listMods();
                                    },
                                    onFinally() {
                                        setIsProjModArrayLoading(false);
                                    }
                                })
                            }}
                            handleEdit={(_index, projModId, item) => {
                                if (item.aiFieldStatus != 'SUCCESS') {
                                    messageApi.error('模块未处理完毕不能编辑');
                                    return;
                                }
                                if (props.isFree) {
                                    nav(`/proj-edit/config-mod-fedit/${props.projId}/${projModId}`)
                                } else {
                                    nav(`/proj-edit/config-mod-edit/${props.projId}/${projModId}`)
                                }
                            }}
                            handleRemove={(_index, projModId, item) => {
                                if (item.aiFieldStatus != 'SUCCESS') {
                                    messageApi.error('模块未处理完毕不能删除');
                                    return;
                                }
                                del<any>({
                                    messageApi,
                                    url: `/api/proj-mod/remove/proj-id/${props.projId}/${projModId}`,
                                    onBefore() {
                                        setIsProjModArrayLoading(true);
                                    },
                                    onSuccess() {
                                        messageApi.success('删除成功');
                                        listMods();
                                    },
                                    onFinally() {
                                        setIsProjModArrayLoading(false);
                                    }
                                })
                            }}
                        />
                    </Spin>
                </div>
            </div>
            <div style={{ display: activeTab == '登录' ? 'block' : 'none' }}>
                <div style={{ height: `${height - 80}px`, overflow: 'auto', display: 'flex', justifyContent: 'flex-start', flexWrap: 'wrap', marginTop: 10 }}>
                    {
                        loginpageArray.map((item) => {
                            const imgSrc = `${Axios.defaults?.baseURL}/route/file/v2/download/true/${item.previewImgs}`;
                            return (
                                <div key={item.loginpageId} className={item.loginpageId == loginpageId ? 'page-img-select page-img-selected' : 'page-img-select'}
                                    style={{ marginRight: '10px', marginBottom: '10px', width: 265,height:150,borderRadius:15}}
                                    onClick={() => {
                                        setloginpageId(item.loginpageId)
                                        put({
                                            messageApi,
                                            url: `/api/proj/update-loginpage-id/proj-id/${props.projId}/loginpage-id/${item.loginpageId}`,
                                           

                                            onSuccess() {
                                                messageApi.open({
                                                    type: 'success',
                                                    content: '已更改'
                                                })
                                                getLoginPageInfo()
                                                // props.closeModal()
                                                // props.closeModal()


                                            },

                                        })
                                    }}
                                >
                                    <div className="page-img" >
                                        <Image
                                            src={imgSrc}
                                            preview={false} width={265} height={150}
                                            style={{borderRadius:15}} />
                                    </div>
                                    <div className="page-title">
                                        <div className="checkbox"></div>
                                        {/* <div className="text">{props.title ? props.title : '标题'}</div> */}
                                    </div>
                                        
                                    
                                </div>
                            )
                        })
                    }

                </div>
                <div className='pagination'>
                    {/* defaultCurrent: 默认当前页数  total:数据总数 defaultPageSize:'页面显示几条'  */}
                    <Pagination defaultCurrent={1} total={total} defaultPageSize={10} onChange={(page) => {
                        console.log(page);
                        // setPage(page)
                        setloginpageArray([])
                        getlistLoginpage(page)
                    }} />
                </div>

            </div>

            <div style={{ display: activeTab == '页面' ? 'block' : 'none' }}>
                <div style={{ height: `${height - 80}px`, overflow: 'auto', display: 'flex', justifyContent: 'flex-start', flexWrap: 'wrap', marginTop: 10 }}>
                    {
                        pageImgArray.map((item) => {
                            const imgSrc = `${Axios.defaults?.baseURL}/route/file/v2/download/true/${item.previewImgs}`;
                            return (
                                <div key={item.loginpageId} className={item.codeTypePageId == codeTypePageId ? 'page-img-select page-img-selected' : 'page-img-select'}
                                    style={{ marginRight: '10px', marginBottom: '10px', width: 265, height: 135,borderRadius:15 }}
                                    onClick={() => {
                                        // setSelectedId(item.codeTypePageId)
                                        // setSelectedImg(item.previewImgs)
                                        setcodeTypePageId(item.codeTypePageId)
                                        put({
                                            messageApi,
                                            // url: `/api/proj/update/edit-step1/${props.projId}`,
                                            url: `/api/proj/update-code-type-page-id/proj-id/${props.projId}/code-page-type-id/${item.codeTypePageId}`,


                                            onSuccess() {
                                                messageApi.open({
                                                    type: 'success',
                                                    content: '已更改'
                                                })
                                                getData()

                                            },

                                        })
                                    }}
                                >
                                    <div className="page-img" >
                                        <Image
                                            src={imgSrc}
                                            preview={false} width={265} height={135} style={{borderRadius:15}} />
                                    </div>
                                    <div className="page-title">
                                        <div className="checkbox"></div>
                                        {/* <div className="text">{props.title ? props.title : '标题'}</div> */}
                                    </div>
                                </div>
                            )
                        })
                    }

                </div>
                <div className='pagination'>
                    {/* defaultCurrent: 默认当前页数  total:数据总数 defaultPageSize:'页面显示几条'  */}
                    <Pagination defaultCurrent={1} total={pageTotal} defaultPageSize={10} onChange={(page) => {
                        console.log(page);
                        // setPage(page)
                        setpageImgArray([])
                        getPageImgData(page)
                    }} />
                </div>

            </div>
            {/* <div className='proIntroduction'>
                项目简介
            </div>
            <div className='proDetail'>
                项目详情
            </div> */}


        </div>
    )
}