import React, { Component } from 'react';
import { Form, Input, Button, Radio, Checkbox, Select, message} from 'antd';
import { getDetail} from 'api/examPaper';
import { findIndustry} from 'api/question';

const { Option } = Select;

interface optionsState {
    value: string;
    label: string;
}

// 定义单个试题的状态接口
interface QuestionState {
    id: string;
    serviceTypeId: string;
    questionTypes: string;
    questionContent: string;
    answerOptions: optionsState[];
    answer: string | null;
}

// 定义组件的状态接口
interface States {
    id: string | undefined;
    industryDict: any;
    paperName : string | undefined;
    industryId : number | undefined;
    questionCount : number | undefined;
    totalScore : number | undefined;
    examDuration : string | undefined;
    durationType : number | undefined;
    paperContent : string | undefined;
    questions: QuestionState[];
}

class ExamPaperView extends Component<any, States> {
    formRef: any;
    constructor(props: any) {
        super(props);
        this.formRef = React.createRef();
        this.state = {
            id: undefined,
            industryDict: undefined,
            paperName: undefined,
            industryId: undefined,
            questionCount: undefined,
            totalScore: undefined,
            examDuration: undefined,
            durationType: undefined,
            paperContent: undefined,
            questions: [],
        };
    }

    // 初期
    componentDidMount() {
        const id = sessionStorage.getItem('id');
        sessionStorage.removeItem('id');
        this.findIndustry();
        this.getDetail(id);
    }

    // 监管行业
    findIndustry() {
        findIndustry().then((res: any) => {
            if (res.data) {
                this.setState({ industryDict: res.data });
            }
        });
    }

    // 试卷详情
    getDetail = (id: string | null) => {
        getDetail(id).then((res: any) => {
            if (res.data) {
                const newQuestions: QuestionState[] = res.data.data.map((questionData: any) => {
                    const options = questionData.options.split('，');
                    const answerOptions = options.map((option: any) => {
                        const [value, label] = option.split(':');
                        return { value, label };
                    });
                    return {
                        id: String(questionData.id),
                        serviceTypeId: String(questionData.serviceTypeId),
                        questionTypes: String(questionData.questionTypes),
                        questionContent: String(questionData.questionContent),
                        answerOptions: answerOptions,
                        answer: String(questionData.answer)
                    };
                });
                const paperName = res.data.head.paperName;
                const industryId = res.data.head.industryId;
                const questionCount = res.data.head.questionCount;
                const totalScore = res.data.head.totalScore;
                const examDuration = res.data.head.examDuration;
                const durationType = res.data.head.durationType;
                const paperContent = res.data.head.paperContent;
                this.setState({
                    questions: newQuestions,
                    paperName,
                    industryId,
                    questionCount,
                    totalScore,
                    examDuration,
                    durationType,
                    paperContent,
                });
            }
        }).catch(() => {
            message.error('获取题目详情失败，请重试');
        });
    };
    findDurationTypeName = (durationType:number | undefined) => {
        switch (durationType) {
            case 1:
                return '分(min)';
            case 2:
                return '时(h)';
            default:
                return '未知';
        }
    };
    findIndustryName = (industryId:number | undefined) => {
        const { industryDict } = this.state;
        if (industryDict) {
            const industry = industryDict.find((item:any) => item.industryId === String(industryId));
            return industry ? industry.industryName : '未知行业';
        }
        return '未知行业';
    };
    render() {
        const {
            questions,
            paperName,
            industryId,
            questionCount,
            totalScore,
            examDuration,
            durationType,
            paperContent,
        } = this.state;
        // 页面跳转
        const handleListQuestion = () => {
            this.props.history.push('/examPaperList');
        };
        return (
            <div className="container">
                <Form ref={this.formRef}>
                    <h3 style={{ fontWeight: 'bold' }}>基本信息</h3>
                    <Form.Item label="试卷名称：">
                        <span>{paperName}</span>
                    </Form.Item>
                    <div style={{ display: 'flex', gap: 20 }}>
                        <Form.Item label="监管行业：">
                            <span>{this.findIndustryName(industryId)}</span>
                        </Form.Item>
                        <Form.Item label="题目数量：">
                            <span>{questionCount}</span>
                        </Form.Item>
                        <Form.Item label="总分值：">
                            <span>{totalScore}</span>
                        </Form.Item>
                        <Form.Item label="考试时长：">
                            <span>{examDuration}</span>
                        </Form.Item>
                        <Form.Item label="">
                            <span>{this.findDurationTypeName(durationType)}</span>
                        </Form.Item>
                    </div>
                    <Form.Item label="内容描述：">
                        <span>{paperContent}</span>
                    </Form.Item>
                    <div style={{ display: 'flex' }}>
                        <h3 style={{ fontWeight: 'bold' }}>试题详情</h3>
                    </div>
                    {questions.map((question, index) => (
                        <div
                            style={{
                                border: '1px solid #e8e8e8',
                                padding: 10,
                                marginBottom: 10
                            }}
                        >
                            <span style={{ fontWeight: 'bold' }}>{index + 1}. {question.questionContent}</span>
                            <Form.Item>
                                {question.questionTypes === '1'? (
                                    <Radio.Group value={question.answer}>
                                        {question.answerOptions.map((option) => (
                                            <Radio value={option.value}>
                                                {option.value}. {option.label}
                                            </Radio>
                                        ))}
                                    </Radio.Group>
                                ) : (
                                    <Checkbox.Group value={question.answer? question.answer.split('，') : []}>
                                        {question.answerOptions.map((option) => (
                                            <Checkbox value={option.value}>
                                                {option.value}. {option.label}
                                            </Checkbox>
                                        ))}
                                    </Checkbox.Group>
                                )}
                            </Form.Item>
                        </div>
                    ))}
                    <div
                        style={{
                            textAlign: 'right',
                            position: 'fixed',
                            bottom: 10,
                            right: 10,
                            width: '100%',
                            backgroundColor: 'white',
                            zIndex: 1000
                        }}
                    >
                        <Button type="default" htmlType="button" onClick={
                            handleListQuestion
                        }>
                            取消
                        </Button>
                    </div>
                </Form>
            </div>
        );
    }
}
export default ExamPaperView;