<template>
  <div v-loading="loading" class="questionList-wrapper">
    <div class="container">
      <div class="basic-info">
        <h3 v-if="taskInfo && taskInfo.IsReadingShowSubjectInfo">
          <span v-if="visitInfo.SubjectCode">{{ visitInfo.SubjectCode }} </span>
          <span style="margin-left:5px;">{{ visitInfo.TaskBlindName }}</span>
        </h3>
        <div v-if="readingTaskState < 2">
          <el-tooltip class="item" effect="dark" :content="$t('trials:dicomReading:message:confirmReset')"
            placement="bottom">
            <i class="el-icon-refresh-left" @click="resetForm" />
          </el-tooltip>
        </div>
      </div>
      <el-form v-if="taskInfo && rerender" ref="questions" size="small" :model="questionForm" class="ecrf-form">
        <template v-if="rerender">
          <QuestionFormItem v-for="question of questions" :key="question.Id" :visit-task-id="visitTaskId"
            :question="question" :question-form="questionForm" :reading-task-state="readingTaskState"
            :criterion-id="criterionId" :calculation-list="calculationList"
            :question-mark-info-list="questionMarkInfoList" :questions-mark-status="questionsMarkStatus"
            :is-baseline="isBaseLineTask" @resetFormItemData="resetFormItemData" @setFormItemData="setFormItemData"
            @getQuestions="getQuestions" @operateImageMarker="operateImageMarker"
            @unBindAnnotationToQuestion="unBindAnnotationToQuestion" />
        </template>

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

    <!-- 签名框 -->
    <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 { getCustomTableQuestionAnswer, changeDicomReadingQuestionAnswer, submitVisitTaskQuestionsInDto, verifyVisitTaskQuestions, getQuestionCalculateRelation, saveTaskQuestion } from '@/api/trials'
import { setSkipReadingCache, resetReadingTask, saveTableQuestionMark } from '@/api/reading'
import const_ from '@/const/sign-code'
import QuestionFormItem from './QuestionFormItem'
import SignForm from '@/views/trials/components/newSignForm'
import store from '@/store'
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
export default {
  name: 'EcrfList',
  components: {
    QuestionFormItem,
    SignForm
  },
  props: {
    visitInfo: {
      type: Object,
      required: true
    },
    readingTaskState: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      trialId: '',
      criterionId: '',
      visitTaskId: '',
      loading: false,
      questions: [],
      questionForm: {},
      publicQuestions: [],
      signVisible: false,
      signCode: null,
      currentUser: zzSessionStorage.getItem('userName'),
      activeName: 0,
      classArr: [],
      calculationList: [],
      taskInfo: null,
      isBaseLineTask: false,
      rerender: true,
      questionMarkInfoList: [],
      operateStateEnum: null, // 0：绑定；1：标记；2：查看；3：更改；4：移除；5：保存；6：更改数值内容；
      operateQuestionId: '',
      operateRowId: '',
      operateParentQsId: '',
      isTableQuestion: false,
      imageTool: '',
      imageToolAttribute: '',
      questionsMarkStatus: {},
      digitPlaces: 2,
      questionImageToolAttributeInfo: {},
      unSaveTargets: []
    }
  },
  mounted() {
    window.addEventListener('message', this.receiveMsg)
    this.trialId = this.$route.query.trialId
    this.visitTaskId = this.visitInfo.VisitTaskId
    this.taskInfo = JSON.parse(sessionStorage.getItem('taskInfo'))
    this.isBaseLineTask = this.taskInfo.IsBaseLine
    this.criterionId = this.taskInfo.TrialReadingCriterionId
    const digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.getQuestionCalculateRelation()
    this.getQuestions(true)
  },
  methods: {
    async getQuestions(isInit) {
      this.loading = true
      try {
        const param = {
          visitTaskId: this.visitTaskId
        }
        const res = await getCustomTableQuestionAnswer(param)
        if (res.IsSuccess) {
          // this.readingTaskState = res.OtherInfo.ReadingTaskState
          res.Result.SinglePage.map((v) => {
            if (v.Type === 'group' && v.Childrens.length === 0) return
            if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary' && v.Type !== 'table' && v.Type !== 'basicTable' && v.Type !== 'number') {
              this.$set(this.questionForm, v.Id, v.Answer)
            }
            if (v.Type === 'table' || v.Type === 'basicTable') {
              this.$set(this.questionForm, v.Id, v.TableQuestions.Answers)
            }
            if (v.Type === 'class') {
              this.classArr.push({ triggerId: v.ClassifyQuestionId, classId: v.Id, classifyAlgorithms: v.ClassifyAlgorithms, classifyType: v.ClassifyType })
            }
            if (v.Type === 'number') {
              this.$set(this.questionForm, v.Id, isNaN(parseFloat(v.Answer)) ? v.Answer : parseFloat(v.Answer).toFixed(this.digitPlaces))
              if (v.ImageToolAttribute) {
                this.$set(this.questionImageToolAttributeInfo, v.Id, v.ImageToolAttribute)
              }
            }
            if (v.Childrens.length > 0) {
              this.setChild(v.Childrens)
            }
          })
          this.questions = res.Result.SinglePage
          this.questionsMarkStatus = {}
          this.questionMarkInfoList = res.OtherInfo.QuestionMarkInfoList.map(i => {
            if (i.RowId) {
              this.$set(this.questionsMarkStatus, `${i.RowId}_${i.TableQuestionId}`, { isMarked: i.MeasureData !== '', isSaved: true, OrderMarkName: i.OrderMarkName })
            } else if (i.QuestionId) {
              this.$set(this.questionsMarkStatus, i.QuestionId, { isMarked: i.MeasureData !== '', isSaved: true, OrderMarkName: i.OrderMarkName })
            }
            if (typeof i.MeasureData === 'string' && i.MeasureData) {
              i.MeasureData = JSON.parse(i.MeasureData)
            }
            return i
          })
          if (!isInit) {
            this.$emit('resetAnnotations', this.visitTaskId)
          }
          this.loading = false
        }
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    setChild(obj) {
      obj.forEach(i => {
        if (i.Type !== 'group' && i.Type !== 'summary' && i.Id && i.Type !== 'table' && i.Type !== 'basicTable') {
          this.$set(this.questionForm, i.Id, i.Answer)
        }
        if (i.Type === 'table' || i.Type === 'basicTable') {
          i.TableQuestions.Questions.forEach(o => {
            if (o.Type === 'number') {
              i.TableQuestions.Answers.forEach((ite, index) => {
                this.$set(i.TableQuestions.Answers[index], o.Id, isNaN(parseFloat(i.TableQuestions.Answers[index][o.Id])) ? i.TableQuestions.Answers[index][o.Id] : parseFloat(i.TableQuestions.Answers[index][o.Id]).toFixed(this.digitPlaces))
              })
            }
          })
          this.$set(this.questionForm, i.Id, i.TableQuestions.Answers)
        }
        if (i.Type === 'class') {
          this.classArr.push({ triggerId: i.ClassifyQuestionId, classId: i.Id, classifyAlgorithms: i.ClassifyAlgorithms, classifyType: i.ClassifyType })
        }
        if (i.Type === 'number') {
          this.$set(this.questionForm, i.Id, isNaN(parseFloat(i.Answer)) ? i.Answer : parseFloat(i.Answer).toFixed(this.digitPlaces))
          if (i.ImageToolAttribute) {
            this.$set(this.questionImageToolAttributeInfo, i.Id, i.ImageToolAttribute)
          }
        }
        if (i.Childrens && i.Childrens.length > 0) {
          this.setChild(i.Childrens)
        }
      })
    },
    async getQuestionCalculateRelation() {
      try {
        const res = await getQuestionCalculateRelation({ TrialReadingCriterionId: this.criterionId })
        this.calculationList = res.Result
      } catch (e) {
        console.log(e)
      }
    },
    async handleSave(isMsg) {
      const valid = await this.$refs['questions'].validate()
      if (!valid) return
      this.loading = true
      try {
        var answers = []
        for (const k in this.questionForm) {
          if (this.questionForm[k] instanceof Array) { } else {
            answers.push({ id: k, answer: this.questionForm[k] })
          }
        }
        var params = {
          visitTaskId: this.visitTaskId,
          answers: answers
        }
        const res = await changeDicomReadingQuestionAnswer(params)
        if (res.IsSuccess) {
          if (isMsg) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
          this.loading = false
        }
      } catch (e) {
        this.loading = false
      }
    },
    async handleSubmit() {
      const valid = await this.$refs['questions'].validate()
      if (!valid) return
      await this.handleSave(false)
      await verifyVisitTaskQuestions({ visitTaskId: this.visitTaskId })
      const { ImageAssessmentReportConfirmation } = const_.processSignature
      this.signCode = ImageAssessmentReportConfirmation
      this.signVisible = true
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名并确认
    async signConfirm(signInfo) {
      this.loading = true
      var answers = []
      for (const k in this.questionForm) {
        if (this.questionForm[k] instanceof Array) { } else {
          answers.push({ readingQuestionTrialId: k, answer: this.questionForm[k] })
        }
      }
      var params = {
        data: {
          trialId: this.trialId,
          visitTaskId: this.visitTaskId,
          readingQuestionCriterionTrialId: this.criterionId,
          answerList: answers
        },
        signInfo: signInfo
      }
      try {
        const res = await submitVisitTaskQuestionsInDto(params)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.isEdit = false
          this.$refs['signForm'].btnLoading = false
          this.signVisible = false
          this.$emit('setReadingTaskState', 2)
          window.opener.postMessage('refreshTaskList', window.location)
          const confirm = await this.$confirm(
            this.$t('trials:noneDicoms:message:msg1'),
            {
              type: 'warning',
              distinguishCancelAndClose: true
            }
          )
          if (confirm !== 'confirm') return
          window.location.reload()
        }
      } catch (e) {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      }
    },
    async skipTask() {
      try {
        // 是否确认跳过？
        const confirm = await this.$confirm(
          this.$t('trials:readingReport:message:skipConfirm'),
          {
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
        if (confirm !== 'confirm') return
        this.loading = true
        const res = await setSkipReadingCache({ visitTaskId: this.visitTaskId })
        this.loading = false
        if (res.IsSuccess) {
          window.location.reload()
        }
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    resetFormItemData(v) {
      this.questionForm[v] = null
    },
    setFormItemData(obj) {
      this.$set(this.questionForm, obj.key, JSON.parse(JSON.stringify(obj.val)))
      this.classArr.map(i => {
        if (i.triggerId === obj.key) {
          let answer = null
          const list = JSON.parse(i.classifyAlgorithms)
          if (i.classifyType === 0) {
            const o = list.find(v => {
              return (
                parseFloat(obj.val) >= parseFloat(v.gt) &&
                parseFloat(obj.val) < parseFloat(v.lt)
              )
            })
            answer = o ? o.label : null
          } else if (i.classifyType === 1) {
            const o = list.find(v => {
              return v.val.includes(obj.val)
            })
            answer = o ? o.label : null
          }
          this.$set(this.questionForm, i.classId, answer)
        }
      })
    },

    verifyAnnotationIsBound(annotation) {
      const i = this.questionMarkInfoList.findIndex(i => i.MeasureData && i.MeasureData.annotationUID === annotation.annotationUID)
      return i > -1
    },
    // async operateImageMarker(obj) {
    //   this.operateStateEnum = obj.operateStateEnum
    //   this.isTableQuestion = obj.question.IsTableQuestion ? true : false
    //   this.imageTool = obj.question.ImageTool
    //   this.imageToolAttribute = obj.question.ImageToolAttribute
    //   this.operateQuestionId = obj.question.Id
    //   this.operateRowId = obj.question.RowId
    //   this.operateParentQsId = obj.question.ParentQsId
    //   if (obj.operateStateEnum === 0) { 
    //     // 绑定标记
    //     this.$emit('setReadingToolPassive')
    //   } else if (obj.operateStateEnum === 1) {
    //     // 添加标记
    //     this.$emit('setReadingToolActive', obj.question.ImageTool)
    //   } else if (obj.operateStateEnum === 2) {
    //     // 查看标记
    //     let i = -1
    //     if (this.isTableQuestion) {
    //       if (this.operateRowId) {
    //         i = this.questionMarkInfoList.findIndex(i => i.TableQuestionId === obj.question.Id && i.RowId === this.operateRowId)
    //       } else {
    //         i = this.questionMarkInfoList.findIndex(i => i.TableQuestionId === obj.question.Id && !i.RowId)
    //       }
    //     } else {
    //       i = this.questionMarkInfoList.findIndex(i => i.QuestionId === obj.question.Id)
    //     }
    //     if (i > -1) {
    //       const annotation = this.questionMarkInfoList[i].MeasureData
    //       this.$emit('viewCustomAnnotationSeries', { visitTaskId: this.visitTaskId, annotation })
    //     }
    //   } else if (obj.operateStateEnum === 3) {
    //     // 更改标记
    //     this.$emit('setReadingToolPassive')
    //   } else if (obj.operateStateEnum === 4) {
    //     this.$emit('setReadingToolPassive')
    //     // 移除标记
    //     let i = -1
    //     let questionMarkInfo = {}
    //     if (this.isTableQuestion) {
    //       if (this.operateRowId) {
    //         i = this.questionMarkInfoList.findIndex(i => i.TableQuestionId === obj.question.Id && i.RowId === this.operateRowId)
    //       } else {
    //         i = this.questionMarkInfoList.findIndex(i => i.TableQuestionId === obj.question.Id && !i.RowId)
    //       }
    //     } else {
    //       this.$set(this.questionForm, obj.question.Id, '')
    //       i = this.questionMarkInfoList.findIndex(i => i.QuestionId === obj.question.Id)
    //     }
    //     if (i === -1) return
    //     this.questionMarkInfoList[i].MeasureData = ''
    //     this.questionMarkInfoList[i].StudyId = ''
    //     this.questionMarkInfoList[i].SeriesId = ''
    //     this.questionMarkInfoList[i].InstanceId = ''
    //     questionMarkInfo = this.questionMarkInfoList[i]
    //     questionMarkInfo.isMarked = false
    //     questionMarkInfo.isSaved = false
    //     this.$set(this.questionsMarkStatus, this.operateRowId ? `${this.operateRowId}_${obj.question.Id}` : obj.question.Id, questionMarkInfo)
    //   } else if (obj.operateStateEnum === 5) {
    //     // 保存外层标记
    //     this.loading = true
    //     try {
    //       const answers = []
    //       answers.push({ id: obj.question.Id, answer: this.questionForm[obj.question.Id] })
    //       const markInfo = []
    //       const i = this.questionMarkInfoList.findIndex(i => i.QuestionId === this.operateQuestionId)
    //       if (i > -1) {
    //         const obj = Object.assign({}, this.questionMarkInfoList[i])
    //         obj.MeasureData = obj.MeasureData ? JSON.stringify(obj.MeasureData) : ''
    //         markInfo.push(obj)
    //       }
    //       // 上传截图
    //       const params = {
    //         visitTaskId: this.visitTaskId,
    //         answers: answers,
    //         questionMarkInfoList: markInfo
    //       }
    //       await saveTaskQuestion(-10, params)

    //       this.$set(this.questionsMarkStatus, obj.question.Id, {isMarked: this.questionMarkInfoList[i].MeasureData ? true : false, isSaved: true})
    //       this.loading = false
    //     } catch (e) {
    //       console.log(e)
    //       this.loading = false
    //     }
    //   } else if (obj.operateStateEnum === 6) {
    //     // 更改数值内容
    //     let questionMarkInfo = {}
    //     if (this.isTableQuestion) {
    //       questionMarkInfo.isMarked = false
    //       questionMarkInfo.isSaved = false
    //     } else {
    //       questionMarkInfo.isMarked = false
    //       questionMarkInfo.isSaved = false
    //     }
    //     this.$set(this.questionsMarkStatus, this.operateRowId ? `${this.operateRowId}_obj.question.Id` : obj.question.Id, questionMarkInfo)
    //   } else if (obj.operateStateEnum === 7) {
    //     // 保存表格问题标记
    //     const loading = this.$loading({ fullscreen: true })
    //     try {
    //       let annotation = null
    //       if (!this.operateRowId && obj.rowId && obj.question.ParentQsId) {
    //         this.operateRowId = obj.rowId
    //         this.questionMarkInfoList.forEach(item => {
    //           if (item.QuestionId === obj.question.ParentQsId && !item.RowId) {
    //             item.RowId = obj.rowId
    //             let questionMarkStatus = Object.assign({}, this.questionsMarkStatus[item.TableQuestionId])
    //             delete this.questionsMarkStatus[item.TableQuestionId]
    //             if (item.TableQuestionId === this.operateQuestionId) {
    //               annotation = item.MeasureData
    //               this.$set(this.questionsMarkStatus, `${obj.rowId}_${item.TableQuestionId}`, questionMarkStatus)
    //             } else {
    //               this.$set(this.questionsMarkStatus, `${obj.rowId}_${item.TableQuestionId}`, {isMarked: item.MeasureData ? true : false, isSaved: false})
    //             }

    //           }
    //         })
    //       } else if (this.operateRowId && this.operateQuestionId) {
    //         const i = this.questionMarkInfoList.findIndex(i => i.RowId === this.operateRowId && i.TableQuestionId === this.operateQuestionId)
    //         if (i === -1) return
    //         annotation = this.questionMarkInfoList[i].MeasureData
    //       }
    //       let picturePath = ''
    //       if (annotation) {
    //         // 上传截图
    //         const base64Str = await this.getScreenshots({ visitTaskId: this.visitTaskId, annotation })
    //         const pictureObj = await this.uploadScreenshots(`${new Date().getTime()}`, base64Str)
    //         picturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
    //       }
    //       let params = {
    //         Answer: obj.answer,
    //         VisitTaskId: this.visitTaskId,
    //         QuestionId: obj.question.ParentQsId,
    //         InstanceId: annotation ? annotation.instanceId : '',
    //         SeriesId: annotation ? annotation.seriesId : '',
    //         StudyId: annotation ? annotation.studyId : '',
    //         MarkTool: annotation ? annotation.markTool : '',
    //         PicturePath: picturePath,
    //         NumberOfFrames: annotation ? annotation.numberOfFrames : null,
    //         MeasureData: annotation ? JSON.stringify(annotation) : '',
    //         QuestionType: 0,
    //         OrderMarkName: annotation ? annotation.data.label : '',
    //         RowId: this.operateRowId,
    //         TableQuestionId: this.operateQuestionId,
    //         RowIndex: obj.rowIndex
    //       }
    //       // 保存标记
    //       await saveTableQuestionMark(params, -10)
    //       this.$set(this.questionsMarkStatus, `${this.operateRowId}_${this.operateQuestionId}`, {isMarked: annotation ? true : false, isSaved: true})
    //       this.resetOperateState()
    //       loading.close()
    //     } catch(e) {
    //       console.log(e)
    //       loading.close()
    //     }
    //   }
    // },
    async operateImageMarker(obj) {
      const STATE = {
        BIND: 0,       // 绑定标记
        ADD: 1,        // 添加标记
        VIEW: 2,       // 查看标记
        CHANGE: 3,     // 更改标记
        REMOVE: 4,     // 移除标记
        SAVE_OUTER: 5, // 保存外层标记
        UPDATE: 6,     // 更改数值内容
        SAVE_TABLE: 7  // 保存表格标记
      }
      const { question, operateStateEnum, rowId, answer } = obj
      const { Id, IsTableQuestion, ImageTool, ImageToolAttribute, ParentQsId, RowId } = question

      Object.assign(this, {
        operateStateEnum,
        isTableQuestion: !!IsTableQuestion,
        imageTool: ImageTool,
        imageToolAttribute: ImageToolAttribute,
        operateQuestionId: Id,
        operateRowId: RowId,
        operateParentQsId: ParentQsId
      })
      const stateHandlers = {
        [STATE.BIND]: () => this.$emit('setReadingToolPassive'),
        [STATE.ADD]: () => this.$emit('setReadingToolActive', ImageTool),
        [STATE.VIEW]: this.handleViewAnnotation,
        [STATE.CHANGE]: () => this.$emit('setReadingToolPassive'),
        [STATE.REMOVE]: this.handleRemoveAnnotation,
        [STATE.SAVE_OUTER]: this.handleSaveOuterQuestions,
        [STATE.UPDATE]: this.handleUpdateValue,
        [STATE.SAVE_TABLE]: this.handleSaveTableQuestions
      }

      const handler = stateHandlers[operateStateEnum]
      handler && await handler.call(this, obj)
    },
    async handleViewAnnotation(obj) {
      const index = this.findMarkIndex(obj.question)
      if (index === -1) return
      const annotation = this.questionMarkInfoList[index].MeasureData
      this.$emit('viewCustomAnnotationSeries', {
        visitTaskId: this.visitTaskId,
        annotation
      })
    },
    handleRemoveAnnotation(obj) {
      const index = this.findMarkIndex(obj.question)
      if (index === -1) return
      Object.assign(this.questionMarkInfoList[index], {
        MeasureData: '',
        StudyId: '',
        SeriesId: '',
        InstanceId: '',
        OrderMarkName: '',
        PicturePath: ''
      })
      const key = this.operateRowId
        ? `${this.operateRowId}_${obj.question.Id}`
        : obj.question.Id
      this.$set(this.questionsMarkStatus, key, {
        isMarked: false,
        isSaved: false,
      })
    },
    async handleSaveOuterQuestions(obj) {
      this.loading = true;
      try {
        const answers = [{ id: obj.question.Id, answer: this.questionForm[obj.question.Id] }]
        const markInfo = []
        const index = this.questionMarkInfoList.findIndex(
          item => item.QuestionId === this.operateQuestionId
        )

        if (index > -1) {
          const item = { ...this.questionMarkInfoList[index] }
          item.MeasureData = item.MeasureData ? JSON.stringify(item.MeasureData) : ''
          markInfo.push(item)
        }
        let annotation = null
        if (!this.operateRowId && obj.rowId) {
          this.operateRowId = obj.rowId
          // this.updateQuestionsMarkStatus(obj)
        }
        annotation = this.getAnnotationByRow(obj.question.Id, false)
        // 截图上传
        let picturePath = obj.picturePath
        if (annotation) {
          const base64Str = await this.getScreenshots({
            visitTaskId: this.visitTaskId,
            annotation
          })
          if (!picturePath) {
            const pictureObj = await this.uploadScreenshots(`${Date.now()}`, base64Str)
            picturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
          }
          markInfo[0].PicturePath = picturePath
        }
        if (markInfo && markInfo.length > 0) {
          markInfo[0].MarkId = annotation ? annotation.annotationUID : null
        }
        await saveTaskQuestion(-10, {
          visitTaskId: this.visitTaskId,
          answers,
          questionMarkInfoList: markInfo
        })
        this.$set(this.questionsMarkStatus, obj.question.Id, {
          isMarked: !!this.questionMarkInfoList[index]?.MeasureData,
          isSaved: true,
          OrderMarkName: index > -1 ? this.questionMarkInfoList[index].OrderMarkName : ''
        })
        this.resetOperateState()
        if (annotation) {
          for (let i = 0; i < this.questionMarkInfoList.length; i++) {
            const item = this.questionMarkInfoList[i]
            if (!item.MeasureData || item.MeasureData.annotationUID !== annotation.annotationUID) continue
            const isTableMode = item.TableQuestionId
            if (!isTableMode && this.questionsMarkStatus[item.QuestionId] && !this.questionsMarkStatus[item.QuestionId].isSaved && this.questionsMarkStatus[item.QuestionId].isMarked) {
              DicomEvent.$emit('operateImageMarker', { QuestionId: item.QuestionId, operateStateEnum: 5, picturePath })
              break
            }
          }
        }
      } catch (e) {
        console.error('保存失败:', e)
      } finally {
        this.loading = false
      }
    },
    handleUpdateValue(obj) {
      const key = this.operateRowId
        ? `${this.operateRowId}_${obj.question.Id}`
        : obj.question.Id
      this.$set(this.questionsMarkStatus, key, {
        isMarked: false,
        isSaved: false,
      })
    },
    async handleSaveTableQuestions(obj) {
      const loading = this.$loading({ fullscreen: true })
      try {
        let annotation = null
        if (!this.operateRowId && obj.rowId && obj.question.ParentQsId) {
          this.operateRowId = obj.rowId
          this.updateQuestionsMarkStatus(obj)
        }
        annotation = this.getAnnotationByRow(this.operateRowId)
        // 截图上传
        let picturePath = obj.picturePath
        if (annotation && !picturePath) {
          const base64Str = await this.getScreenshots({
            visitTaskId: this.visitTaskId,
            annotation
          })
          const pictureObj = await this.uploadScreenshots(`${Date.now()}`, base64Str)
          picturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
        }
        await saveTableQuestionMark({
          Answer: obj.answer,
          VisitTaskId: this.visitTaskId,
          QuestionId: obj.question.ParentQsId,
          ...(annotation ? {
            InstanceId: annotation.instanceId,
            SeriesId: annotation.seriesId,
            StudyId: annotation.studyId,
            MarkTool: annotation.markTool,
            NumberOfFrames: annotation.numberOfFrames,
            MeasureData: JSON.stringify(annotation),
            OrderMarkName: annotation.data.label
          } : {}),
          PicturePath: picturePath,
          QuestionType: 0,
          RowId: this.operateRowId,
          TableQuestionId: this.operateQuestionId,
          RowIndex: obj.rowIndex,
          MarkId: annotation ? annotation.annotationUID : null
        }, -10)
        this.$set(this.questionsMarkStatus,
          `${this.operateRowId}_${this.operateQuestionId}`,
          { isMarked: !!annotation, isSaved: true, OrderMarkName: annotation ? annotation.data.label : '' }
        )
        this.resetOperateState()
        if (annotation) {
          for (let i = 0; i < this.questionMarkInfoList.length; i++) {
            const item = this.questionMarkInfoList[i]
            if (!item.MeasureData || item.MeasureData.annotationUID !== annotation.annotationUID) continue
            const isTableMode = item.TableQuestionId
            if (isTableMode && ((this.questionsMarkStatus[`${item.RowId}_${item.TableQuestionId}`] && !this.questionsMarkStatus[`${item.RowId}_${item.TableQuestionId}`].isSaved && this.questionsMarkStatus[`${item.RowId}_${item.TableQuestionId}`].isMarked) || (this.questionsMarkStatus[`${item.TableQuestionId}`] && !this.questionsMarkStatus[`${item.TableQuestionId}`].isSaved && this.questionsMarkStatus[`${item.TableQuestionId}`].isMarked))) {
              DicomEvent.$emit('operateImageMarkerTable', { QuestionId: item.TableQuestionId, operateStateEnum: 7, picturePath })
              break
            }
          }
        }
      } catch (e) {
        console.error('表格保存失败:', e)
      } finally {
        loading.close()
      }
    },
    findMarkIndex(question) {
      const { Id, RowId } = question
      if (this.isTableQuestion) {
        return RowId
          ? this.questionMarkInfoList.findIndex(i =>
            i.TableQuestionId === Id && i.RowId === RowId)
          : this.questionMarkInfoList.findIndex(i =>
            i.TableQuestionId === Id && !i.RowId)
      }
      return this.questionMarkInfoList.findIndex(i => i.QuestionId === Id)
    },
    updateQuestionsMarkStatus(obj) {
      this.questionMarkInfoList.forEach(item => {
        if (item.QuestionId === obj.question.ParentQsId && !item.RowId) {
          item.RowId = obj.rowId
          const oldKey = item.TableQuestionId
          const newKey = `${obj.rowId}_${item.TableQuestionId}`

          if (this.questionsMarkStatus[oldKey]) {
            const status = { ...this.questionsMarkStatus[oldKey] }
            delete this.questionsMarkStatus[oldKey]
            this.$set(this.questionsMarkStatus, newKey, status)
          }
        }
      })
    },
    getAnnotationByRow(rowId, isTable = true) {
      console.log(this.questionMarkInfoList, 'this.questionMarkInfoList')
      let index = -1;
      if (isTable) {
        index = this.questionMarkInfoList.findIndex(
          i => i.RowId === rowId && i.TableQuestionId === this.operateQuestionId
        )
      } else {
        index = this.questionMarkInfoList.findIndex(
          i => i.QuestionId === rowId
        )
      }
      return index > -1 ? this.questionMarkInfoList[index].MeasureData : null
    },
    async bindAnnotationToQuestion(annotation) {
      try {
        const VALID_STATES = [null, 0, 1, 3]
        const currentState = this.operateStateEnum
        if (!VALID_STATES.includes(currentState)) return
        const isInvalidAnnotation = currentState === 1 && annotation.markTool !== this.imageTool
        if (isInvalidAnnotation) return
        if (currentState === null) {
          return this.handleNullState(annotation)
        }
        if (!this.operateQuestionId) return
        if ([0, 1, 3].includes(currentState)) {
          // 该标记不能与问题绑定！
          if (!annotation.data.label || annotation.markTool !== this.imageTool) {
            let message = this.$t("dicom3D:CustomizeQuestionList:alert:markNoSaveToQuestion").replace("xxx", this.$t(`dicom3D:mark:${this.imageTool}`))
            this.$alert(message)
            return
          }
          // if (currentState === 3) {
          let conflictIndex = this.questionMarkInfoList.findIndex(
            item => item.MeasureData.annotationUID === annotation.annotationUID
              && item.RowId !== this.operateRowId && item.RowId
          )
          // && this.operateRowId
          console.log(conflictIndex)
          if (conflictIndex > -1) {
            //该标记已绑定到其他行，不能更改绑定！
            this.$alert(this.$t("dicom3D:CustomizeQuestionList:alert:markIsbind"))
            return
          }
          conflictIndex = this.questionMarkInfoList.findIndex(
            item => item.MeasureData.annotationUID === annotation.annotationUID
              && !item.TableQuestionId && this.isTableQuestion
          )
          if (conflictIndex > -1) {
            //该标记已绑定到外层问题，不能更改绑定！
            this.$alert(this.$t("dicom3D:CustomizeQuestionList:alert:markIsbind2"))
            return
          }
          // }
          // 是否确认绑定？ 是否确认更改？
          const message = currentState === 0 ? this.$t("dicom3D:CustomizeQuestionList:confirm:bindYesOrNo") : currentState === 3 ? this.$t("dicom3D:CustomizeQuestionList:confirm:updateYesOrNo") : null
          if (message) {
            const result = await this.$confirm(message, {
              type: 'warning',
              distinguishCancelAndClose: true
            })
            const isConfirmed = result === 'confirm'
            if (!isConfirmed) return
          }
        }
        const targetIndex = this.findTargetIndex()
        if (targetIndex === -1) {
          this.questionMarkInfoList.push({
            InstanceId: annotation.instanceId,
            SeriesId: annotation.seriesId,
            OrderMarkName: annotation.data.label,
            StudyId: annotation.studyId,
            MarkTool: annotation.metadata.toolName,
            PicturePath: '',
            NumberOfFrames: annotation.numberOfFrames,
            MeasureData: annotation,
            RowId: this.operateRowId || '',
            QuestionId: this.isTableQuestion
              ? this.operateParentQsId
              : this.operateQuestionId,
            TableQuestionId: this.isTableQuestion
              ? this.operateQuestionId
              : ''
          })
        } else {
          const target = this.questionMarkInfoList[targetIndex]
          Object.assign(target, {
            InstanceId: annotation.instanceId,
            SeriesId: annotation.seriesId,
            StudyId: annotation.studyId,
            OrderMarkName: annotation.data.label,
            MarkTool: annotation.metadata.toolName,
            PicturePath: '',
            NumberOfFrames: annotation.numberOfFrames,
            MeasureData: annotation
          })
        }
        this.updateMarkStatus(targetIndex, annotation)
        this.operateStateEnum = null
      } catch (e) {
        console.error('绑定失败:', e); // 增强错误信息
      }
    },
    handleNullState(annotation) {
      const qsArr = []
      const markList = this.questionMarkInfoList
      for (let i = 0; i < markList.length; i++) {
        const item = markList[i];
        if (item.MeasureData?.annotationUID !== annotation.annotationUID) continue
        item.MeasureData = annotation

        if (item.TableQuestionId) {
          qsArr.push({ ...item, ImageToolAttribute: this.imageToolAttribute })

          const keyId = item.RowId
            ? `${item.RowId}_${item.TableQuestionId}`
            : item.TableQuestionId

          this.$set(this.questionsMarkStatus, keyId, {
            isMarked: true,
            isSaved: false,
          })
        } else {
          this.setAnswerToQuestion(annotation, item.QuestionId)
          this.$set(this.questionsMarkStatus, item.QuestionId, {
            isMarked: true,
            isSaved: false,
          })
        }
      }
      if (qsArr.length) {
        store.dispatch('dicom3d/setOperateInfo', qsArr)
      }
    },
    findTargetIndex() {
      if (this.isTableQuestion && this.operateRowId) {
        return this.questionMarkInfoList.findIndex(
          item => item.TableQuestionId === this.operateQuestionId
            && item.RowId === this.operateRowId
        )
      } else if (this.isTableQuestion) {
        return this.questionMarkInfoList.findIndex(
          item => item.TableQuestionId === this.operateQuestionId
            && !item.RowId
        )
      }
      return this.questionMarkInfoList.findIndex(
        item => item.QuestionId === this.operateQuestionId
      )
    },

    updateMarkStatus(index, annotation) {
      const status = { isMarked: true, isSaved: false }
      if (this.isTableQuestion) {
        const keyId = index > -1 && this.questionMarkInfoList[index].RowId
          ? `${this.questionMarkInfoList[index].RowId}_${this.questionMarkInfoList[index].TableQuestionId}`
          : this.operateRowId
            ? `${this.operateRowId}_${this.operateQuestionId}`
            : this.operateQuestionId

        this.$set(this.questionsMarkStatus, keyId, status)
        store.dispatch('dicom3d/setOperateInfo', [{
          MeasureData: annotation,
          QuestionId: this.operateParentQsId,
          TableQuestionId: this.operateQuestionId,
          RowId: this.operateRowId,
          ImageToolAttribute: this.imageToolAttribute
        }])
      } else {
        this.setAnswerToQuestion(annotation, this.operateQuestionId)
        this.$set(this.questionsMarkStatus, this.operateQuestionId, status)
      }
    },

    updateAnnotationToQuestion(annotation) {
      const questionMarkInfo = { isMarked: true, isSaved: false }
      const qsArr = []
      for (let i = 0; i < this.questionMarkInfoList.length; i++) {
        const item = this.questionMarkInfoList[i]
        if (!item.MeasureData || item.MeasureData.annotationUID !== annotation.annotationUID) continue
        item.MeasureData = annotation
        const isTableMode = this.isTableQuestion || item.TableQuestionId
        if (!isTableMode) {
          this.imageToolAttribute = null
          this.setAnswerToQuestion(annotation, item.QuestionId)
          this.$set(this.questionsMarkStatus, item.QuestionId, questionMarkInfo)
          continue
        }
        this.operateParentQsId = item.QuestionId
        this.operateQuestionId = item.TableQuestionId
        this.operateRowId ||= item.RowId
        qsArr.push({ ...item })
        const keyId = item.RowId ? `${item.RowId}_${item.TableQuestionId}` : item.TableQuestionId;
        this.$set(this.questionsMarkStatus, keyId, questionMarkInfo);
        if (item.RowId) {
          DicomEvent.$emit('openAddTableCol', { RowId: item.RowId })
        }
      }
      if (qsArr.length > 0) {
        store.dispatch('dicom3d/setOperateInfo', qsArr);
      }
    },
    setAnswerToQuestion(annotation, questionId) {
      if (!questionId || !annotation) return
      let prop = ''
      if (!this.imageToolAttribute) {
        prop = this.questionImageToolAttributeInfo[questionId]
      } else {
        prop = this.imageToolAttribute
      }
      let val = this.getAnnotationProp(annotation, prop)
      this.$set(this.questionForm, questionId, val)
    },
    getAnnotationProp(annotation, prop) {
      if (!annotation || !prop) return
      const referencedImageId = annotation?.metadata?.referencedImageId
      if (!referencedImageId) return null
      const cacheKey = `imageId:${referencedImageId}`
      const cachedStats = annotation.data?.cachedStats?.[cacheKey]
      const hasProp = cachedStats
        && Object.prototype.hasOwnProperty.call(cachedStats, prop)
      if (!hasProp) return null
      const value = cachedStats[prop]
      return value !== null
        ? parseFloat(value).toFixed(this.digitPlaces)
        : value
    },
    unBindAnnotationToQuestion(obj) {
      const { markTableQuestions = [], questionId } = obj || {}
      const { questionMarkInfoList, questionsMarkStatus } = this
      if (!Array.isArray(markTableQuestions) || !questionId || !Array.isArray(questionMarkInfoList)) {
        return
      }
      this.questionMarkInfoList = questionMarkInfoList.filter(item => {
        const { TableQuestionId, QuestionId, RowId } = item || {}
        if ((TableQuestionId && QuestionId === questionId && markTableQuestions.includes(TableQuestionId)) && !RowId) {
          if (questionsMarkStatus && questionsMarkStatus[TableQuestionId]) {
            delete questionsMarkStatus[TableQuestionId]
          } else {
            return item
          }
        } else {
          return item
        }
      })
    },
    // 获取截图
    getScreenshots(obj) {
      return new Promise((resolve, reject) => {
        this.$emit('getCustomScreenshots', obj, resolve) // 将resolve传递给父组件
      })
    },
    async uploadScreenshots(fileName, file) {
      try {
        file = this.convertBase64ToBlob(file)
        const trialId = this.$route.query.trialId
        const taskInfo = JSON.parse(localStorage.getItem('taskInfo'))
        const subjectId = taskInfo.SubjectId
        const result = await this.OSSclient.put(`/${trialId}/Read/${subjectId}/${this.visitTaskId}/${fileName}.png`, file)
        return { isSuccess: true, result: result }
      } catch (e) {
        console.log(e)
        return { isSuccess: false, result: e }
      }
    },
    convertBase64ToBlob(imageEditorBase64) {
      const base64Arr = imageEditorBase64.split(',')
      let imgtype = ''
      let base64String = ''
      if (base64Arr.length > 1) {
        base64String = base64Arr[1]
        imgtype = base64Arr[0].substring(
          base64Arr[0].indexOf(':') + 1,
          base64Arr[0].indexOf(';')
        )
      }
      const bytes = atob(base64String)
      const bytesCode = new ArrayBuffer(bytes.length)
      const byteArray = new Uint8Array(bytesCode)
      for (let i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i)
      }
      return new Blob([bytesCode], { type: imgtype })
    },
    resetOperateState() {
      console.log('resetOperateState')
      this.operateStateEnum = null
      this.operateQuestionId = ''
      this.operateRowId = ''
      this.imageTool = ''
      this.imageToolAttribute = ''
    },
    async resetForm() {
      const confirm = await this.$confirm(
        this.$t('trials:dicomReading:message:confirmReset1'),
        this.$t('trials:dicomReading:message:confirmReset2'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      this.$emit('setReadingToolPassive')
      const loading = this.$loading({ fullscreen: true })
      try {
        const res = await resetReadingTask({ visitTaskId: this.visitTaskId })
        if (res.IsSuccess) {
          this.rerender = false
          await this.getQuestionCalculateRelation()
          await this.getQuestions(true)
          this.$emit('resetAnnotations', this.visitTaskId)
          this.$nextTick(() => {
            this.rerender = true
          })
        }
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    receiveMsg(event) {
      if (event.data.type === 'isCanActiveNoneDicomTool') {
        let obj = { isCanActiveTool: true, lesionName: '', reason: '', toolName: event.data.toolName }
        // this.getUnSaveTarget()
        // var obj = {}
        // if (this.unSaveTargets.length > 0) {
        //   var rowIndex = String(this.unSaveTargets[0].rowIndex)
        //   var questionId = this.unSaveTargets[0].questionId
        //   const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        //   if (rowIndex === this.activeItem.activeRowIndex && questionId === this.activeItem.activeCollapseId && !this.$refs[refName][0].questionForm.MeasureData) {
        //     // 判断是否是靶病灶
        //     //  questions.findIndex(i => i.QuestionMark === questionMark)
        //     var lesionType = this.$refs[refName][0].questionForm.LesionType
        //     if (lesionType === 0) {
        //       // '当前病灶为靶病灶，不允许添加标记！'
        //       obj = { isCanActiveTool: false, lesionName: '', reason: this.$t('trials:reading:warnning:msg18') }
        //     } else {
        //       obj = { isCanActiveTool: true, lesionName: this.$refs[refName][0].lesionMark, reason: '', toolName: event.data.toolName }
        //     }
        //   } else {
        //     let msg = this.$t('trials:reading:warnning:msg5')
        //     msg = msg.replace('xxx', this.unSaveTargets[0].lessionName)
        //     obj = { isCanActiveTool: false, lesionName: '', reason: msg }
        //   }
        // } else {
        //   if (this.activeItem.activeCollapseId) {
        //     // 判断是否是靶病灶
        //     const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        //     // obj = { isCanActiveTool: true, lesionName: this.$refs[refName][0].lesionMark, reason: '' }
        //     const lesionType = this.$refs[refName][0].questionForm.LesionType
        //     if (lesionType === 0) {
        //       // 当前病灶为靶病灶，不允许添加标记！
        //       obj = { isCanActiveTool: false, lesionName: '', reason: this.$t('trials:reading:warnning:msg18') }
        //     } else {
        //       obj = { isCanActiveTool: true, lesionName: this.$refs[refName][0].lesionMark, reason: '', toolName: event.data.toolName }
        //     }
        //   } else {
        //     // 获取非靶病灶/新病灶的长度及标识
        //     var qsObj = null
        //     var lesionName = ''
        //     if (this.isBaseLineTask) {
        //       const idx = this.tableQuestions.findIndex(item => item.LesionType === 1)
        //       if (idx > -1) {
        //         qsObj = this.tableQuestions[idx]
        //       }
        //     } else {
        //       const idx = this.tableQuestions.findIndex(item => item.LesionType === 2)
        //       if (idx > -1) {
        //         qsObj = this.tableQuestions[idx]
        //       }
        //     }

        //     // var questions = qsObj.TableQuestions.Questions.find(item => item.QuestionMark === 3)
        //     // if (questions) {
        //     //   var maxIndex = this.getMaxRowIndex(qsObj.TableQuestions.Answers)
        //     //   lesionName = `${qsObj.OrderMark}${String(maxIndex + 1).padStart(2, '0')}`
        //     // }
        //     var maxIndex = this.getMaxRowIndex(qsObj.TableQuestions.Answers)
        //     lesionName = `${qsObj.OrderMark}${String(maxIndex + 1).padStart(2, '0')}`
        //     obj = { isCanActiveTool: true, lesionName: lesionName, reason: '', toolName: event.data.toolName }
        //   }
        // }

        DicomEvent.$emit('isCanActiveNoneDicomTool', obj)
      } else if (event.data.type === 'setMeasurement') {
        // this.setMeasuredData(event.data.data)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.questionList-wrapper {
  height: 100%;
  overflow-y: auto;

  .container {
    padding: 10px;

    .basic-info {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        color: #ddd;
        padding: 5px 0px;
        margin: 0;
      }

      i {
        color: #fff;
        font-size: 22px;
        font-weight: bold;
        cursor: pointer;
      }
    }

    .ecrf-form {
      ::v-deep .el-form-item__label {
        color: #ddd;
      }
    }

    ::v-deep .el-table,
    .el-table__expanded-cell {
      background-color: #000;
      color: #fff;
      border-color: #444444;
    }

    ::v-deep .el-table th,
    .el-table tr {
      background-color: #000;
      color: #fff;
      border-color: #444444;
    }

    ::v-deep .el-table__body tr>td {
      background-color: #000 !important;
      color: #fff;
      border-color: #444444;
    }

    ::v-deep .el-table__body tr:hover>td {
      background-color: #858282 !important;
      color: #fff;
      border-color: #444444;
    }

    ::v-deep .el-table--border th.gutter:last-of-type {
      border: none;
    }

    ::v-deep .el-dialog {
      background: #1e1e1e;
      border: 1px solid #ddd;
      color: #ddd;

      .el-dialog__title {
        color: #fff;
      }

      .el-input .el-input__inner {
        background-color: transparent;
        color: #ddd;
        border: 1px solid #5e5e5e;
      }

      .el-input.is-disabled .el-input__inner {
        background-color: #646464a1;
      }

      .el-form-item__label {
        color: #dfdfdf
      }
    }
  }
}

// .ecrf-list-container{
//   min-height:400px;
//   color: #ddd;

// }</style>
