<template>
  <div v-loading="loading">
    <el-form
      v-if="isRender"
      ref="questionForm"
      size="small"
      :model="questionForm"
      style="width:100%;"
    >
      <qSFormItem
        v-for="question of questions"
        :key="question.Id"
        :question="question"
        :question-form="questionForm"
        :is-audit="isAudit"
        @resetFormItemData="resetFormItemData"
      />
    </el-form>
  </div>

</template>

<script>

import { getQCQuestionAnswer } from '@/api/trials'
import qSFormItem from './qsFormItem'
export default {
  name: 'QcQuestions',
  components: {
    qSFormItem
  },
  props: {
    trialId: {
      type: String,
      required: true
    },
    subjectVisitId: {
      type: String,
      required: true
    },
    qcProcessEnum: {
      type: Number,
      required: true
    },
    currentQCEnum: {
      type: Number,
      required: true
    },
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      questions: [],
      questionForm: {},
      isRender: false
    }
  },
  mounted() {
    this.getQuestions()
  },
  methods: {
    getQuestions() {
      this.loading = true
      var param = {
        trialId: this.trialId,
        subjectVisitId: this.subjectVisitId,
        qcProcessEnum: this.qcProcessEnum,
        currentQCEnum: this.currentQCEnum
      }
      getQCQuestionAnswer(param).then(res => {
        res.Result.map((v) => {
          this.$set(this.questionForm, v.Id, v.Answer)
          if (v.Childrens.length > 0) {
            this.setChild(v.Childrens)
          }
        })
        this.questions = res.Result

        this.isRender = true
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    setChild(obj) {
      obj.forEach(i => {
        this.$set(this.questionForm, i.Id, i.Answer)
        if (i.Childrens && i.Childrens.length > 0) {
          this.setChild(i.Childrens)
        }
      })
    },
    resetFormItemData(v) {
      this.questionForm[v] = ''
    },
    submit() {
      return new Promise((resolve, reject) => {
        this.$refs['questionForm'].validate(valid => {
          if (!valid) {
            this.$confirm(this.$t('trials:audit:message:specifyQuestions'), {
              type: 'warning',
              showCancelButton: false,
              callback: action => {}
            })
            reject()
          } else {
            var answers = []
            for (const k in this.questionForm) {
              answers.push({ Id: k, answer: this.questionForm[k] })
            }
            resolve(answers)
          // 设置当前节点的Answer
            // this.answers.forEach((item, index) => {
            //   if (item.IsShow) {
            //     this.$set(this.answers[index], 'Answer', this.questionForm[item.TrialQCQuestionConfigureId])
            //   }
            // })
            // resolve(this.answers)
          }
        })
      })
    }
  }
}
</script>

