<template>
  <div class="conclusions">

    <el-form
      ref="conclusionsForm"
      v-loading="loading"
      :model="form"
      label-width="100px"
      style="width:500px"
    >

      <el-form-item style="text-align:right;width: 500px;">
        <!-- <el-button
          v-if="userTypeEnumInt===14 && auditState !== 2"
          type="primary"
          size="small"
          :disabled="isSendMessage"
          @click="handleSave(true)"
        >
          {{ form.IsHaveQuestion?$t('trials:medicalFeedback:button:saveAndSend'):$t('common:button:save') }}
        </el-button> -->
        <!-- <el-button
          v-if="form.IsHaveQuestion === true && isSendMessage && userTypeEnumInt===14"
          type="primary"
          size="small"
          @click="handleReply"
        >
          {{ isClosedDialog?$t('trials:medicalFeedback:button:viewQuestions'):$t('trials:medicalFeedback:button:reply') }}
        </el-button>

        <el-button
          v-if="form.IsHaveQuestion === true && isSendMessage && userTypeEnumInt===13"
          type="primary"
          size="small"
          @click="handleReply"
        >
          {{ isClosedDialog?$t('trials:medicalFeedback:button:viewQuestions'):$t('trials:medicalFeedback:button:reply') }}
        </el-button> -->
        <!-- 查看质询 -->
        <!-- <el-button
          v-if="form.IsHaveQuestion === true && isSendMessage && userTypeEnumInt!==13 && userTypeEnumInt!==14"
          type="primary"
          size="small"
          @click="handleReply"
        >
          {{ $t('trials:medicalFeedback:button:viewQuestions') }}
        </el-button> -->
        <!-- 关闭 -->
        <!-- <el-button
          v-if="userTypeEnumInt===14 && form.IsHaveQuestion === true && !isClosedDialog && isSendMessage "
          type="primary"
          size="small"
          @click="handleCloseReply"
        >
          {{ $t('trials:medicalFeedback:button:close') }}
        </el-button> -->
      </el-form-item>
      <!-- 是否有问题 -->
      <el-form-item
        :label="$t('trials:medicalFeedback:button:isQuestions')"
        prop="IsHaveQuestion"
        :rules="[
          { required: true, message: $t('common:ruleMessage:select')},
        ]"
      >
        <el-radio-group
          v-model="form.IsHaveQuestion"
          :disabled="isSendMessage || auditState===2 || userTypeEnumInt!==14"
        >
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="'IsHaveQuestion' + item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 质询问题 -->
      <el-form-item
        v-if="form.IsHaveQuestion === true"
        :label="$t('trials:medicalFeedback:title:qcQuestions')"
        prop="Questioning"
        maxlength="500"
        autosize
        show-word-limit
        :rules="[
          { required: true, message: $t('common:ruleMessage:specify')},
        ]"
      >
        <el-input :maxLength="$inputMax"
          v-model="form.Questioning"
          type="textarea"
          :disabled="isSendMessage || auditState===2 || userTypeEnumInt!==14"
        />
      </el-form-item>
      <!-- 审核建议 -->
      <el-form-item
        v-if="form.IsHaveQuestion === true"
        :label="$t('trials:medicalFeedback:title:auditAdviceEnum')"
        prop="AuditAdviceEnum"
        :rules="[
          { required: true, message: $t('common:ruleMessage:select')},
        ]"
      >
        <el-radio-group
          v-model="form.AuditAdviceEnum"
          :disabled="isSendMessage || auditState===2 || userTypeEnumInt!==14"
        >
          <el-radio
            v-for="item of $d.AuditAdvice"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 相关截图 -->
      <el-form-item
        v-if="form.IsHaveQuestion === true"
        :label="$t('trials:medicalFeedback:form:screenShot')"
      >
        <el-upload
          :action="accept"
          :class="{disabled:isSendMessage}"
          :on-preview="handlePictureCardPreview"
          :before-upload="handleBeforeUpload"
          :http-request="uploadScreenshot"
          list-type="picture-card"
          :on-remove="handleRemove"
          :file-list="fileList"

          :disabled="isSendMessage || auditState===2 || userTypeEnumInt!==14"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{file}">
            <img
              class="el-upload-list__item-thumbnail"
              :src="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="!isSendMessage && auditState!==2"
                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" 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>

    <el-dialog
      v-if="chatVisible"
      :visible.sync="chatVisible"
      :close-on-click-modal="false"
      width="800px"
      :title="`${$t('trials:medicalFeedback:title:qaRecord')} (${subjectCode} ${taskBlindName})`"
      append-to-body
    >
      <ChatForm
        ref="chatForm"
        :visit-task-id="visitTaskId"
        :task-medical-review-id="form.TaskMedicalReviewId"
        @handleCloseReply="handleCloseReply"
      />
    </el-dialog>

    <!-- 关闭质疑 -->
    <el-dialog
      v-if="closeQuestionVisible"
      :visible.sync="closeQuestionVisible"
      :close-on-click-modal="false"
      append-to-body
      custom-class="base-dialog-wrapper"
      width="600px"
      :title="$t('trials:medicalFeedback:title:closeQc')"
    >
      <CloseQC
        :task-medical-review-id="medicalReviewInfo.TaskMedicalReviewId"
        @close="closeQuestionVisible = false"
        @refresh="refresh"
      />
    </el-dialog>
  </div>
</template>
<script>
import { UploadMedicalReviewImage, saveMedicalReviewInfo } from '@/api/trials'
import ChatForm from './ChatForm'
import CloseQC from './CloseQC'
export default {
  name: 'AuditConclusions',
  components: {
    ChatForm,
    CloseQC
  },
  props: {
    medicalReviewInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    auditState: {
      type: Number,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    subjectCode: {
      type: String,
      required: true
    },
    taskBlindName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {
        TaskMedicalReviewId: '',
        IsHaveQuestion: null,
        Questioning: '',
        AuditAdviceEnum: null,
        FileList: []
      },

      loading: false,
      accept: '.png,.jpg,.jpeg',
      imgVisible: false,
      imageUrl: '',
      uploadDisabled: false,
      fileList: [],
      chatVisible: false,
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      isClosedDialog: false,
      isSendMessage: false,
      closeQuestionVisible: false
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    initForm() {
      if (Object.keys(this.medicalReviewInfo).length > 0) {
        for (const k in this.form) {
          if (this.medicalReviewInfo.hasOwnProperty(k)) {
            this.form[k] = this.medicalReviewInfo[k]
          }
        }
        this.fileList = []
        if (this.form.FileList) {
          this.form.FileList.map(file => {
            this.fileList.push({ name: file.FileName, url: file.ImagePath })
          })
        }
        this.isClosedDialog = this.medicalReviewInfo.IsClosedDialog
        this.isSendMessage = this.medicalReviewInfo.IsSendMessage
      }
    },
    handleSave(isPrompt) {
      return new Promise((resolve, reject) => {
        this.$refs['conclusionsForm'].validate((valid) => {
          if (!valid) {
            reject()
          } else {
            this.loading = true
            this.form.IsSendDialog = this.form.IsHaveQuestion
            var files = []
            this.fileList.map(file => {
              files.push({ FileName: file.name, ImagePath: file.url })
            })
            this.form.FileList = files
            saveMedicalReviewInfo(this.form).then(res => {
              if (isPrompt) {
                this.$message.success(this.$t('common:message:savedSuccessfully'))
                this.$emit('getMedicalAuditList')
              }
              this.isSendMessage = this.form.IsHaveQuestion
              this.loading = false
              resolve()
            }).catch(() => {
              this.loading = false
              reject()
            })
          }
        })
      })
    },
    save() {
      return new Promise((resolve, reject) => {
        this.$refs['conclusionsForm'].validate((valid) => {
          if (!valid) {
            resolve(false)
          } else {
            this.loading = true
            this.form.IsSendDialog = this.form.IsHaveQuestion
            var files = []
            this.fileList.map(file => {
              files.push({ FileName: file.name, ImagePath: file.url })
            })
            this.form.FileList = files
            saveMedicalReviewInfo(this.form).then(res => {
              this.$emit('getMedicalAuditList')
              this.isSendMessage = this.form.IsHaveQuestion
              this.loading = false
              resolve(true)
            }).catch(() => {
              this.loading = false
              reject()
            })
          }
        })
      })
    },
    handleReply() {
      this.chatVisible = true
    },
    handleCloseReply() {
      this.closeQuestionVisible = true
    },
    refresh() {
      this.isClosedDialog = true
      this.$emit('getMedicalAuditList')
      this.$refs['chatForm'].getMessageList()
    },
    uploadScreenshot(param) {
      this.loading = true
      const formData = new FormData()
      formData.append('file', param.file)
      UploadMedicalReviewImage(this.$route.query.trialId, this.form.TaskMedicalReviewId, formData).then(res => {
        this.loading = false
        if (res.IsSuccess) {
          this.fileList.push({ name: res.Result.FileName, url: res.Result.Path })
        }
      }).catch(() => {
        this.loading = false
      })
    },
    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.$message.error(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
      }
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.imageUrl = 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>
.conclusions{
  .disabled{
    >>>.el-upload--picture-card {
      display: none;
    }
  }
  >>> .el-upload-list__item {
    transition: none !important;
  }
  >>> .el-upload-list__item-thumbnail {
      /* 图片在方框内显示长边 */
      object-fit: scale-down !important;
  }
}
</style>
