<template>
<div class='m-container'>
    <h2>
      <el-page-header @back="onCancel" :content="titleName"></el-page-header>
    </h2>
    <div class="m-core">
        <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="问卷名称" prop="title" :rules="[{ required: true, message: '请输入问卷名称', trigger: 'blur' }]">
                        <el-input v-model="form.title" placeholder="请输入问卷名称" :disabled="disabled"></el-input>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18" v-for="(item, index) in form.questionnaireQuestionList" :key="index" style="padding: 15px 22px; background-color: #eef4f9; margin-bottom: 10px;">
                <el-row type="flex" align="middle" style="flex: 1 auto; padding-bottom: 15px;">
                    <el-col :span="12">
                        <span style="font-size: 18px;width: 80px; text-align: right;display: inline-block;">问题{{ index + 1 }}</span>
                    </el-col>
                    <el-col :span="12" style="text-align: right; padding-right: 15px;">
                        <el-tooltip class="item" effect="dark" content="向下移动" placement="top">
                            <el-button icon="el-icon-top" circle size="small" @click.stop="moveDown(form.questionnaireQuestionList, index)" :disabled="index == 0 || disabled"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="向下移动" placement="top">
                            <el-button icon="el-icon-bottom" circle size="small" @click.stop="moveUp(form.questionnaireQuestionList, index)" :disabled="form.questionnaireQuestionList.length <= 1 || form.questionnaireQuestionList.length == (index + 1) || disabled"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top">
                            <el-button icon="el-icon-delete" circle size="small" @click.stop="onDelete(form.questionnaireQuestionList, index)" :disabled="form.questionnaireQuestionList.length <= 1 || disabled"></el-button>
                        </el-tooltip>
                    </el-col>
                </el-row>
                <question-list ref="questions" :type="type" :form="item" :disabled="disabled" />
            </el-col>
            <!-- <el-collapse v-model="activeName">
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18" v-for="(item, index) in form.questionnaireQuestionList" :key="index" style="padding: 15px 22px; background-color: #eef4f9; margin-bottom: 10px;">
                <el-collapse-item style="background-color: #eef4f9;" :name="index">
                    <template slot="title">
                        <el-row type="flex" align="middle" style="flex: 1 auto;">
                            <el-col :span="12">
                                <span style="font-size: 18px;width: 80px; text-align: right;display: inline-block;">问题{{ index + 1 }}</span>
                            </el-col>
                            <el-col :span="12" style="text-align: right; padding-right: 15px;">
                                <el-tooltip class="item" effect="dark" content="向下移动" placement="top">
                                    <el-button icon="el-icon-top" circle size="small" @click.stop="moveDown(form.questionnaireQuestionList, index)" :disabled="index == 0"></el-button>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" content="向下移动" placement="top">
                                    <el-button icon="el-icon-bottom" circle size="small" @click.stop="moveUp(form.questionnaireQuestionList, index)" :disabled="form.questionnaireQuestionList.length <= 1 || form.questionnaireQuestionList.length == (index + 1)"></el-button>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                                    <el-button icon="el-icon-delete" circle size="small" @click.stop="onDelete(form.questionnaireQuestionList, index)" :disabled="form.questionnaireQuestionList.length <= 1"></el-button>
                                </el-tooltip>
                            </el-col>
                        </el-row>
                    </template>
                    <question-list ref="questions" :type="type" :form="item" />
                </el-collapse-item>
                </el-col>
            </el-collapse> -->
        </el-row>
        <el-row style="padding-bottom: 15px;">
            <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18" style="text-align: center;">
                <el-button style="width: 100%" type="default" :disabled="disabled" @click="addQuestionItem(form.questionnaireQuestionList)" icon="el-icon-plus">新增问题</el-button>
            </el-col>
        </el-row>
        <el-button type="primary" :disabled="disabled" @click="onSubmit">{{ type == 'create' ? '生成问卷' : '修改问卷' }}</el-button>
        <el-button @click="onReset" :disabled="disabled">重置</el-button>
        <el-button @click="onPreview">预览</el-button>

        <el-dialog title="问卷题目"
               :close-on-click-modal="false"
               :visible.sync="questionStatus"
               v-if="questionStatus"
               width="375px">
            <answer-list :form="form" :close="() => {questionStatus = false}" />
        </el-dialog>
    </div>
</div>
</template>
<script>
import questionList from './components/questionList'
import { questionnaireTopicAdd, questionnaireTopicGetDetail, questionnaireTopicUpdate } from './api'
import AnswerList from './components/answerList'
export default {
    name: 'operationQuestion',
    components: { questionList, AnswerList },
    data () {
        let query = this.$route.query
        let titleName = '问卷'
        if(query.type == 'create') {
          titleName = '添加' + titleName
        } else if(query.type == 'update') {
          titleName = '修改' + titleName
        } else if(query.type == 'look') {
          titleName = '查看' + titleName
        }
        return {
            type: query.type,
            titleName: titleName,
            id: query.id,
            questionList: [],
            activeName: [],
            form: {
                title: null,
                questionnaireQuestionList: [{questionnaireQuestionItemList: [{ }]}],
            },
            disabled: query.type == 'look' ? true : false,
            questionStatus: false
        }
    },
    async mounted () {
        if(this.type == 'update' || this.type == 'look') {
            try {
                let res = await questionnaireTopicGetDetail({ id: this.id })
                this.form = res.data
                this.questionList = res.data
                // let list = res.data.questionnaireQuestionList || []
                // list.forEach((item, index) => {
                //     this.activeName.push(index)
                // })
            } catch {
                //
            }
        }
    },
    methods: {
        getForms() {
            const { $refs: refs } = this;
            return [
                refs.form,
                ...(refs.questions || []),
            ].filter((item) => !!item).map((item) => item.$refs.form || item);
        },
        setResultSort() { // 给问答结果排序
            let form = this.form
            form.questionnaireQuestionList.forEach((item, index) => {
                item.sort = index
                let itemList = item.questionnaireQuestionItemList
                if(item.type != 'textarea') {
                    itemList.forEach((child, index) => {
                        child.sort = index
                    })
                } else {
                    itemList = []
                }
            })
        },
        onSubmit() {
            const forms = this.getForms();
            Promise.all(forms.map(this.getFormPromise)).then(async (res) => {
                const validateResult = res.every(item => !!item)
                console.log(validateResult)
                if(validateResult) {
                    this.setResultSort()
                    try {
                        if(this.type == 'create') {
                            await questionnaireTopicAdd(this.form)
                            this.$message.success('添加成功')
                        } else {
                            await questionnaireTopicUpdate(this.form)
                            this.$message.success('修改成功')
                        }
                        this.onCancel()
                    } catch {
                        //
                    }
                } else {
                    this.$nextTick(() => {
                        let isError = document.getElementsByClassName('is-error')
                        isError[0].scrollIntoView({
                            block: 'center',
                            behavior: 'smooth',
                        })
                    })
                    return false
                }
            })
        },
        getFormPromise(form) {
            return new Promise(resolve => {
                form.validate(res => {
                    resolve(res);
                })
            })
        },
        onPreview() {
            const forms = this.getForms();
            Promise.all(forms.map(this.getFormPromise)).then(async (res) => {
                const validateResult = res.every(item => !!item)
                if(validateResult) {
                    this.questionStatus = true
                }
            })
        },
        onReset() {
            this.form = {
                title: null,
                questionnaireQuestionList: [{questionnaireQuestionItemList: [{ }]}],
            }
            setTimeout(() => {
                const forms = this.getForms();
                for(let form of forms) {
                    form.clearValidate()
                }
            }, 30)
        },
        // 添加题目选项
        addQuestionItem(questionnaireQuestionList) {
            questionnaireQuestionList.push({questionnaireQuestionItemList: [{}]})
        },
        // 向上移动
        moveUp(arr, index) {
            arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
        },
        // 向下移动
        moveDown(arr, index) {
            arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));

        },
        // 删除选项
        onDelete(arr, index) {
            if(this.type == 'update') {
                if(this.form.delQuestionnaireQuestionIdList) {
                    this.form.delQuestionnaireQuestionIdList.push(arr[index].id)
                } else {
                    this.form.delQuestionnaireQuestionIdList = [arr[index].id]
                }
            }
            arr.splice(index, 1)
        },
        onCancel () {
            this.$store.dispatch('delVisitedViews', this.$route)
            this.$router.push({ path: '/operateManager/setQuestions' })
        },
    }
}
</script>
<style lang="scss" scoped>
/deep/.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
/deep/.el-date-editor.el-input {
  width: 100% !important;
}
/deep/.el-select {
  width: 98% !important;
}
/deep/.el-collapse {
    border: 0;
}
/deep/.el-collapse-item__wrap, /deep/.el-collapse-item__header {
    background-color: #eef4f9;
}
</style>