import React, {useEffect} from 'react';
import {Button, Flex, message, Result, Space, Spin, Steps} from "antd";
import CardDiv from "../../../component/CardDiv/CardDiv";
import ChooseUser from "./ChooseUser";
import ParameterConfig from "./ParameterConfig";
import ContentConfig from "./ContentConfig";
import ReadyToGenerate from "./ReadyToGenerate";
import creatMessageCommonAxios from "../../../http/CreatMessageCommonAxios";
import {useNavigate} from "react-router-dom";

const GenerateCertificate = props => {

    const [messageApi, contextHolder] = message.useMessage();
    const commonAxios = creatMessageCommonAxios(messageApi);
    const navigate = useNavigate();


    const [current, setCurrent] = React.useState(() => {
        let nowStep = sessionStorage.getItem('nowStep');
        if (nowStep === null) {
            return 0;
        } else {
            return parseInt(nowStep);
        }
    });

    const [request, setRequest] = React.useState({
        ids: [],
        stuffNumber: "",
        recordType: "",
        totalTeachingWorkload: "",
        annualAverageTeachingWorkload: "",
    });

    const [resultStatus, setResultStatus] = React.useState('error');
    const [result, setResult] = React.useState({});
    const [loading, setLoading] = React.useState(false);

    const [pageConfig, setPageConfig] = React.useState({});

    const steps = [
        {
            title: '选择用户',
            description: '选择生成证书的用户',
        },
        {
            title: '证书参数配置',
            description: '证书类型、参数配置',
        },
        {
            title: '证书内容配置',
            description: '选择证书的工作量记录',
        },
        {
            title: '数据确认',
            description: '确认数据，准备生成',
        },
        {
            title: '生成证明',
            description: '生成进行中',
        },
    ];

    const stepMap = {
        0:
            <ChooseUser
                allowNext={(allow) => allowNext(allow)}
                request={request}
                setRequest={req => setRequest(req)}
            />,
        1:
            <ParameterConfig
                allowNext={(allow) => allowNext(allow)}
                request={request}
                setRequest={req => setRequest(req)}
            />,
        2:
            <ContentConfig
                allowNext={(allow) => allowNext(allow)}
                request={request}
                setRequest={req => setRequest(req)}
            />,
        3:
            <ReadyToGenerate
                allowNext={(allow) => allowNext(allow)}
                request={request}
                setRequest={req => setRequest(req)}
            />,
        4:
            <Result
                status={resultStatus}
                title={resultStatus === 'success' ? '成功' : '失败'}
                subTitle={resultStatus === 'success' ?
                    `编号: ${result.id} 的证书打印请求已成功进入队列，正在生成证书，请前往证书打印页面查看。` :
                    '证书生成失败'}
                extra={[
                    <Button type="primary" key="console" onClick={() => navigate('/data-print')}>
                        {resultStatus === 'success' ? '查看结果' : '返回'}
                    </Button>,
                ]}
            />
    }

    const [preButton, setPreButton] = React.useState({
        type: "default",
        disabled: true,
        hidden: false,
        text: "上一步",
    });

    const [nextButton, setNextButton] = React.useState({
        type: "primary",
        disabled: true,
        hidden: false,
        text: "下一步",
    })


    const onNext = () => {
        let nextCurrent = current + 1;
        setPreButton({...preButton, disabled: false,});

        if (nextCurrent === 3) {
            setCurrent(nextCurrent);
            sessionStorage.setItem('nowStep', nextCurrent.toString());
        }
        if (nextCurrent >= 4) {
            setLoading(true);
            commonAxios.post('/api/v1/workload/certificate/generate', request).then((response) => {
                console.log(response);
                console.log(response.data.data !== null)
                console.log(response.data.data.success === true)
                if (response.data.data !== null && response.data.success === true) {
                    setResultStatus('success');
                    setResult(response.data.data);
                } else {
                    setResultStatus('error');
                    setResult(response.data.errorDetails);
                    messageApi.error(response.data.errorDetails.message + `(${response.data.errorDetails.code})`);
                }
                setPreButton({...preButton, hidden: true,});
                setNextButton({...nextButton, hidden: true,});
                setCurrent(4);
                setLoading(false);
            });
            sessionStorage.removeItem('nowStep');
            sessionStorage.removeItem('chooseUser');
            sessionStorage.removeItem('certificateParam');
            sessionStorage.removeItem('targetKeys');
            sessionStorage.removeItem('generate-request');
        } else {
            setCurrent(nextCurrent);
            allowNext(false);
            sessionStorage.setItem('nowStep', nextCurrent.toString());
        }

    }

    const onPrev = () => {
        let nextCurrent = current - 1;
        setCurrent(nextCurrent);
        let editFlag = sessionStorage.getItem('edit-flag');
        if (nextCurrent <= 0) {
            setCurrent(0)
            setPreButton({...preButton, disabled: true,})
        }
        sessionStorage.setItem('nowStep', nextCurrent.toString());
    }

    const allowNext = (allow) => {
        setNextButton({...nextButton, disabled: !allow})
    }

    useEffect(() => {
        console.log(request);
        if (request.stuffNumber !== '') {
            sessionStorage.setItem('generate-request', JSON.stringify(request));
        }
    }, [request]);

    useEffect(() => {
        let request = sessionStorage.getItem('generate-request');
        if (request !== null) {
            request = JSON.parse(request);
            setRequest(request);
        }
    }, []);

    return (
        <div>
            {contextHolder}
            <Space direction="vertical" size="large" style={{display: "flex"}}>
                <CardDiv>
                    <Steps
                        current={current}
                        items={steps}
                    />
                </CardDiv>
                <Spin spinning={loading}>
                    <CardDiv>
                        {stepMap[current]}
                        <Flex justify={"start"} align={"center"} gap={"middle"} style={{marginTop: 20}}
                              hidden={current >= 4}>
                            <Button
                                type={preButton.type}
                                disabled={preButton.disabled}
                                onClick={onPrev}
                                style={{display: current === 4 ? 'none' : 'inline-block'}}>
                                {preButton.text}
                            </Button>
                            <Button
                                type={nextButton.type}
                                disabled={nextButton.disabled}
                                onClick={onNext}
                                style={{display: current === 4 ? 'none' : 'inline-block'}}>
                                {current === 3 ? '开始生成' : nextButton.text}
                            </Button>
                        </Flex>
                    </CardDiv>
                </Spin>
            </Space>
        </div>
    );
};

GenerateCertificate.propTypes = {};

export default GenerateCertificate;