<template>
  <div class="measurement-wrapper" :style="{ 'height': height + 10 + 'px' }" style="position: relative">

    <div class="container" :style="{ 'height': height + 'px' }" style="padding-bottom: 50px;overflow-y: auto;">
      <div class="basic-info">
        <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="resetMeasuredData" />
          </el-tooltip>
        </div>
        <h3 v-if="isReadingShowSubjectInfo">
          <span v-if="subjectCode">{{ subjectCode }} </span>
          <span style="margin-left:5px;">{{ taskBlindName }}</span>
        </h3>
      </div>
      <QuestionsPreview ref="QuestionsPreview" v-if="ecrfShow && TrialReadingCriterionId" :visitTaskId="visitTaskId"
        :criterionId="TrialReadingCriterionId" @handleReadingChart="handleReadingChart">
      </QuestionsPreview>
    </div>
    <div class="questions-footer">
      <i v-if="readingTaskState < 2" class="el-icon-warning feedback-icon" @click="openFeedBackTable"
        :style="{ color: isExistUnprocessedFeedback ? '#ffeb3b' : '#fff' }" />
      <el-button v-if="readingTaskState < 2" style="margin-right: 10px" type="primary" size="small"
        @click="handleSave(true)">
        {{ $t('common:button:save') }}
      </el-button>
      <el-button v-if="readingTaskState < 2 && IseCRFShowInDicomReading" type="primary" style="margin-right: 10px"
        size="small" @click="skipTask">
        <!-- 跳过 -->
        {{ $t('trials:readingReport:button:skip') }}
      </el-button>
      <el-button style="margin-right: 10px" type="primary" size="small"
        v-if="readingTaskState < 2 && IseCRFShowInDicomReading" @click="handleConfirm">
        {{ $t('common:button:submit') }}</el-button>
    </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>
    <el-dialog v-if="measuredDataVisible" :visible.sync="measuredDataVisible" :close-on-click-modal="false"
      width="600px" custom-class="base-dialog-wrapper">
      <el-form ref="measuredDataForm" :model="form" :rules="rules" v-loading="loading" label-width="120px" size="small">
        <el-form-item :label="$t('trials:reading:title:measuredDataName')" prop="measuredDataName">
          <el-input v-model="form.measuredDataName"></el-input>
        </el-form-item>
        <el-form-item style="text-align:right;">
          <!-- Cancel -->
          <el-button type="primary" @click="handleMeasuredDataCancel">
            {{ $t('common:button:cancel') }}
          </el-button>
          <!-- Save -->
          <el-button type="primary" @click="handleMeasuredDataSave">
            {{ $t('common:button:save') }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { submitDicomVisitTask, verifyVisitTaskQuestions } from '@/api/trials'
import { getCustomTag, submitCustomTag, resetReadingTask } from '@/api/reading'
import { setSkipReadingCache } from '@/api/reading'
import DicomEvent from './../components/DicomEvent'
import SignForm from '@/views/trials/components/newSignForm'
import QuestionsPreview from './CustomizeQuestionsPreview'
import const_ from '@/const/sign-code'
import store from '@/store'
import { mapGetters } from 'vuex'
export default {
  name: 'CustomizeMeasurementList',
  components: {
    QuestionsPreview, SignForm
  },
  props: {
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    },
    IseCRFShowInDicomReading: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        measuredDataName: null,
      },
      rules: {
        measuredDataName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur'] }]
      },
      measuredDataVisible: false,
      currentUser: zzSessionStorage.getItem('userName'),
      height: window.innerHeight - 140,
      visitTaskId: '',
      loading: false,
      CriterionType: null,
      subjectCode: '',
      taskBlindName: '',
      TrialReadingCriterionId: null,
      ecrfShow: false,
      signCode: null,
      signVisible: false,
      readingTaskState: null,
      isExistUnprocessedFeedback: false
    }
  },
  computed: {
    ...mapGetters(['visitTaskList', 'lastCanvasTaskId', 'currentReadingTaskState'])
  },
  watch: {
    lastCanvasTaskId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initList()
        }
      }
    },
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.readingTaskState = val
        }
      }
    }
  },
  mounted() {
    // this.subjectCode = this.$router.currentRoute.query.subjectCode
    this.subjectCode = localStorage.getItem('subjectCode')
    this.CriterionType = parseInt(localStorage.getItem('CriterionType'))
    this.TrialReadingCriterionId = this.$router.currentRoute.query.TrialReadingCriterionId
    this.isExistUnprocessedFeedback = localStorage.getItem('IsExistUnprocessedFeedback')
    DicomEvent.$on('getCustomTableQuestionAnswer', (visitTaskId) => {
      this.$refs['QuestionsPreview'].getCustomTableQuestionAnswer(visitTaskId)
    })
    DicomEvent.$on('setReadingState', readingTaskState => {
      console.log(readingTaskState)
      this.readingTaskState = readingTaskState
    })

    window.addEventListener('resize', this.setHeight)
  },
  beforeDestroy() {
    DicomEvent.$off('loadMeasurementList')
    DicomEvent.$off('setCollapseActive')
    DicomEvent.$off('changeLesionType')
    DicomEvent.$off('getUnSaveTarget')
    DicomEvent.$off('setReadingState')
    DicomEvent.$off('getCustomTableQuestionAnswer')
  },
  methods: {
    handleReadingChart(e) {
      this.$emit('handleReadingChart', e)
    },
    async initList() {
      if (this.visitTaskId !== this.lastCanvasTaskId) {
        this.ecrfShow = true
        var i = this.visitTaskList.findIndex(i => i.VisitTaskId === this.lastCanvasTaskId)
        console.log(i)
        if (i > -1) {
          this.visitTaskId = this.visitTaskList[i].VisitTaskId
          this.taskBlindName = this.visitTaskList[i].TaskBlindName
          this.readingTaskState = this.visitTaskList[i].ReadingTaskState
          console.log(this.visitTaskList[i].IsInit)
          if (!this.visitTaskList[i].IsInit) {
            var loading = this.$loading({ fullscreen: true })
            var triald = this.trialId = this.$router.currentRoute.query.trialId
            if (!this.visitTaskList[i].measureDataInit) {
              await store.dispatch('reading/getCustomizeMeasuredData', this.visitTaskList[i].VisitTaskId)
            }
            if (!this.visitTaskList[i].studyListInit) {
              await store.dispatch('reading/getStudyInfo', { trialId: triald, subjectVisitId: this.visitTaskList[i].VisitId, visitTaskId: this.visitTaskList[i].VisitTaskId, taskBlindName: this.visitTaskList[i].TaskBlindName })
            }
            if (!this.visitTaskList[i].readingQuestionsInit) {
              await store.dispatch('reading/getReadingQuestionAndAnswer', { trialId: triald, visitTaskId: this.visitTaskList[i].VisitTaskId })
            }
            if (!this.visitTaskList[i].questionsInit) {
              await store.dispatch('reading/getDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskList[i].VisitTaskId })
            }

            await store.dispatch('reading/setStatus', { visitTaskId: this.visitTaskList[i].VisitTaskId })
            loading.close()
          }
          this.$nextTick(() => {
            if (this.$refs['QuestionsPreview']) {
              this.$refs['QuestionsPreview'].getCustomTableQuestionAnswer(this.visitTaskId)
            }
          })
        }
      }
    },
    getCustomTag() {
      getCustomTag({ visitTaskId: this.visitTaskId }).then(res => {
        console.log(res)
      })
    },
    setMeasuredData(measureData) {
      console.log(measureData)
      measureData.visitTaskId = this.visitTaskId
      this.measuredDataVisible = true
      this.measureData = measureData
    },
    modifyMeasuredData(measureData) {
      measureData.visitTaskId = this.visitTaskId
      measureData.measureData.pictureBaseStr = ''
      if (this.readingTaskState >= 2) {
        this.measuredDataVisible = false
        store.dispatch('reading/addCustomizeMeasuredData', { visitTaskId: this.visitTaskId, measureData: measureData.measureData })
      } else {
        let params = JSON.parse(JSON.stringify(measureData))
        params.measureData = JSON.stringify(measureData.measureData)
        params.Id = params.questionInfo.Id
        params.StudyId = params.questionInfo.StudyId
        params.SeriesId = params.questionInfo.SeriesId
        params.InstanceId = params.questionInfo.InstanceId
        params.NumberOfFrames = measureData.frame
        submitCustomTag(params).then(() => {
          this.measuredDataVisible = false
          DicomEvent.$emit('updateImage')
          // this.$message.success(this.$t('common:message:savedSuccessfully'))
        })
      }

    },
    async moveMeasureData(measureData) {
      console.log('measureData', measureData)
      await store.dispatch('reading/removeCustomizeMeasuredData', { visitTaskId: this.visitTaskId, ...measureData })
      DicomEvent.$emit('updateImage')
    },
    handleMeasuredDataCancel() {
      this.measuredDataVisible = false
      // DicomEvent.$emit('updateImage')
    },
    handleMeasuredDataSave() {
      this.$refs.measuredDataForm.validate(valid => {
        if (!valid) return
        // 是否同名验证
        let isValid = this.validateRemarkName(this.form.measuredDataName)
        if (!isValid) {
          // '存在同名标记，不允许保存！'
          this.$message.error(this.$t('trials:customReading:error:validMarkName'))
          return
        }
        this.measureData.data.remark = this.form.measuredDataName
        this.measureData.pictureBaseStr = ''
        if (this.readingTaskState >= 2) {
          this.measuredDataVisible = false
          this.form.measuredDataName = ''
          store.dispatch('reading/addCustomizeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.measureData })
          DicomEvent.$emit('updateImage')
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        } else {
          let params = JSON.parse(JSON.stringify(this.measureData))
          params.measureData = JSON.stringify(this.measureData)
          params.NumberOfFrames = this.measureData.frame
          submitCustomTag(params).then(async (res) => {
            this.measuredDataVisible = false
            this.form.measuredDataName = ''
            await store.dispatch('reading/addCustomizeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.measureData, id: res.Result })
            await store.dispatch('reading/getCustomizeMeasuredData', this.visitTaskId)
            DicomEvent.$emit('updateImage')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          })
        }
      })
    },
    validateRemarkName(remark) {
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
      var measureData = this.visitTaskList[idx].MeasureData
      let i = measureData.findIndex(i => i.MeasureData.data.remark === remark)
      return i === -1
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名并确认
    signConfirm(signInfo) {
      this.loading = true
      var params = {
        data: {
          visitTaskId: this.visitTaskId
        },
        signInfo: signInfo
      }
      this.signVisible = false
      submitDicomVisitTask(params).then(res => {
        if (res.IsSuccess) {
          try {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            if (this.$refs['signForm']) {
              this.$refs['signForm'].btnLoading = false
            }
            this.signVisible = false
            // 设置当前任务阅片状态为已读
            this.readingTaskState = 2
            store.dispatch('reading/setVisitTaskReadingTaskState', { visitTaskId: this.visitTaskId, readingTaskState: 2 })
            DicomEvent.$emit('setReadingState', 2)
            window.opener.postMessage('refreshTaskList', window.location)
            this.$confirm(this.$t('trials:oncologyReview:title:msg2'), {
              type: 'warning',
              distinguishCancelAndClose: true
            })
              .then(() => {
                window.location.reload()
              })
              .catch(action => {
              })
          } catch (e) {
            console.log(e)
          }
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        if (this.$refs['signForm'] && this.$refs['signForm'].btnLoading) {
          this.$refs['signForm'].btnLoading = false
        }
      })
    },
    async handleConfirm() {
      var res = await this.$refs['QuestionsPreview'].handleSave(false)
      if (res) {
        await verifyVisitTaskQuestions({ visitTaskId: this.visitTaskId })
        const { ImageAssessmentReportConfirmation } = const_.processSignature
        this.signCode = ImageAssessmentReportConfirmation
        this.signVisible = true
      }
    },
    handleSave(isMsg) {
      this.$refs['QuestionsPreview'].handleSave(isMsg)
    },
    setHeight() {
      this.height = window.innerHeight - 140
    },
    initPage(obj) {
      if (this.visitTaskId !== obj.visitTaskId) {
        this.visitTaskId = obj.visitTaskId
        this.taskBlindName = obj.taskBlindName
        this.ecrfShow = true
      }
    },
    async resetMeasuredData() {
      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
      const loading = this.$loading({ fullscreen: true })
      try {
        const res = await resetReadingTask({ visitTaskId: this.visitTaskId })
        this.loading = false
        if (res.IsSuccess) {
          // 刷新标注、表单、报告页信息
          this.$refs['QuestionsPreview'].getCustomTableQuestionAnswer(this.visitTaskId)
          await store.dispatch('reading/refreshCustomizeMeasuredData', this.visitTaskId)
          DicomEvent.$emit('getMeasureData')
          DicomEvent.$emit('getReportInfo', true)
          DicomEvent.$emit('refreshStudyListMeasureData')
        }
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    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)
      }
    },
    openFeedBackTable() {
      this.$FB({
        type: 'imgfail',
        trialId: this.$route.query.trialId,
        visitTaskId: this.visitTaskId,
        callBack: async () => {
          console.log('callBack')
          const confirm = await this.$confirm(
            this.$t('trials:reading:confirm:feedbackmsg'),
            {
              type: 'warning',
              distinguishCancelAndClose: true
            }
          )
          if (confirm !== 'confirm') return
          this.loading = true
          try {
            const res = await setSkipReadingCache({ visitTaskId: this.visitTaskId })
            this.loading = false
            if (res.IsSuccess) {
              window.location.reload()
            }
          } catch (e) {
            this.loading = false
            console.log(e)
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.measurement-wrapper {
  overflow-y: auto;
  // overflow: hidden;

  .container {
    padding: 10px;

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

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

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

  .title {
    padding: 5px;
    font-weight: bold;
    color: #ddd;
    font-size: 15px;

  }

  .add-icon {
    padding: 5px;
    font-weight: bold;
    color: #ddd;
    font-size: 15px;
    border: 1px solid #938b8b;
    margin-bottom: 2px;
    cursor: pointer;
  }

  .add-icon:hover {
    background-color: #607d8b;
  }

  .flex-row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background-color: #424242;

  }

  .lesion_list {
    position: relative;
  }

  .el-collapse {
    border-bottom: none;

    ::v-deep .el-collapse-item {
      background-color: #000 !important;
      color: #ddd;

    }

    ::v-deep .el-collapse-item__header {
      background-color: #000 !important;
      color: #ddd;
      border-bottom-color: #5a5a5a;
      padding-left: 5px;
      height: 35px;
      line-height: 35px;
    }

    ::v-deep .el-collapse-item__wrap {
      background-color: #000 !important;
      color: #ddd;
    }

    ::v-deep .el-collapse-item__content {
      width: 260px;
      position: absolute;
      top: 0px;
      right: 0px;
      // border: 1px solid #ffeb3b;
      border: 1px solid #fff;
      z-index: 1;
      color: #ddd;
      padding: 5px;
      background-color: #1e1e1e;
    }

  }

  .questions-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 10;
    background: #000;
    width: 100%;
    display: flex;
    justify-content: right;
    align-items: center;
    height: 50px;

    .feedback-icon {
      padding: 0 10px;
      color: #fff;
      font-weight: 400;
      font-size: 24px;
      cursor: pointer;

      &:hover {
        color: #68a2d5;
      }
    }
  }
}
</style>
