import React, { Component } from'react';
import { Form, Input, Button, Radio, Checkbox, Select, message } from 'antd';
import { dictionary } from "api/dict/index";
import {findIndustry, getDetail, update} from 'api/question';

const { Option } = Select;

interface QuestionState {
    id: string|null;
    questionTypes: string;
    industryId: string;
    serviceTypeId: string;
    questionContent: string;
    answerOptions: {[
        key: string]: string
    };
    answer: string;
}

interface States {
    industryDict: any;
    serviceTypeDict: any;
    isLoading: boolean;
    question: QuestionState;
}

class QuestionUp extends Component<any, States> {
    formRef: any;
    constructor(props: any) {
        super(props);
        this.formRef = React.createRef();
        this.state = {
            industryDict: undefined,
            serviceTypeDict: undefined,
            isLoading: false,
            question: {
                id: '',
                questionTypes: '1',
                industryId: '',
                serviceTypeId: '',
                questionContent: '',
                answerOptions: { A: '', B: '', C: '', D: '' },
                answer: ''
            },
        };
    }

    componentDidMount() {
        this.findIndustry()
        this.findDict();
        this.getDetail();
    }

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

    // AQ服务类型
    findDict() {
        dictionary('serviceTypeDict').then((res) => {
            if (res.data) {
                this.setState({ serviceTypeDict: res.data });
            }
        });
    }

    // 题目详情
    getDetail = () => {
        const id = sessionStorage.getItem('id');
        sessionStorage.removeItem('id');
        getDetail(id).then((res: any) => {
            if (res.data) {
                let answerOptions = {};
                const options = res.data.options.split('，');
                options.forEach((option: any) => {
                    const [key, value] = option.split(':');
                    answerOptions[key] = value;
                });
                const question: QuestionState = {
                    id:id,
                    questionTypes: String(res.data.questionTypes),
                    industryId: String(res.data.industryId),
                    serviceTypeId: String(res.data.serviceTypeId),
                    questionContent: String(res.data.questionContent),
                    answerOptions: answerOptions,
                    answer: res.data.answer
                };
                this.setState({ question: question }, () => {
                    const formValues = {};
                    formValues['questionTypes'] = question.questionTypes;
                    formValues['industryId'] = question.industryId;
                    formValues['serviceTypeId'] = question.serviceTypeId;
                    formValues['questionContent'] = question.questionContent;
                    formValues['answer'] = question.answer;
                    formValues['answerOption_A'] = question.answerOptions.A;
                    formValues['answerOption_B'] = question.answerOptions.B;
                    formValues['answerOption_C'] = question.answerOptions.C;
                    formValues['answerOption_D'] = question.answerOptions.D;
                    this.formRef.current.setFieldsValue(formValues);
                });
            }
        }).catch(() => {
            message.error('获取题目详情失败，请重试');
        });
    };

    // 题型
    handleQuestionTypeChange = (value: string) => {
        this.setState((prevState) => {
            prevState.question.questionTypes = value;
            prevState.question.answer = '';
            return {
                question: prevState.question
            };
        });
    };

    // 单选框
    handleRadioChange = (value: string) => {
        this.setState((prevState) => {
            prevState.question.answer = value;
            return {
                question: prevState.question
            };
        });
    };

    // 多选框
    handleCheckboxChange = (type: string, values: (string | number | boolean)[] | null) => {
        const currentAnswer = this.state.question.answer;
        const currentSelectedArray = currentAnswer? currentAnswer.split('，') : [];
        if (!values || values.length === 0) {
            const newSelectedArray = currentSelectedArray.filter(val => val!== type);
            newSelectedArray.sort();
            this.setState((prevState) => {
                prevState.question.answer = newSelectedArray.join('，');
                return {
                    question: prevState.question
                };
            });
        } else {
            const stringValues = values.map((val) => String(val));
            const newSelectedArray = Array.from(new Set([...currentSelectedArray, ...stringValues]));
            newSelectedArray.sort();
            this.setState((prevState) => {
                prevState.question.answer = newSelectedArray.join('，');
                return {
                    question: prevState.question
                };
            });
        }
    };

    // 答案
    handleAnswerOptionChange = (option: string, value: string) => {
        this.setState((prevState) => {
            prevState.question.answerOptions[option] = value;
            return {
                question: prevState.question
            };
        });
    };

    // 保存修改
    update = () => {
        this.setState({ isLoading: true });
        this.formRef.current.validateFields().then((values: Record<string, any>) => {
            const { question } = this.state;
            const updatedQuestion = {
                ...question,
                industryId: values['industryId'],
                serviceTypeId: values['serviceTypeId'],
                questionContent: values['questionContent']
            };
            this.setState({ question: updatedQuestion });
            update(updatedQuestion).then((res) => {
                const isSuccess = res.data;
                if (isSuccess) {
                    message.success('修改成功');
                    this.setState({ isLoading: false });
                    this.props.history.push('/questionList');
                } else {
                    message.error('修改失败，请稍后重试');
                    this.setState({ isLoading: false });
                }
            }).catch(() => {
                message.error('修改时发生错误，请检查');
                this.setState({ isLoading: false });
            });
        });
    };
    render() {
        const { industryDict, serviceTypeDict, question, isLoading } = this.state;
        const handleListQuestion = () => {
            this.props.history.push('/questionList');
        };
        return (
            <div className="container">
                <Form ref={this.formRef} layout="inline">
                    <div style={{ display: 'flex'}}>
                        <Form.Item name="questionTypes">
                            <Radio.Group
                                onChange={(e) => this.handleQuestionTypeChange(e.target.value)}>
                                <Radio.Button value="1">单选题</Radio.Button>
                                <Radio.Button value="2">多选题</Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            label="监管行业："
                            name="industryId"
                            rules={[{ required: true, message: '请选择监管行业' }]}
                        >
                            <Select placeholder="请选择监管行业"
                                    style={{ width: 240 }}
                                    allowClear>
                                {
                                    industryDict && industryDict.length > 0 ?
                                        (() => {
                                            let rows = [];
                                            for (let i = 0; i < industryDict.length; i++) {
                                                const item = industryDict[i];
                                                rows.push(
                                                    <Option value={item.industryId}>{item.industryName}</Option>
                                                );
                                            }
                                            return rows;
                                        })()
                                        :
                                        <Option disabled>暂无数据</Option>
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="AQ服务类型："
                            name="serviceTypeId"
                            rules={[{ required: true, message: '请选择AQ服务类型' }]}
                        >
                            <Select placeholder="请选择AQ服务类型"
                                    style={{ width: 240 }}
                                    allowClear>
                                {
                                    serviceTypeDict && serviceTypeDict.length > 0 ?
                                        (() => {
                                            let rows = [];
                                            for (let i = 0; i < serviceTypeDict.length; i++) {
                                                const item = serviceTypeDict[i];
                                                rows.push(
                                                    <Option
                                                        value={String(item.dictKey).trim().toLowerCase()}>{item.dictValue}</Option>
                                                );
                                            }
                                            return rows;
                                        })()
                                        :
                                        <Option disabled>暂无数据</Option>
                                }
                            </Select>
                        </Form.Item>
                    </div>
                    <Form.Item
                        label="题干："
                        name="questionContent"
                        style={{ marginTop: 10 }}
                        rules={[{ required: true, message: '请输入题干内容' }]}
                    >
                        <Input.TextArea
                            placeholder="请输入题干内容"
                            style={{ width: 1100, height: 60 }}
                        />
                    </Form.Item>
                    <Form.Item style={{ marginTop: 10, marginLeft: 40 }}>
                        <div>
                            <div style={{ display: 'flex' }}>
                                {question.questionTypes === '1'? (
                                    <Radio.Group
                                        value={question.answer}
                                        onChange={(e) => this.handleRadioChange(e.target.value)}
                                    >
                                        <Radio value="A">A</Radio>
                                        <Input
                                            placeholder="请输入答案"
                                            value={question.answerOptions.A}
                                            style={{ width: 490}}
                                            onChange={(e) => this.handleAnswerOptionChange('A', e.target.value)}
                                        />
                                    </Radio.Group>
                                ) : (
                                    <Checkbox.Group
                                        value={question.answer? String(question.answer || '').split('，') : []}
                                        onChange={(values) => this.handleCheckboxChange('A', values,)}>
                                        <Checkbox value="A">A</Checkbox>
                                        <Input
                                            placeholder="请输入答案"
                                            value={question.answerOptions.A}
                                            style={{ width: 500}}
                                            onChange={(e) => this.handleAnswerOptionChange('A', e.target.value)}
                                        />
                                    </Checkbox.Group>
                                )}
                                {question.questionTypes === '1' ? (
                                    <Radio.Group
                                        value={question.answer}
                                        onChange={(e) => this.handleRadioChange( e.target.value)}
                                        style={{ marginLeft: 20 }}
                                    >
                                        <Radio value="B">B</Radio>
                                        <Input
                                            placeholder="请输入答案"
                                            value={question.answerOptions.B}
                                            style={{ width: 490}}
                                            onChange={(e) => this.handleAnswerOptionChange('B', e.target.value)}
                                        />
                                    </Radio.Group>
                                ) : (
                                    <Checkbox.Group
                                        style={{ marginLeft: 20 }}
                                        value={question.answer? String(question.answer || '').split('，') : []}
                                        onChange={(values) => this.handleCheckboxChange('B',values)}>
                                        <Checkbox value="B">B</Checkbox>
                                        <Input
                                            placeholder="请输入答案"
                                            value={question.answerOptions.B}
                                            style={{ width: 500}}
                                            onChange={(e) => this.handleAnswerOptionChange( 'B', e.target.value)}
                                        />
                                    </Checkbox.Group>
                                )}
                            </div>
                            <div style={{ display: 'flex', marginTop: 10 }}>
                                {question.questionTypes === '1'? (
                                    <Radio.Group
                                        value={question.answer}
                                        onChange={(e) => this.handleRadioChange( e.target.value)}
                                    >
                                        <Radio value="C">C</Radio>
                                        <Input
                                            placeholder="请输入答案"
                                            value={question.answerOptions.C}
                                            style={{ width: 490}}
                                            onChange={(e) => this.handleAnswerOptionChange('C', e.target.value)}
                                        />
                                    </Radio.Group>
                                ) : (
                                    <Checkbox.Group
                                        value={question.answer? String(question.answer || '').split('，') : []}
                                        onChange={(values) => this.handleCheckboxChange('C', values)}>
                                        <Checkbox value="C">C</Checkbox>
                                        <Input
                                            placeholder="请输入答案"
                                            value={question.answerOptions.C}
                                            style={{ width: 500}}
                                            onChange={(e) => this.handleAnswerOptionChange( 'C', e.target.value)}
                                        />
                                    </Checkbox.Group>
                                )}
                                {question.questionTypes === '1'? (
                                    <Radio.Group
                                        value={question.answer}
                                        onChange={(e) => this.handleRadioChange( e.target.value)}
                                        style={{ marginLeft: 20 }}
                                    >
                                        <Radio value="D">D</Radio>
                                        <Input
                                            placeholder="请输入答案"
                                            value={question.answerOptions.D}
                                            style={{ width: 490}}
                                            onChange={(e) => this.handleAnswerOptionChange('D', e.target.value)}
                                        />
                                    </Radio.Group>
                                ) : (
                                    <Checkbox.Group
                                        style={{ marginLeft: 20 }}
                                        value={question.answer? String(question.answer || '').split('，') : []}
                                        onChange={(values) => this.handleCheckboxChange('D',values)}>
                                        <Checkbox value="D">D</Checkbox>
                                        <Input
                                            placeholder="请输入答案"
                                            value={question.answerOptions.D}
                                            style={{ width: 500}}
                                            onChange={(e) => this.handleAnswerOptionChange('D', e.target.value)}
                                        />
                                    </Checkbox.Group>
                                )}
                            </div>
                        </div>
                    </Form.Item>
                </Form>
                <div style={{ textAlign: 'right', marginTop: 30 }}>
                    <Button type="default" onClick={handleListQuestion} style={{ marginRight: 10 }}>
                        取消
                    </Button>
                    <Button type="primary" htmlType="submit" loading={isLoading} onClick={this.update}>
                        保存修改
                    </Button>
                </div>
            </div>
        );
    }
}

export default QuestionUp;