<template>
    <div>
        <a-modal :visible="visible" @ok="handOK" :confirmLoading="confirmLoading" @cancel="handCancle"
            width="900px" :maskClosable="false" :destroyOnClose="true">
            <div slot="title">{{editType==='add'?'创建':'编辑'}}测验</div>
            
            <div class="modal-box">
                <a-form :form="form" @submit="handOK" layout="horizontal">
                    <a-form-item label="学科：" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                        <a-select
                          placeholder="请选择" 
                          @change="subjectChange" 
                          :disabled="formData.totalQuestion>0"
                          showSearch 
                          :filterOption="filterOption" 
                          v-decorator="
                          [
                            'disciplineId',
                            {
                              rules: [{ required: true, message: '此项为必填!' }],
                              initialValue: formData.disciplineId || ''
                            }
                          ]"
                        >
                        <a-select-opt-group v-for="(val,key) in $store.state.baseInfo.SubjectsGroup" :key="key">
                            <span slot="label">{{key}}</span>
                            <a-select-option :value="v.id" v-for="v in val" :key="v.id">
                                {{v.name}}
                            </a-select-option>
                        </a-select-opt-group>
                      </a-select>
                    </a-form-item>

                    <a-form-item label="教材：" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                        <a-select
                          placeholder="请选择" 
                          @change="textbookChange"
                          :disabled="formData.totalQuestion>0"
                          v-decorator="
                          [
                            'textbookId',
                            {
                              rules: [{ required: true, message: '此项为必填!' }],
                              initialValue: formData.textbookId || ''
                            }
                          ]"
                        >
                          <a-select-option  v-for="item in textbookList" :value="item.id" :key="item.id">
                            {{item.name}}
                          </a-select-option>
                      </a-select>
                    </a-form-item>

                    
                    <a-form-item label="章节：" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                        <a-tree-select
                          placeholder="请选择"
                          :tree-data="chapterList"
                          :disabled="formData.totalQuestion>0"
                          :replaceFields="{
                            children:'children', 
                            title:'name', 
                            key:'id', 
                            value: 'id'
                          }"
                          v-decorator="
                          [
                            'chapterId',
                            {
                              rules: [{ required: true, message: '此项为必填!' }],
                              initialValue: formData.chapterId || ''
                            }
                          ]"
                        >
                      </a-tree-select>
                    </a-form-item>

                    <a-form-item label="测验名称：" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                        <a-input
                          placeholder="请输入" 
                          v-decorator="
                          [
                            'name',
                            {
                              rules: 
                                [{ required: true, message: '此项为必填!' },{max:30,message: '最大长度不能超过30个字符'}],
                                initialValue: formData.name || ''
                            }
                          ]" 
                        />
                    </a-form-item>
                    <a-form-item label="测验时间：" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                        <a-input
                          placeholder="请输入" 
                          suffix="分钟"
                          v-decorator="
                          [
                            'testingTime',
                            {
                              rules: 
                                [{ required: true, message: '此项为必填!' }],
                                initialValue: formData.testingTime || '30'
                            }
                          ]" 
                        >
                        </a-input>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>
<script>
    import { TextbookGetList, ChapterGetAllByTextbookList, TestingCreate, TestingUpdate } from '@/api/api'
    import { listToTree } from '@/utils/tools'
    export default {
        components: {
            
        },
        data() {
            return {
                confirmLoading: false,
                visible: false,
                editType: 'add',
                formData:{},
                textbookList:[],
                chapterList: [],
                form: this.$form.createForm(this),
            };
        },
        computed: {
        },
        mounted() {

        },
        methods: {
            showModal(type,data) {
                this.editType = type;
                if ( type === 'edit' ) {
                  this.getTextbookList(data.disciplineId)
                  this.getChapterList(data.textbookId)
                }
                this.formData = data
                this.visible = true;
            },
            //表单确认
            handOK(e) {
              const self = this
                e.preventDefault();
                self.form.validateFields((err, values) => {
                    if (!err) {
                      self.confirmLoading = true;
                        console.log('handOK', values);
                        if(self.editType === 'add') {
                          TestingCreate(values)
                          .then(() =>{
                            self.confirmLoading = false;
                            self.$message.success('添加成功')
                            self.$parent._TestingGetList();
                            self.handCancle();
                          })
                          .catch(err =>{
                            self.confirmLoading = false;
                            console.log('TestingCreate error',err)
                            //self.$message.error(err.message)
                          })
                        }
                        if(self.editType === 'edit') {
                          const params = {
                                id: self.formData.id
                            }
                          TestingUpdate(values, params)
                          .then(() =>{
                            self.confirmLoading = false;
                            self.$message.success('编辑成功')
                            self.$parent._TestingGetList();
                            self.handCancle();
                          })
                          .catch(err =>{
                            self.confirmLoading = false;
                            console.log('TestingUpdate error',err)
                            //self.$message.error(err.message)
                          })
                        }
                    }
                })
            },
            handCancle() {
                this.visible = false;
                this.textbookList = []
            },
            subjectChange(value) {
              //console.log('subjectChange',value);
              this.form.setFieldsValue({
                  textbookId: '',
                  chapterId: '',
              })
              this.getTextbookList(value)
              this.chapterList = []
            },
            filterOption(input, option){
              if ( option.componentOptions.children[0].children ) {
                return option.componentOptions.children[0].children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
              } else {
                return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            },
            getTextbookList(disciplineId) {
              const self = this
              TextbookGetList({disciplineId:disciplineId})
              .then(res=>{
                self.textbookList = res.items
              })
              .catch(err => {
                self.textbookList = []
              })
            },
            textbookChange(value) {
              this.form.setFieldsValue({
                  chapterId: '',
              })
              this.getChapterList(value)
            },
            getChapterList(textbookId) {
              const self = this
              ChapterGetAllByTextbookList({textbookId:textbookId})
              .then(res=>{
                if ( res.length > 0) {
                  self.chapterList = listToTree(res) 
                } else {
                  self.chapterList = []
                }
              })
              .catch(err => {
                self.chapterList = []
              })

            }
        },
    };
</script>
<style scoped>
</style>