<template>
  <a-modal
    :confirmLoading='confirmLoading'
    :maskClosable='false'
    :title='title'
    :visible='visible'
    :width='800'
    @cancel='handleCancel'
    @ok='handleOk'>

    <a-spin :spinning='confirmLoading'>
      <a-form-model ref='form' :label-col='labelCol' :model='model' :rules='validatorRules' :wrapper-col='wrapperCol'>
        <!-- 主表单区域 -->
        <a-row :gutter='0' class='form-row'>
          <a-col :lg='12'>
            <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='类别' prop='type'>
              <j-dict-select-tag v-model='model.type' v-decorator="[ 'type', {'initialValue':0}]" dictCode='topic_type'
                                 placeholder='请选择类别' type='list' />
            </a-form-model-item>
          </a-col>
          <a-col :lg='12'>
            <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='题目' prop='question'>
              <!--              <j-input-pop v-model='model.question' placeholder='请输入题目' rows='4' />-->
              <a-textarea v-model='model.question' placeholder='请输入问题' rows='2' />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter='0' class='form-row'>
          <a-col :lg='12'>
            <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='题型' prop='optionType'>
              <j-dict-select-tag v-model='model.optionType' v-decorator="[ 'optionType', {'initialValue':0}]"
                                 dictCode='option_type' placeholder='请选择题型' type='radio' />
            </a-form-model-item>
          </a-col>
          <a-col :lg='12'>
            <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='题目解析' prop='topicAnalysis'>
              <a-textarea v-model='model.topicAnalysis' placeholder='请输入题目解析' rows='2' />
              <!--              <j-input-pop v-model='model.topicAnalysis' placeholder='请输入题目解析' rows='4' />-->
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter='0' class='form-row'>
          <a-col v-if='model.type==2' :lg='12'>
            <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='答案' prop='answer' required>
              <j-dict-select-tag v-model='model.answer' v-decorator="[ 'answer', {'initialValue':0}]"
                                 dictCode='answer_number'
                                 placeholder='请选择答案'
                                 type='radio' />
            </a-form-model-item>
          </a-col>
          <a-col v-if='model.type==2' :lg='12'>
            <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='积分' prop='score'>
              <a-input-number v-model='model.score' :max='10000' :min='0' />
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 子表单区域 -->
        <a-tabs v-model='activeKey' @change='handleChangeTabs'>
          <a-tab-pane key='1' :forceRender='true' tab='选项列表'>
            <j-editable-table
              ref='editableTable1'
              :actionButton='true'
              :columns='table1.columns'
              :dataSource='table1.dataSource'
              :loading='table1.loading'
              :maxHeight='300'
              :rowNumber='true'
              :rowSelection='true' />

          </a-tab-pane>

        </a-tabs>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>

import JEditableTable from '@/components/jeecg/JEditableTable'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED, validateFormModelAndTables } from '@/utils/JEditableTableUtil'
import { getAction, httpAction } from '@/api/manage'
import JDate from '@/components/jeecg/JDate'

export default {
  name: 'QuestionModal',
  components: {
    JDate, JEditableTable
  },
  data() {
    return {
      title: '操作',
      visible: false,
      confirmLoading: false,
      model: { optionType: 0 },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      },
      activeKey: '1',
      // 客户信息
      table1: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '选项编号',
            key: 'number',
            width: '15%',
            type: FormTypes.select,
            dictCode: 'answer_number',
            defaultValue: '0',
            placeholder: '请选择${title}'
          },
          {
            title: '选项内容',
            key: 'options',
            width: '75%',
            type: FormTypes.input_pop,
            defaultValue: '',
            placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          }
        ]
      },
      validatorRules: {
        question: [
          { required: true, message: '请输入问题!' }
        ],
        optionType: [
          { required: true, message: '请选择题型！' }
        ],
        type: [
          { required: true, message: '请选择类别！' }
        ],
        answer: [
          { required: true, message: '请选择答案代号!' }
        ],
        score: [{ required: true, message: '请输入积分!' }]
      },
      url: {
        add: '/publish/question/add',
        edit: '/publish/question/edit',
        orderCustomerList: '/publish/question/queryOptionsByQuestionId'
      }
    }
  },
  created() {
  },
  methods: {
    // 获取所有的editableTable实例
    getAllTable() {
      return Promise.all([
        getRefPromise(this, 'editableTable1')
      ])
    },

    add() {
      // 默认新增一条数据
      this.getAllTable().then(editableTables => {
        editableTables[0].add()
      })

      this.edit({})
    },
    edit(record) {
      this.visible = true
      this.activeKey = '1'
      this.model = Object.assign({}, record)
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestTableData(this.url.orderCustomerList, params, this.table1)
      }

    },
    close() {
      this.visible = false
      this.model.question = ''
      this.model = {}
      this.getAllTable().then(editableTables => {
        editableTables[0].initialize()
      })
      this.$emit('close')
      this.$refs.form.resetFields()
    },
    /** 查询某个tab的数据 */
    requestTableData(url, params, tab) {
      tab.loading = true
      getAction(url, params).then(res => {
        console.log(res)
        tab.dataSource = res.result || []
      }).finally(() => {
        tab.loading = false
      })
    },
    handleOk() {
      this.validateFields()
    },
    handleCancel() {
      this.close()
    },
    /** ATab 选项卡切换事件 */
    handleChangeTabs(key) {
      getRefPromise(this, `editableTable${key}`).then(editableTable => {
        editableTable.resetScrollTop()
      })
    },

    /** 触发表单验证 */
    validateFields() {
      this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormModelAndTables(this.$refs.form, this.model, tables)
      }).then(allValues => {
        let formData = this.classifyIntoFormData(allValues)
        // 发起请求
        return this.requestAddOrEdit(formData)
      }).catch(e => {
        if (e.error === VALIDATE_NO_PASSED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : (e.index + 1).toString()
        } else {
          console.error(e)
        }
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let question = Object.assign(this.model, allValues.formValue)
      return {
        ...question, // 展开
        options: allValues.tablesValue[0].values
      }
    },
    /** 发起新增或修改的请求 */
    requestAddOrEdit(formData) {
      let url = this.url.add, method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      httpAction(url, formData, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    }

  }
}
</script>

<style scoped>
</style>