import './proj-edit.css';
import {Link, useNavigate, useParams} from "react-router-dom";
import {Breadcrumb, Button, message, Modal} from "antd";
import StepProjEdit from "../../components/step/StepProjEdit.tsx";
import CardProjEdit from "../../components/card/CardProjEdit.tsx";
import {Process} from "../../interfaces/step/IStepProj.ts";
import CardProjLoading from "../../components/card/CardProjLoading.tsx";
import CardProjResult from "../../components/card/CardProjResult.tsx";
import CardProjDownload from "../../components/card/CardProjDownload.tsx";
import CardProjJump from "../../components/card/CardProjJump.tsx";
import {useEffect, useState} from "react";
import {Axios, get, post} from "../../util/AjaxUtils.ts";
import {EditStepEnum, IProjEdit} from "../../interfaces/card/ICardProj.ts";
import {MAX_MOD_SIZE} from "./edit/ProjConfigModList.tsx";
import {GenerateStatus} from "../../interfaces/proj/IProj.ts";

export default function ProjEdit() {
    const nav = useNavigate();
    const pathParams = useParams();

    const [messageApi, contextHolder] = message.useMessage();
    const [editStepArray, setEditStepArray] = useState<IProjEdit[]>([]);
    const [configArray, setConfigArray] = useState<IProjEdit[]>([]);
    const [isEditStepEdited, setIsEditStepEdited] = useState(false);
    const [isConfigEdited, setIsConfigEdited] = useState(false);
    // const [isAllStepEdited, setIsAllStepEdited] = useState(false);
    const [canGenerate, setCanGenerate] = useState(false);
    const [generateStatus, setGenerateStatus] = useState(GenerateStatus.NONE);
    const [isGenerateModalOpen, setIsGenerateModalOpen] = useState(false);
    const [previewUrl, setPreviewUrl] = useState('');
    const height = window.innerHeight - 240;

    const renderEditStep = (editSteps: any[], isEdited: boolean) => {
        const editStepArray: IProjEdit[] = [];
        editStepArray.push(
            {
                title: '标题简介',
                desc: '完善代码、样式类型和详细介绍等内容',
                step: 1,
                status: editSteps[0].editStatus,
                handleEdit() {
                    nav(`/proj-edit/step1/${pathParams.projId}`)
                }
            },
            {
                title: '基本信息',
                desc: '完善项目简介、编程语言、版本、公司等内容',
                step: 2,
                status: editSteps[1].editStatus,
                handleEdit() {
                    nav(`/proj-edit/step2/${pathParams.projId}`)
                }
            },
            {
                title: '软件功能特点',
                desc: '请完善软件功能特点',
                step: 3,
                status: editSteps[2].editStatus,
                handleEdit() {
                    nav(`/proj-edit/step3/${pathParams.projId}`)
                }
            },
            {
                title: '著作人信息',
                desc: '请完善著作人相关信息',
                step: 4,
                status: editSteps[3].editStatus,
                handleEdit() {
                    nav(`/proj-edit/step4/${pathParams.projId}`)
                }
            },
            {
                title: '申请人信息',
                desc: '请完善申请人信息',
                step: 5,
                status: editSteps[4].editStatus,
                handleEdit() {
                    nav(`/proj-edit/step5/${pathParams.projId}`)
                }
            },
            {
                title: '选择登录页面',
                desc: '选择软件的登录页面模板',
                step: 6,
                status: editSteps[5].editStatus,
                handleEdit() {
                    nav(`/proj-edit/step6/${pathParams.projId}`)
                }
            }
        )
        setEditStepArray(editStepArray);
        setIsEditStepEdited(isEdited);
    }

    const renderSetting = (data: any, isConfig: boolean) => {
        const configArray: IProjEdit[] = [];
        configArray.push(
            {
                title: '登录界面设置',
                desc: '请对登录界面完成个性化设置',
                step: 1,
                btnName: '设置',
                status: data.loginpage.loginpageId ? EditStepEnum.EDITED : EditStepEnum.UN_EDIT,
                handleEdit() {
                    nav(`/proj-edit/config-loginpage/${pathParams.projId}`)
                }
            },
            {
                title: '系统菜单管理',
                desc: '请对系统菜单进行设置',
                step: 2,
                btnName: '设置',
                status: data.projModCount > MAX_MOD_SIZE ? EditStepEnum.EDITED : EditStepEnum.UN_EDIT,
                handleEdit() {
                    nav(`/proj-edit/config-mod-list/${pathParams.projId}`)
                }
            },
            {
                title: '菜单顺序',
                desc: '调整菜单顺序',
                step: 3,
                btnName: '设置',
                status: data.projModCount > MAX_MOD_SIZE ? EditStepEnum.EDITED : EditStepEnum.UN_EDIT,
                handleEdit() {
                    nav(`/proj-edit/config-menu-list/${pathParams.projId}`)
                }
            }
        )
        setConfigArray(configArray);
        setIsConfigEdited(isConfig);
    }

    const renderData = () => {
        get({
            messageApi: messageApi,
            url: `/api/proj/get/${pathParams.projId}`,
            onSuccess({data}) {
                const isEdited = data.editSteps[0].editStatus == EditStepEnum.EDITED
                    && data.editSteps[1].editStatus == EditStepEnum.EDITED
                    && data.editSteps[2].editStatus == EditStepEnum.EDITED
                    && data.editSteps[3].editStatus == EditStepEnum.EDITED
                    && data.editSteps[4].editStatus == EditStepEnum.EDITED
                    && data.editSteps[5].editStatus == EditStepEnum.EDITED;
                const isConfig = data.loginpage.loginpageId && MAX_MOD_SIZE > 0;
                const isGenerate = isEdited && isConfig;
                renderEditStep(data.editSteps, isEdited);
                renderSetting(data, isConfig);
                setCanGenerate(isGenerate);
                setGenerateStatus(data.generate.generateStatus);
                setPreviewUrl(data.previewUrl);
            }
        })
    }

    useEffect(() => {
        renderData();
    }, [])

    return (
        <>
            {contextHolder}
            <Breadcrumb
                items={[
                    {title: <Link to={'/'}>首页</Link>},
                    {title: <Link to={'/proj-create'}>创建项目</Link>},
                    {title: '编辑项目'},
                ]}
            />
            <div className="proj-edit" style={{height: `${height}px`}}>
                <StepProjEdit step={1} process={isEditStepEdited ? Process.COMPLETE : Process.PROCESSING}
                              descTitle="完善信息"
                              descDetail="完善项目的基本信息"
                              hasNext={true}>
                    {
                        editStepArray.map((item, index) => {
                            return <CardProjEdit key={`editStep-${index}`}
                                                 title={item.title}
                                                 desc={item.desc}
                                                 status={item.status}
                                                 handleEdit={item.handleEdit}
                            />
                        })
                    }

                </StepProjEdit>
                <StepProjEdit step={2}
                              process={!isEditStepEdited ? Process.PENDING : (isConfigEdited ? Process.COMPLETE : Process.PROCESSING)}
                              descTitle="功能设置"
                              descDetail="设置系统的菜单功能" hasNext={true}>
                    {
                        configArray.map((item, index) => {
                            return <CardProjEdit key={`config-${index}`}
                                                 title={item.title}
                                                 desc={item.desc}
                                                 btnName={item.btnName}
                                                 canBtnClick={isEditStepEdited}
                                                 status={item.status}
                                                 handleEdit={item.handleEdit}
                            />
                        })
                    }
                    {
                        isEditStepEdited && isConfigEdited ? (
                            <CardProjJump title="预览系统"
                                          desc="点击查看预览系统"
                                          handleJump={() => {
                                              window.open(`${Axios.defaults?.baseURL}/${previewUrl}`, '_blank')
                                          }}
                            />
                        ) : <></>
                    }
                </StepProjEdit>
                <StepProjEdit step={3} process={canGenerate ? Process.PROCESSING : Process.PENDING} descTitle="资料生成"
                              hasNext={true}>
                    {
                        generateStatus == GenerateStatus.NONE || generateStatus == GenerateStatus.FAILED ? (
                            <CardProjEdit title="资料生成"
                                          desc="生成软著所需要的资料，此操作后项目无法再次编辑"
                                          btnName="生成"
                                          status={EditStepEnum.UN_EDIT}
                                          canBtnClick={canGenerate}
                                          handleEdit={() => {
                                              setIsGenerateModalOpen(true);
                                          }}
                            />
                        ) : <></>
                    }
                    {
                        generateStatus == GenerateStatus.PENDING ? (
                            <CardProjLoading title="正在排队"
                                             desc="资料正在排队"
                                             duration={600}
                                             handleCountDownOver={() => {
                                                 renderData();
                                             }}
                            />
                        ) : <></>
                    }
                    {
                        generateStatus == GenerateStatus.GENERATING ? (
                            <CardProjLoading title="正在生成"
                                             desc="资料正在生成"
                                             duration={600}
                                             handleCountDownOver={() => {
                                                 renderData();
                                             }}

                            />
                        ) : <></>
                    }
                    {
                        generateStatus == GenerateStatus.SUCCESS ? (
                            <CardProjResult title="生成成功"
                                            isSuccess={true}
                            />
                        ) : <></>
                    }
                    {
                        generateStatus == GenerateStatus.FAILED ? (
                            <CardProjResult title="生成失败"
                                            isSuccess={false}
                                            handleFeedback={() => {
                                                console.log('反馈')
                                            }}
                            />
                        ) : <></>
                    }
                </StepProjEdit>
                <StepProjEdit step={4} process={Process.PENDING} descTitle="资料下载">
                    <CardProjDownload title="软件基本信息"
                                      desc="请完善软件的介绍，详细介绍等基本信息"
                                      handleDownload={() => {
                                          console.log('下载')
                                      }}
                    />
                    <CardProjJump title="跳转"
                                  desc="请完善软件的介绍，详细介绍等基本信息"
                                  handleJump={() => {
                                      nav('/agent-select/2');
                                  }}
                    />
                </StepProjEdit>
            </div>
            <div className="btn-container">
                <Button size="large" style={{
                    width: '200px',
                    fontSize: '14px',
                    backgroundColor: 'var(--color-primary)',
                    color: 'var(--color-light)'
                }} onClick={() => {
                    nav(-1);
                }}>返回</Button>
            </div>
            <Modal title="提示"
                   okText="确定"
                   cancelText="取消"
                   open={isGenerateModalOpen}
                   onOk={() => {
                       post({
                           messageApi,
                           url: `/api/proj/generate/proj-id/${pathParams.projId}`,
                           body: {},
                           onSuccess() {
                               messageApi.success('提交成功');
                               setIsGenerateModalOpen(false);
                               renderData();
                           }
                       })
                   }}
                   onCancel={() => {
                       setIsGenerateModalOpen(false);
                   }}>
                <div>点击“确定按钮”后，项目便无法再次修改，建议通过预览查看系统，确认无误后点击“确定按钮”。</div>
            </Modal>
        </>
    )
}