<template>
  <div v-loading="loading" style="min-height:400px;" class="ecrf-wrapper">
    <el-form
      v-if="isRender"
      ref="questions"
      size="small"
      :model="questionForm"
    >
      <template v-if="formType===2">
        <el-tabs v-model="activeName">
          <el-tab-pane
            v-for="q of questions"
            :key="q.PageName"
            :label="q.PageName"
            :name="q.PageName"
          >
            <div v-if="q.Childrens.length>0" :class="{'tabContent':publicQuestions.length>0}">
              <FormItem
                v-for="question of q.Childrens"
                :key="question.Id"
                :question="question"
                :question-form="questionForm"
                :reading-task-state="readingTaskState"
                :visit-task-id="visitTaskId"
                @setFormItemData="setFormItemData"
                @resetFormItemData="resetFormItemData"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
        <el-divider v-if="publicQuestions.length>0" content-position="left">
          <!-- 公共分页 -->
        </el-divider>
        <div v-for="q of publicQuestions" :key="q.PageName">
          <h4>{{ q.PageName }}</h4>
          <template v-if="q.Childrens.length>0">
            <FormItem
              v-for="question of q.Childrens"
              :key="question.Id"
              :question="question"
              :question-form="questionForm"
              :reading-task-state="readingTaskState"
              :visit-task-id="visitTaskId"
              @setFormItemData="setFormItemData"
              @resetFormItemData="resetFormItemData"
            />
          </template>
        </div>
      </template>
      <template v-else>
        <FormItem
          v-for="question of questions"
          :key="question.Id"
          :question="question"
          :question-form="questionForm"
          :reading-task-state="readingTaskState"
          :visit-task-id="visitTaskId"
          @setFormItemData="setFormItemData"
          @resetFormItemData="resetFormItemData"
        />
      </template>

      <!-- <FormItem
        v-for="question of questions"
        :key="question.Id"
        :question="question"
        :question-form="questionForm"
        :reading-task-state="readingTaskState"
        @resetFormItemData="resetFormItemData"
      /> -->
      <!-- <el-form-item v-if="readingTaskState < 2">
        <div style="text-align:center;">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </el-form-item> -->

      <el-form-item v-if="readingTaskState < 2">
        <div style="text-align:center;">
          <el-button type="primary" @click="handleSave">{{ $t('common:button:save') }}</el-button>
          <el-button type="primary" @click="handleSubmit">{{ $t('common:button:submit') }}</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 签名框 -->
    <el-dialog
      v-if="signVisible"
      :visible.sync="signVisible"
      :close-on-click-modal="false"
      width="600px"
      custom-class="base-dialog-wrapper"
    >
      <div slot="title">
        <span style="font-size:18px;">{{ $t('common:dialogTitle:sign') }}</span>
        <span style="font-size:12px;margin-left:5px">{{ `(${$t('common:label:sign')}${ currentUser })` }}</span>
      </div>
      <SignForm ref="signForm" :sign-code-enum="signCode" @closeDialog="closeSignDialog" />
    </el-dialog>
  </div>

</template>

<script>

import { getTrialReadingQuestion, saveVisitTaskQuestions, submitVisitTaskQuestionsInDto } from '@/api/trials'
import const_ from '@/const/sign-code'
import FormItem from './FormItem'
import SignForm from '@/views/trials/components/newSignForm'
// import { getToken } from '@/utils/auth'
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
export default {
  name: 'ECRF',
  components: {
    FormItem,
    SignForm
  },
  props: {
    trialId: {
      type: String,
      required: true
    },
    subjectId: {
      type: String,
      required: true
    },
    criterionId: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      questions: [],
      questionForm: {},
      publicQuestions: [],
      isRender: false,
      signVisible: false,
      signCode: null,
      currentUser: zzSessionStorage.getItem('userName'),
      readingTaskState: 0,
      activeName: 0,
      formType: null
    }
  },
  mounted() {
    this.getQuestions()
  },
  methods: {
    getQuestions() {
      this.loading = true
      var param = {
        readingQuestionCriterionTrialId: this.criterionId,
        visitTaskId: this.visitTaskId
      }
      getTrialReadingQuestion(param).then(res => {
        this.readingTaskState = res.OtherInfo.readingTaskState
        this.formType = res.OtherInfo.FormType
        if (res.OtherInfo.FormType === 2) {
          if (res.Result.MultiPage.length > 0) {
            res.Result.MultiPage.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 = res.Result.MultiPage
            this.activeName = res.Result.MultiPage[0].PageName
          }
          if (res.Result.PublicPage.length > 0) {
            res.Result.PublicPage.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.publicQuestions = res.Result.PublicPage
          }
        } else {
          res.Result.SinglePage.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 = res.Result.SinglePage
        }
        this.isRender = true
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    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({ readingQuestionTrialId: k, answer: this.questionForm[k] })
        }
        var params = {
          trialId: this.trialId,
          visitTaskId: this.visitTaskId,
          readingQuestionCriterionTrialId: this.criterionId,
          answerList: answers

        }
        saveVisitTaskQuestions(params).then(res => {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      })
    },
    handleSubmit() {
      this.$refs['questions'].validate((valid) => {
        if (!valid) return
        const { ImageAssessmentReportConfirmation } = const_.processSignature
        this.signCode = ImageAssessmentReportConfirmation
        this.signVisible = true
      })
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名并确认
    signConfirm(signInfo) {
      this.loading = true
      var answers = []
      for (const k in this.questionForm) {
        answers.push({ readingQuestionTrialId: k, answer: this.questionForm[k] })
      }
      var params = {
        data: {
          trialId: this.trialId,
          visitTaskId: this.visitTaskId,
          readingQuestionCriterionTrialId: this.criterionId,
          answerList: answers
        },
        signInfo: signInfo
      }
      submitVisitTaskQuestionsInDto(params).then(res => {
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.isEdit = false
          this.$refs['signForm'].btnLoading = false
          this.signVisible = false
          this.readingTaskState = 2
          window.opener.postMessage('refreshTaskList', window.location)
          this.$confirm(this.$t('trials:globalReview:message:msg2'), {
            type: 'warning',
            distinguishCancelAndClose: true
          })
            .then(() => {
              DicomEvent.$emit('getNextTask')
            })
            .catch(action => {

            })
          // window.location.reload()
          // window.opener.postMessage('refreshTaskList', window.location)
          // var token = getToken()
          // var subjectCode = this.$router.currentRoute.query.subjectCode
          // var criterionType = this.$router.currentRoute.query.criterionType
          // var readingTool = this.$router.currentRoute.query.readingTool
          // var isReadingTaskViewInOrder = this.$router.currentRoute.query.isReadingTaskViewInOrder
          // var trialReadingCriterionId = this.$router.currentRoute.query.TrialReadingCriterionId
          // const routeData = `/noneDicomReading?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${subjectCode}&subjectId=${this.subjectId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}&key=${new Date().getTime()}`
          // this.$router.push({ path: routeData })
          // this.$router.push({
          //   path: `/readingPage?subjectCode=${subjectCode}&subjectId=${this.subjectId}&trialId=${this.trialId}&TokenKey=${token}`
          // })
        }
        this.loading = false
      }).catch(_ => {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      })
    },
    resetFormItemData(v) {
      this.questionForm[v] = null
    },
    setFormItemData(obj) {
      this.questionForm[obj.key] = obj.val
    }
  }
}
</script>
<style lang="scss" scoped>
.tabContent{
  height:400px;
  overflow-y: auto;
}
</style>
