<template>
  <div v-loading="loading" class="ecrf-wrapper">
    <el-form
      v-if="questions.length > 0"
      ref="questions"
      size="small"
      :model="questionForm"
    >
      <QuestionItem
        v-for="question of questions"
        :key="question.Id"
        :question="question"
        :question-form="questionForm"
        :reading-task-state="readingTaskState"
        :is-first-change-task="isFirstChangeTask"
        :visit-task-id="visitTaskId"
        @setFormItemData="setFormItemData"
        @resetFormItemData="resetFormItemData"
      />

      <el-form-item v-if="readingTaskState < 2 && !isFirstChangeTask">
        <div style="text-align:right">
          <el-button size="mini" :disabled="!questionFormChangeState" :type="questionFormChangeState ? 'primary' : null" @click="handleSave">{{ $t('common:button:save') }}</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>

import { saveImageQuality } from '@/api/trials'
import QuestionItem from './QuestionItem'
import DicomEvent from './DicomEvent'
import { mapGetters } from 'vuex'
import store from '@/store'
export default {
  name: 'ECRF',
  components: {
    QuestionItem
  },
  props: {
    questionFormChangeState: {
      type: Boolean,
      default: false
    },
    questionFormChangeNum: {
      type: Number,
      default: 0
    },
    isFirstChangeTask: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      questions: [],
      questionForm: {},
      readingTaskState: 2,
      visitTaskId: ''
    }
  },
  computed: {
    ...mapGetters(['visitTaskList', 'currentReadingTaskState'])
  },
  watch: {
    questionForm: {
      deep: true,
      immediate: false,
      handler(v) {
        DicomEvent.$emit('questionFormChange', true)
      }
    },
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.readingTaskState = val
        }
      }
    }
  },
  mounted() {
    DicomEvent.$on('setReadingState', readingTaskState => {
      this.readingTaskState = readingTaskState
    })
    DicomEvent.$on('handleSaveQuestions', readingTaskState => {
      this.handleSave()
    })
  },
  beforeDestroy() {
    DicomEvent.$off('setReadingState')
  },
  methods: {
    async getQuestions(visitTaskId) {
      this.visitTaskId = visitTaskId
      // const loading = this.$loading({ fullscreen: true })
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === visitTaskId)

      if (idx > -1) {
        this.readingTaskState = this.visitTaskList[idx].ReadingTaskState
        var questions = this.visitTaskList[idx].Questions
        questions.map((v) => {
          if (v.Type === 'group' && v.Childrens.length === 0) return
          if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary') {
            this.$set(this.questionForm, v.Id, v.Answer ? v.Answer : null)
          }
          if (v.Childrens.length > 0) {
            this.setChild(v.Childrens)
          }
        })
        this.questions = questions
      }
      // loading.close()
    },
    setChild(obj) {
      obj.forEach(i => {
        if (i.Type !== 'group' && i.Type !== 'summary' && i.Id) {
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
        }
        if (i.Childrens && i.Childrens.length > 0) {
          this.setChild(i.Childrens)
        }
      })
    },
    handleSave() {
      this.$refs['questions'].validate((valid) => {
        if (!valid) return
        this.loading = true
        var answers = []
        for (const k in this.questionForm) {
          answers.push({ id: k, answer: this.questionForm[k] })
        }
        var params = {
          visitTaskId: this.visitTaskId,
          answers: answers
        }
        saveImageQuality(params).then(async res => {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          var trialId = this.$route.query.trialId
          await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: trialId, visitTaskId: this.visitTaskId })
          this.getQuestions(this.visitTaskId)
          this.loading = false

          DicomEvent.$emit('questionFormChange', false)
          DicomEvent.$emit('getReportInfo', true)
          // DicomEvent.$emit('refreshVisitList', this.visitTaskId)
        }).catch(() => {
          this.loading = false
        })
      })
    },
    resetFormItemData(v) {
      this.questionForm[v] = null
    },
    setFormItemData(obj) {
      this.questionForm[obj.key] = obj.val
    }
  }
}
</script>
<style lang="scss" scoped>
  .ecrf-wrapper{
    >>>.el-form-item__label{
      color: #c3c3c3;
    }
    >>>.el-input__inner{
      background-color: transparent;
      color: #ddd;
      border: 1px solid #5e5e5e;
    }
    >>>.el-form-item{
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
    }
    >>>.el-form-item__content{
      flex: 1;
    }
    >>>.el-button--mini, .el-button--mini.is-round {
    padding: 7px 10px;
  }
    .el-form-item__content
    .el-select{
      width: 100%;
    }
  }

  </style>

