<template>
  <el-form
    ref="feedBackForm"
    v-loading="loading"
    :model="form"
    label-width="340px"
    size="small"
    :rules="rules"
    class="feedback-form"
  >
    <div class="base-dialog-body" style="min-height: 500px;">
      <!-- 是否认可医学反馈 -->
      <el-form-item
        :label="$t('trials:medicalFeedback:form:isEndorse')"
        prop="DoctorUserIdeaEnum"
      >
        <el-radio-group
          v-model="form.DoctorUserIdeaEnum"
          @change="handleDoctorUserIdeaChange"
        >
          <el-radio
            v-for="item of $d.MedicalReviewDoctorUserIdea"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 原因 -->
      <el-form-item
        v-if="form.DoctorUserIdeaEnum===2"
        :label="$t('trials:medicalFeedback:title:reason')"
        prop="DisagreeReason"
      >
        <el-input
          v-model="form.DisagreeReason"
        />
      </el-form-item>
      <!-- 是否申请重阅 -->
      <el-form-item
        v-if="form.DoctorUserIdeaEnum===1"
        :label="$t('trials:medicalFeedback:form:isRequestReread')"
        prop="IsApplyHeavyReading"
      >
        <el-radio-group
          v-model="form.IsApplyHeavyReading"
          @change="handleIsApplyHeavyReadingChange"
        >
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="`IsApplyHeavyReading${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 申请原因 -->
      <el-form-item
        v-if="form.IsApplyHeavyReading"
        :label="$t('trials:medicalFeedback:form:applyReason')"
        prop="ReReadingReason"
        :rules="[
          { required: true, message: $t('common:ruleMessage:select')},
        ]"
      >
        <el-radio-group v-model="form.ReReadingReason">
          <!-- 阅片记录错误 -->
          <el-radio :label="$t('trials:medicalFeedback:form:errorRecords')" />
          <!-- 其他 -->
          <el-radio :label="$t('trials:medicalFeedback:form:other')" />
        </el-radio-group>
      </el-form-item>
      <!-- 备注 -->
      <el-form-item
        v-if="form.ReReadingReason === $t('trials:medicalFeedback:form:other')"
        :label="$t('trials:medicalFeedback:form:remark')"
        prop="OtherReason"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500` }
        ]"
      >
        <el-input
          v-model="form.OtherReason"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          :placeholder="$t('common:ruleMessage:specify')"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <!-- 是否复制阅片表单 -->
      <el-form-item
        v-if="form.IsApplyHeavyReading"
        :label="$t('trials:medicalFeedback:form:isCopyForm')"
        prop="IsCopyOrigenalForms"
        :rules="[
          { required: true, message: $t('common:ruleMessage:select')},
        ]"
      >
        <el-radio-group v-model="form.IsCopyOrigenalForms">
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="'IsCopyOrigenalForms' + item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 是否复制阅片表单 -->
      <el-form-item
        v-if="form.IsApplyHeavyReading"
        :label="$t('trials:medicalFeedback:form:isCopyForm2')"
        prop="IsCopyFollowForms"
        :rules="[
          { required: true, message: $t('common:ruleMessage:select')},
        ]"
      >
        <el-radio-group v-model="form.IsCopyFollowForms">
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="'IsCopyFollowForms' + item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 相关截图 -->
      <el-form-item
        :label="$t('trials:medicalFeedback:form:screenShot')"
      >
        <el-upload
          :action="accept"
          :on-preview="handlePictureCardPreview"
          :before-upload="handleBeforeUpload"
          :http-request="uploadScreenshot"
          list-type="picture-card"
          :on-remove="handleRemove"
          :file-list="fileList"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{file}">
            <img
              class="el-upload-list__item-thumbnail"
              crossorigin="anonymous"
              :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
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog
          append-to-body
          :visible.sync="imgVisible"
          width="600px"
        >
          <!-- <img width="100%" :src="imageUrl" alt="图片未找到"> -->
          <el-image :src="imageUrl" crossorigin="anonymous" width="100%">
            <div slot="placeholder" class="image-slot">
              {{ $t('trials:medicalFeedback:message:loading') }}<span class="dot">...</span>
            </div>
          </el-image>
        </el-dialog>
      </el-form-item>
      <!--      <el-form-item v-if="form.IsApplyHeavyReading" label="重阅影响任务列表">-->
      <!--      </el-form-item>-->
      <div v-if="form.IsApplyHeavyReading" style="margin-bottom: 10px;padding-left: 5px;font-weight: bold;color: #666;">
        <!-- 重阅影响任务列表 -->
        {{ $t('trials:medicalFeedback:form:influenceList') }}
      </div>
      <el-table
        v-if="form.IsApplyHeavyReading"
        v-loading="listLoading"
        :data="InfluenceTaskList"
        stripe
        border
      >
        <!-- 任务编号 -->
        <el-table-column
          prop="TaskCode"
          :label="$t('trials:readTask:table:taskCode')"
          min-width="100"
          show-overflow-tooltip
        />
        <!-- 中心编号 -->
        <el-table-column
          prop="TrialSiteCode"
          :label="$t('trials:readTask:table:siteCode')"
          min-width="100"
          show-overflow-tooltip
        />
        <!-- 受试者编号 -->
        <el-table-column
          prop="SubjectCode"
          :label="$t('trials:readTask:table:subjectCode')"
          min-width="120"
          show-overflow-tooltip
        />
        <!-- 访视/阅片期名称 -->
        <!-- <el-table-column
          prop="VisitTaskNum"
          label="访视/阅片期名称"
          min-width="140"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.TaskName }}
          </template>
        </el-table-column> -->
        <!-- 盲态任务标识 -->
        <el-table-column
          prop="TaskBlindName"
          :label="$t('trials:readTask:table:blindName')"
          min-width="120"
          show-overflow-tooltip
        />
        <!-- 阅片标准 -->
        <el-table-column
          prop="TrialReadingCriterionName"
          :label="$t('trials:readTask:table:criterionName')"
          min-width="100"
          show-overflow-tooltip
        />
        <!-- 任务状态 -->
        <el-table-column
          prop="TaskState"
          :label="$t('trials:readTask:table:taskState')"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.TaskState === 0" type="primary">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
            <el-tag v-if="scope.row.TaskState === 1" type="info">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
            <el-tag v-if="scope.row.TaskState === 3" type="danger">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
            <el-tag v-if="scope.row.TaskState === 4" type="warning">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
            <el-tag v-if="scope.row.TaskState === 5" type="danger">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 任务类型 -->
        <el-table-column
          prop="ReadingCategory"
          min-width="100"
          :label="$t('trials:readTask:table:readingCategory')"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.ReadingCategory === 1" type="primary">{{ $fd('ReadingCategory', scope.row.ReadingCategory) }}</el-tag>
            <el-tag v-if="scope.row.ReadingCategory === 2" type="info">{{ $fd('ReadingCategory', scope.row.ReadingCategory) }}</el-tag>
            <el-tag v-if="scope.row.ReadingCategory === 4" type="danger">{{ $fd('ReadingCategory', scope.row.ReadingCategory) }}</el-tag>
            <el-tag v-if="scope.row.ReadingCategory === 5" type="warning">{{ $fd('ReadingCategory', scope.row.ReadingCategory) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 阅片状态 -->
        <el-table-column
          prop="ReadingTaskState"
          :label="$t('trials:readTask:table:readingTaskState')"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.ReadingTaskState === 2" type="primary">{{ $fd('ReadingTaskState', scope.row.ReadingTaskState) }}</el-tag>
            <el-tag v-else type="danger">{{ $fd('ReadingTaskState', scope.row.ReadingTaskState) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 生效后影响 -->
        <el-table-column
          prop="OptType"
          :label="$t('trials:readTask:table:optType')"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.OptType === 0" type="primary">{{ $fd('ReReadingOrBackOptType', scope.row.OptType) }}</el-tag>
            <el-tag v-if="scope.row.OptType === 1" type="danger">{{ $fd('ReReadingOrBackOptType', scope.row.OptType) }}</el-tag>
            <el-tag v-if="scope.row.OptType === 2" type="warning">{{ $fd('ReReadingOrBackOptType', scope.row.OptType) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 阅片人 -->
        <el-table-column
          prop="UserName"
          :label="$t('trials:readTask:table:reader')"
          min-width="160"
          show-overflow-tooltip
        >
          <template v-if="scope.row.DoctorUser" slot-scope="scope">
            {{ scope.row.DoctorUser.UserName }}({{ scope.row.DoctorUser.FullName }})
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <el-form-item style="text-align:right;">
        <!-- 取消 -->
        <el-button
          size="small"
          type="primary"
          @click="handleClose"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 发送 -->
        <el-button
          size="small"
          type="primary"
          @click="handleSave"
        >
          {{ $t('trials:medicalFeedback:button:send') }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import { iRSendMedicalReviewDialog, UploadMedicalReviewImage } from '@/api/trials'
import { getReReadingOrBackInfluenceTaskList } from '@/api/trials/reading'
export default {
  name: 'FeedbackFrom',
  props: {
    taskMedicalReviewId: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    }
  },

  data() {
    return {
      form: {
        TaskMedicalReviewId: '',
        DoctorUserIdeaEnum: null,
        DisagreeReason: '',
        IsApplyHeavyReading: null,
        IsCopyOrigenalForms: null,
        IsCopyFollowForms: null,
        RequestReReadingType: 0,
        RequestReReadingReason: '',
        ReReadingReason: '',
        OtherReason: '',
        // ImagePath: '',
        // FileName: ''
        FileList: []
      },
      InfluenceTaskList: [],
      rules: {
        DoctorUserIdeaEnum: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        DisagreeReason: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500` }],
        IsApplyHeavyReading: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]
      },
      loading: false,
      accept: '.png,.jpg,.jpeg',
      imgVisible: false,
      imageUrl: '',
      uploadDisabled: false,
      listLoading: false,
      fileList: []
    }
  },
  mounted() {

  },
  methods: {
    // 更新qc问题配置信息
    handleSave() {
      this.$refs.feedBackForm.validate(valid => {
        if (!valid) return
        this.loading = true
        this.form.TaskMedicalReviewId = this.taskMedicalReviewId
        this.form.RequestReReadingReason = this.form.OtherReason ? this.form.OtherReason : this.form.ReReadingReason
        this.form.TrialId = this.$route.query.trialId
        var files = []
        this.fileList.map(file => {
          files.push({ FileName: file.name, ImagePath: file.url })
        })
        this.form.FileList = files
        iRSendMedicalReviewDialog(this.form).then(res => {
          this.loading = false
          if (res.IsSuccess) {
            // 关闭弹窗并刷新
            this.$emit('close')
            this.$emit('getList')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
        }).catch(() => { this.loading = false })
      })
    },
    handleClose() {
      this.$emit('close')
    },
    handleIsApplyHeavyReadingChange(val) {
      if (val === true) {
        this.listLoading = true
        getReReadingOrBackInfluenceTaskList(this.visitTaskId, true).then(res => {
          this.InfluenceTaskList = res.Result
          this.listLoading = false
        }).catch(() => { this.listLoading = false })
      }
    },
    handleDoctorUserIdeaChange(val) {
      console.log('handleDoctorUserIdeaChange:  ' + val)
      this.form.IsApplyHeavyReading = null
      this.form.IsCopyOrigenalForms = null
      this.form.IsCopyFollowForms = null
      this.form.RequestReReadingType = 0
      this.form.RequestReReadingReason = ''
      this.form.ReReadingReason = ''
      this.form.OtherReason = ''
      this.form.DisagreeReason = ''
    },
    handleBeforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        return true
      } else {
        var msg = this.$t('trials:medicalFeedback:message:format')
        msg = msg.replace('xxx', this.accept)
        this.$alert(msg)
        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
      }
    },
    async uploadScreenshot(param) {
      this.loading = true
      this.uploadDisabled = false
      var file = await this.fileToBlob(param.file)
      const res = await this.OSSclient.put(`/System/${this.$route.query.trialId}/MedicalReviewImage/${param.file.name}`, file)
      this.fileList.push({ name: param.file.name, url: this.$getObjectName(res.url)})
      this.loading = false
      this.uploadDisabled = true
    },
    // 预览图片
    handlePictureCardPreview(file) {
      // this.imgVisible = true
      // this.uploadDisabled = true
      this.imageUrl = this.OSSclientConfig.basePath + file.url
      this.imgVisible = true
    },
    // 删除图片
    handleRemove(file, fileList) {
      var idx = this.fileList.findIndex(i => i.url === file.url)
      if (idx === -1) return
      this.fileList.splice(idx, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.feedback-form{
.disabled{
  /deep/ .el-upload--picture-card {
    display: none;
  }
}
/deep/  .el-upload-list__item {
    transition: none !important;
  }
  /deep/  .el-upload-list__item-thumbnail {
      /* 图片在方框内显示长边 */
      object-fit: scale-down !important;
  }
}
</style>
