new Vue({
    el: '#container',
    data() {
        return {
            isLogin: checkWebLogin(),
            title: '',
            questionnairesId: '',
            questionnairesList: [],
            loading: false,
            radio: '',
            cacheAnswers: [],
            form: {
                answers: []
            },
            userInfo: {}
        }
    },
// {
//     "userId": "user202207081451",
//     "answers": [
//     {
//         "questionId": "问题的ID",
//         "optionId": "选项的ID（如果问题类型是判断题、单选题、多选题）",
//         "text": "问题的答案（如果问题类型是问答题）"
//     },
//     {
//         "questionId": "问题2的ID",
//         "optionId": "选项的ID（如果问题类型是判断题、单选题、多选题）",
//         "text": "问题的答案（如果问题类型是问答题）"
//     }
// ]
// }
    methods: {
        toast(type, text, callback) {
            this.$message({
                message: text,
                type: type,
                customClass: 'submitSuccessMsg',
                duration: 3000
            });
            setTimeout(() => {
                callback && callback();
            }, 2000)
        },
        submit(finalyAnswers) {
            var _this = this;
            $.ajax({
                url: '/questionnaires/' + _this.questionnairesId + '/answers',
                type: 'POST',
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                data: JSON.stringify({
                    userId: _this.userInfo.id || '',
                    answers: finalyAnswers
                }),
                success: function () {
                    _this.resetQuestion();
                    _this.toast('success', '提交成功',function () {
                        location.replace('/index/index?from=web')
                    })
                },
                error: function () {
                    localStorage.setItem('answers', JSON.stringify(_this.form.answers));
                    _this.toast('error','服务器出错~',function (){
                        location.reload();
                    })
                }
            })
        },
        resetQuestion() {
            localStorage.removeItem('answers');
            this.cacheAnswers = [];
            this.form.answers = [];
            this.initAnswers();
        },
        submitQuestion() {
            var finalyAnswers = []
            this.form.answers.forEach((item, index) => {
                item.questionGroups.forEach((_i, _index) => {
                    _i.answers.forEach((deep, deepIndex) => {
                        deep.text = deep.optionId.split(',')[1];
                        var newDeep = Object.assign({}, deep)
                        newDeep.text = newDeep.optionId.split(',')[1];
                        newDeep.optionId = newDeep.optionId.split(',')[0];
                        if (newDeep.optionId) {
                            finalyAnswers.push(newDeep);
                        }
                    })
                })
            })
            if (finalyAnswers.length === 0) return this.toast('warning', '您还未回答问卷调查')
            this.submit(finalyAnswers);
        },
        initAnswers: function () {
            if (this.cacheAnswers.length) return;
            this.questionnairesList.forEach((item, index) => {
                this.form.answers.push({
                    questionGroups: []
                })
                item.questionGroups.forEach((_i, _index) => {
                    this.form.answers[index].questionGroups.push({
                        answers: []
                    })
                    _i.questions.forEach((deep, deepIndex) => {
                        this.form.answers[index].questionGroups[_index].answers.push({
                            questionId: deep.id,
                            // questionName: deep.text,
                            text: '',
                            optionId: ''
                        })
                    })
                })
            })
        },
        getQuestionList: function () {
            var _this = this;
            $.ajax({
                url: '/questionnaires/66-common-disease/optimization',
                type: 'GET',
                async: true,
                success: function (data) {
                    _this.questionnairesList = data.dynamicNode;
                    _this.initAnswers();
                    _this.questionnairesId = data.id;
                    _this.title = data.name;
                    _this.loading = false;
                }
            })
        },
        getUserInfo: function () {
            var _this = this;
            $.ajax({
                url: '/user/getUserInfoWeb',
                type: 'POST',
                success: function (data) {
                    _this.userInfo = data.data || {};
                }
            })
        }
    },
    created: function () {
        if (this.isLogin) {
            this.getUserInfo();
        }
        var cacheAnsswers = localStorage.getItem('answers');
        if (cacheAnsswers) {
            this.cacheAnswers = JSON.parse(cacheAnsswers);
            this.form.answers = this.cacheAnswers;
        }
        this.loading = true;
       this.getQuestionList();
    }
})