<template>
  <div>
    <!-- <div
      v-if="!!question.GroupName && (questionForm[question.ParentId] === question.ParentTriggerValue) || question.ParentId===''||question.ParentId===null"
      style="font-weight: bold;font-size: 16px;margin: 5px 0px;"
    >
      {{ question.GroupName }}
    </div> -->
    <div v-if="!!question.GroupName && question.Type === 'group'">
      <h4 style="color: #ddd;padding: 5px 0px;margin: 0;">
        {{ language === 'en' ? question.GroupEnName : question.GroupName }}
      </h4>
    </div>
    <template v-else-if="((question.QuestionType === 56 || question.QuestionType === 57) && question.IsBaseLineTask)" />
    <template v-else>

      <el-form-item
        v-if="(question.ShowQuestion === 1 && question.ParentTriggerValueList.includes(String(questionForm[question.ParentId]))) || question.ShowQuestion === 0"
        :label="`${question.QuestionName}`" :prop="question.Id" :rules="[
          {
            required: (question.IsRequired === 0 || (question.IsRequired === 1 && question.RelevanceId && (questionForm[question.RelevanceId] === question.RelevanceValue))) && question.Type !== 'group' && question.Type !== 'summary',
            message: ['radio', 'select', 'checkbox'].includes(question.Type) ? $t('common:ruleMessage:select') : $t('common:ruleMessage:specify'), trigger: ['blur', 'change']
          },
        ]"
        :class="[question.Type === 'group' ? 'mb' : (question.Type === 'upload' || question.QuestionName.length > 15) ? 'uploadWrapper' : '']">
        <template v-if="question.QuestionType === 60 || question.QuestionType === 61">
          <div style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center;">
            <div style="display: flex;justify-content: space-between;" v-if="question.Type === 'calculation'">
              <el-input v-if="question.Type === 'calculation'" v-model="questionForm[question.Id]" disabled
                style="width: 130px;">
                <template v-if="question.Unit" slot="append">
                  {{ $fd('ValueUnit', parseInt(question.Unit)) }}
                </template>
              </el-input>
              <svg-icon v-if="question.ShowChartTypeEnum > 0" icon-class="readingChart"
                class="svg-icon svg-readingChart" @click.stop="(e) => handleReadingChart({
                  e,
                  data: {
                    QuestionId: question.Id,
                    QuestionName: question.QuestionName
                  }
                })" />
            </div>
            <!-- 测量 -->
            <el-button v-if="!questionForm[question.Id] && readingTaskState !== 2" size="mini" type="text"
              @click="addAnnotation(question)">{{ $t('trials:lugano:button:addAnnotation') }}</el-button>
            <!-- 清除标记 -->
            <el-button v-if="questionForm[question.Id] && readingTaskState !== 2" size="mini" type="text"
              @click="removeAnnotation(question)">{{ $t('trials:lugano:button:clearAnnotation') }}</el-button>
            <!-- 定位 -->
            <el-button v-if="questionForm[question.Id]" size="mini" type="text" @click="locateAnnotation(question)">{{
              $t('trials:lugano:button:locateAnnotation') }}</el-button>
            <!-- 保存 -->
            <el-button v-if="readingTaskState !== 2 && question.SaveEnum === 1" size="mini" type="text"
              @click="saveAnnotation(question)">
              <!-- 未保存 -->
              <el-tooltip class="item" effect="dark" :content="$t('trials:reading:button:unsaved')" placement="bottom">
                <i class="el-icon-warning" style="color:red" />
              </el-tooltip>
              {{ $t('common:button:save') }}
            </el-button>
          </div>
        </template>

        <template
          v-else-if="question.QuestionType === 48 || question.QuestionType === 51 || question.QuestionType === 52 || question.QuestionType === 53">
          <div style="display: flex;justify-content: space-between;" v-if="question.Type === 'calculation'">
            <el-input v-if="question.Type === 'calculation'" v-model="questionForm[question.Id]" disabled>
              <template v-if="question.Unit" slot="append">
                {{ $fd('ValueUnit', parseInt(question.Unit)) }}
              </template>
            </el-input>
            <svg-icon v-if="question.ShowChartTypeEnum > 0" icon-class="readingChart" class="svg-icon svg-readingChart"
              @click.stop="(e) => handleReadingChart({
                e,
                data: {
                  QuestionId: question.Id,
                  QuestionName: question.QuestionName
                }
              })" />
          </div>
        </template>

        <!-- 输入框 -->
        <el-input v-else-if="question.Type === 'input'" v-model="questionForm[question.Id]"
          :disabled="readingTaskState >= 2 || isFirstChangeTask"
          @change="((val) => { formItemChange(val, question) })" />
        <!-- 多行文本输入框 -->
        <el-input v-else-if="question.Type === 'textarea'" v-model="questionForm[question.Id]" type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }" maxlength="500" :disabled="readingTaskState >= 2 || isFirstChangeTask"
          @change="((val) => { formItemChange(val, question) })" />
        <!-- 下拉框 -->
        <el-select v-else-if="question.Type === 'select'" v-model="questionForm[question.Id]"
          :disabled="readingTaskState >= 2 || ((question.TableQuestionType === 2 || question.QuestionGenre === 2) && !!question.DictionaryCode) || isFirstChangeTask || question.QuestionType === 50 || question.QuestionType === 55 || question.QuestionType === 1026"
          clearable :multiple="question.OptionTypeEnum === 1" @change="((val) => { formItemChange(val, question) })">
          <template v-if="question.TableQuestionType === 1">
            <el-option v-for="item in organList" :key="item.Id" :label="item[question.DataTableColumn]"
              :value="item[question.DataTableColumn]" />
          </template>
          <template v-else-if="question.QuestionGenre === 3 && question.QuestionType === 47 && question.IsBaseLineTask">
            <el-option v-for="item of $d[question.DictionaryCode]"
              v-show="item.value === 1 || item.value === 2 || item.value === 5" :key="item.id"
              :value="String(item.value)" :label="item.label" />
          </template>
          <template
            v-else-if="question.QuestionGenre === 3 && question.QuestionType === 47 && !question.IsBaseLineTask">
            <el-option-group
              :label="!isNaN(parseFloat(question.LastTaskAnswer)) ? `${$t('trials:dicomReading:tip:lastVisitStatus')} ${$fd(question.DictionaryCode, parseFloat(question.LastTaskAnswer))}` : ''">
              <el-option v-for="item of $d[question.DictionaryCode]"
                v-show="item.value === 1 || item.value === 3 || item.value === 4 || item.value === 5" :key="item.id"
                :value="String(item.value)" :label="item.label" />
            </el-option-group>
          </template>
          <template v-else-if="question.QuestionGenre === 3 && question.QuestionType === 49 && question.IsBaseLineTask">
            <el-option v-for="item of $d[question.DictionaryCode]"
              v-show="item.value === 1 || item.value === 5 || item.value === 6" :key="item.id"
              :value="String(item.value)" :label="item.label" />
          </template>
          <template
            v-else-if="question.QuestionGenre === 3 && question.QuestionType === 49 && !question.IsBaseLineTask">
            <el-option-group
              :label="!isNaN(parseFloat(question.LastTaskAnswer)) ? `${$t('trials:dicomReading:tip:lastVisitStatus')} ${$fd(question.DictionaryCode, parseFloat(question.LastTaskAnswer))}` : ''">
              <el-option v-for="item of $d[question.DictionaryCode]"
                v-show="item.value === 1 || item.value === 2 || item.value === 3 || item.value === 4 || item.value === 5"
                :key="item.id" :value="String(item.value)" :label="item.label" />
            </el-option-group>
          </template>
          <template v-else-if="question.TableQuestionType === 3 || question.QuestionGenre === 3">
            <el-option v-for="item of $d[question.DictionaryCode]" :key="item.id" :value="String(item.value)"
              :label="item.label" />
          </template>
          <template
            v-else-if="(question.TableQuestionType === 2 || question.QuestionGenre === 2) && question.DictionaryCode">
            <el-option v-for="item of $d[question.DictionaryCode]" :key="item.id" :value="String(item.value)"
              :label="item.label" />
          </template>
          <template v-else>
            <el-option v-for="val in question.TypeValue.split('|')" :key="val" :label="val" :value="val" />
          </template>
        </el-select>
        <!-- 单选 -->
        <el-radio-group v-else-if="question.Type === 'radio'" v-model="questionForm[question.Id]"
          :disabled="readingTaskState >= 2 || isFirstChangeTask" @change="((val) => { formItemChange(val, question) })">
          <template v-if="question.DictionaryCode">
            <el-radio v-for="item of $d[question.DictionaryCode]" :key="item.id" :label="String(item.value)">
              {{ item.label }}
            </el-radio>
          </template>
          <template v-else-if="question.TypeValue">
            <el-radio v-for="val in question.TypeValue.split('|')" :key="val" :label="val">
              {{ val }}
            </el-radio>
          </template>
        </el-radio-group>
        <!-- 复选框 -->
        <el-checkbox-group v-else-if="question.Type === 'checkbox'" v-model="questionForm[question.Id]"
          :disabled="readingTaskState >= 2 || isFirstChangeTask">
          <el-checkbox v-for="val in question.TypeValue.split('|')" :key="val" :label="val">
            {{ val }}
          </el-checkbox>
        </el-checkbox-group>
        <!-- 数值 -->
        <!-- <el-input-number
          v-else-if="question.Type==='number'"
          v-model="questionForm[question.Id]"
          :disabled="readingTaskState >= 2 || isFirstChangeTask"
          :precision="2"
        /> -->
        <div style="display: flex;justify-content: space-between;"
          v-else-if="question.Type === 'number' || question.Type === 'calculation'">
          <template v-if="question.Type === 'number'">
            <el-input 
              v-if="question.Unit"
              type="number"
              @input="(val) => questionForm[question.Id] = val.replace(/[^\d.]/g, '')"
              @blur="handleBlur(questionForm[question.Id], questionForm, question)"
              v-model.trim="questionForm[question.Id]" :disabled="readingTaskState === 2">
              <template slot="append" v-if="question.Unit !== 0">{{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit) : question.CustomUnit }}</template>
              <template slot="append" v-else-if="question.ValueType === 2">%</template>
            </el-input>
            <el-input-number v-else-if="question.ValueType === 0" v-model="questionForm[question.Id]" :precision="0"
              :disabled="readingTaskState >= 2 || isFirstChangeTask" />
            <el-input-number v-else-if="question.ValueType === 3" v-model="questionForm[question.Id]"
              :disabled="readingTaskState >= 2 || isFirstChangeTask" />
            <el-input-number v-else-if="question.ValueType === 1 || question.ValueType === 2"
              v-model="questionForm[question.Id]" :precision="digitPlaces"
              :disabled="readingTaskState >= 2 || isFirstChangeTask" />
          </template>
          <el-input v-else-if="question.Type === 'calculation'" v-model="questionForm[question.Id]" disabled>
            <template v-if="question.Unit" slot="append">
              {{ $fd('ValueUnit', parseInt(question.Unit)) }}
            </template>
          </el-input>
          <svg-icon v-if="question.ShowChartTypeEnum > 0" icon-class="readingChart" class="svg-icon svg-readingChart"
            @click.stop="(e) => handleReadingChart({
              e,
              data: {
                QuestionId: question.Id,
                QuestionName: question.QuestionName
              }
            })" />
        </div>
        <!-- 上传图像 -->
        <el-upload v-else-if="question.Type === 'upload'" action :accept="accept" :limit="question.ImageCount"
          :on-preview="handlePictureCardPreview" :before-upload="handleBeforeUpload" :http-request="uploadScreenshot"
          list-type="picture-card" :on-remove="handleRemove" :file-list="fileList"
          :class="{ disabled: fileList.length >= question.ImageCount }"
          :disabled="readingTaskState >= 2 || isFirstChangeTask">
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="OSSclientConfig.basePath + file.url" alt="">
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in" />
              </span>

              <span v-if="readingTaskState < 2" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog v-if="question.Type === 'upload'" append-to-body :visible.sync="imgVisible" width="600px">
          <el-image :src="imageUrl" width="100%">
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </el-image>
        </el-dialog>
      </el-form-item>
    </template>

    <QuestionItem v-for="(item) in question.Childrens" :key="item.Id" :question="item"
      :reading-task-state="readingTaskState" :is-first-change-task="isFirstChangeTask" :question-form="questionForm"
      :visit-task-id="visitTaskId" @setFormItemData="setFormItemData" @resetFormItemData="resetFormItemData" />
  </div>
</template>
<script>
// import { uploadReadingAnswerImage } from '@/api/trials'
import DicomEvent from './DicomEvent'
import { mapGetters } from 'vuex'
export default {
  name: 'QuestionItem',
  props: {
    questionForm: {
      type: Object,
      default() {
        return {}
      }
    },
    question: {
      type: Object,
      default() {
        return []
      }
    },
    readingTaskState: {
      type: Number,
      required: true
    },
    visitTaskId: {
      type: String,
      default: ''
    },
    isFirstChangeTask: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      accept: '.png,.jpg,.jpeg',
      imgVisible: false,
      imageUrl: '',
      urls: [],
      digitPlaces: 2
    }
  },
  computed: {
    ...mapGetters(['language'])
  },
  watch: {
    questionForm: {
      deep: true,
      immediate: true,
      handler(v) {
        // console.log(v)
      }
    }
  },
  mounted() {
    if (this.question.Type === 'upload') {
      if (this.questionForm[this.question.Id]) {
        this.urls = this.questionForm[this.question.Id].split('|')
        this.fileList = []

        this.urls.map(url => {
          this.fileList.push({ name: '', url: `/api/${url}` })
        })
      }
    }
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
  },
  methods: {
    formItemChange(v, question) {
      // if (parseInt(v) !== 5) {
      //   return
      // }

      if (question.Childrens.length > 0) {
        this.resetChild(question.Childrens)
      } else {
        this.$emit('setFormItemData', { key: question.Id, val: v })
      }
    },
    resetChild(obj) {
      obj.forEach(i => {
        this.$emit('resetFormItemData', i.Id)
        if (i.Childrens && i.Childrens.length > 0) {
          this.resetChild(i.Childrens)
        }
      })
    },
    resetFormItemData(v) {
      this.$emit('resetFormItemData', v)
    },
    setFormItemData(obj) {
      this.$emit('setFormItemData', obj)
    },
    addAnnotation(question) {
      DicomEvent.$emit('addAnnotation', question)
    },
    saveAnnotation(question) {
      DicomEvent.$emit('saveAnnotation', question)
    },
    removeAnnotation(question) {
      DicomEvent.$emit('locateAnnotation', question)
      // 是否确认清除标记？
      this.$confirm(this.$t('trials:reading:warnning:msg47'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          DicomEvent.$emit('removeAnnotation', question)
        })
        .catch(() => { })
    },
    locateAnnotation(question) {
      DicomEvent.$emit('locateAnnotation', question)
    },
    async uploadScreenshot(param) {
      if (!this.visitTaskId) return
      const loading = this.$loading({
        target: document.querySelector('.ecrf-wrapper'),
        fullscreen: false,
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      })
      var file = await this.fileToBlob(param.file)
      const res = await this.OSSclient.put(`/${this.trialId}/ReadAttachment/${this.subjectId}/${this.visitTaskId}/${param.file.name}`, file)
      this.fileList.push({ name: param.file.name, url: this.$getObjectName(res.url) })
      this.urls.push(this.$getObjectName(res.url))
      this.$emit('setFormItemData', { key: this.question.Id, val: this.urls.length > 0 ? this.urls.join('|') : '' })
      loading.close()
    },
    handleBeforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        // this.fileList = []
        return true
      } else {
        this.$alert(`必须是 ${this.accept} 格式`)
        return false
      }
    },
    checkFileSuffix(fileName) {
      var index = fileName.lastIndexOf('.')
      var suffix = fileName.substring(index + 1, fileName.length)
      if (this.accept.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) === -1) {
        return false
      } else {
        return true
      }
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.imageUrl = this.OSSclientConfig.basePath + file.url
      this.imgVisible = true
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.imageUrl = ''
      this.fileList.splice(this.fileList.findIndex(f => f.url === file.url), 1)
      this.urls.splice(this.fileList.findIndex(f => f === file.url), 1)
      this.$emit('setFormItemData', { key: this.question.Id, val: this.urls.length > 0 ? this.urls.join('|') : '' })
    },
    handleBlur(value, a, item) {
      if (!value || item.ValueType === 3) return false
      const num = parseFloat(this.questionForm[item.Id])
      if (!isNaN(num)) {
        this.$set(this.questionForm, item.Id, parseFloat(num).toFixed(this.digitPlaces))
        if (item.ValueType === 0) {
          // 整型
          this.$set(this.questionForm, item.Id, parseInt(num))
        }  else if (item.ValueType === 1 || item.ValueType === 2){
          // 小数、百分比
          this.$set(this.questionForm, item.Id, parseFloat(num).toFixed(this.digitPlaces))
        }
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.mb {
  margin-bottom: 0px;
}

.disabled {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}

.uploadWrapper {
  display: flex;
  flex-direction: column !important;
  align-items: flex-start;
}

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

::v-deep .el-input-group__append,
.el-input-group__prepend {
  padding: 0 10px;
}

::v-deep .el-form-item__content {
  width: 100%;
}

::v-deep .el-select.is-disabled .el-input__inner {
  background-color: #646464a1;
}

::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner {
  background-color: #428bca;
  border-color: #428bca;
}
</style>
