<template>
  <div class="adReview_wrapper">
    <el-card shadow="never" :body-style="{ padding: '10px' }" style="margin-bottom:10px">
      <h4 v-if="isReadingShowSubjectInfo">
        受试者：
        <span style="font-weight:normal">{{ subjectCode }} </span>
        <span style="font-weight:normal">({{ taskBlindName }})</span>
      </h4>
    </el-card>
    <el-card :body-style="{ padding: '10px' }" shadow="never">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold;">评估结果</span>
      </div>
      <!-- <el-table
        :data="adInfo.VisitTaskInfoList"
        style="width: 100%"
      >
        <el-table-column
          prop="ArmEnum"
          label="角色"
          show-overflow-tooltip
          width="150"
        >
          <template slot-scope="scope">
            {{ $fd('ArmEnum', scope.row.ArmEnum) }}
          </template>
        </el-table-column>

        <el-table-column
          v-for="(qs,index) in judgeQuestion"
          :key="qs"
          prop=""
          :label="qs"
          show-overflow-tooltip
          width="150"
        >
          <template slot-scope="scope">
            {{ scope.row.JudgeQuestionAnswerInfoList[index].Answer }}
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common:action:action')"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              circle
              title="查看详情"
              icon="el-icon-view"
              @click="handleView(scope.row,1)"
            />
          </template>
        </el-table-column>
      </el-table> -->

      <el-table
        :data="adInfo.VisitInfoList"
        style="width: 100%"
      >
        <el-table-column
          prop="VisitName"
          label="访视名称"
          show-overflow-tooltip
          width="150"
        />

        <!-- 评估结果 -->
        <el-table-column
          v-for="j in judgeQuestion"
          :key="j.armEnum"
          :label="$fd('ArmEnum', j.armEnum)"
          align="center"
          prop=""
        >
          <template>
            <el-table-column
              v-for="(qs,i) in j.judgeQuestionList"
              :key="i"
              prop=""
              :label="qs"
              show-overflow-tooltip
              width="150"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.VisitTaskInfoList[j.index].JudgeQuestionList[i].QuestionType===2">
                  <div v-if="scope.row.VisitTaskInfoList[j.index].JudgeQuestionList[i].Answer">
                    <span>{{ $fd('YesOrNo', scope.row.VisitTaskInfoList[j.index].JudgeQuestionList[i].Answer ) }}</span>
                    <el-button
                      type="text"
                      style="margin-left:5px;"
                      @click="handleViewDetail(scope.row.VisitTaskInfoList[j.index].GlobalVisitTaskId)"
                    >
                      查看详情
                    </el-button>
                  </div>
                  <div v-else>
                    {{ $fd('YesOrNo', scope.row.VisitTaskInfoList[j.index].JudgeQuestionList[i].Answer ) }}
                  </div>
                </div>
                <div v-else>{{ scope.row.VisitTaskInfoList[j.index].JudgeQuestionList[i].Answer }}</div>
              </template>
            </el-table-column>
          </template>
        </el-table-column>

        <el-table-column
          label="查看详情"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              title="查看R1详情"
              @click="handleView(scope.row,1)"
            >
              R1
            </el-button>
            <el-button
              type="text"
              title="查看R2详情"
              @click="handleView(scope.row,2)"
            >
              R2
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="{ padding: '10px' }" class="box-mr">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold;">裁判结果</span>
      </div>
      <el-form
        ref="adForm"
        v-loading="loading"
        :model="adForm"
        style="width:600px"
        label-width="100px"
      >
        <el-form-item
          label="选择阅片人"
          prop="judgeResultTaskId"
          :rules="[
            { required: true, message: '请选择'},
          ]"
        >
          <el-radio-group
            v-model="adForm.judgeResultTaskId"
            :disabled="adInfo.ReadingTaskState >= 2"
          >
            <el-radio
              v-for="t in visitTaskArmList"
              :key="t.VisitTaskId"
              :label="t.VisitTaskId"
            >
              {{ $fd('ArmEnum', t.ArmEnum) }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="裁判原因"
          prop="judgeResultRemark"
          :rules="[
            { required: true, message: '请注明'},
          ]"
        >
          <el-input
            v-model="adForm.judgeResultRemark"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            :disabled="adInfo.ReadingTaskState >= 2"
          />
        </el-form-item>
        <el-form-item
          label="截图说明"
        >
          <el-upload
            :action="accept"
            :limit="1"
            :on-preview="handlePictureCardPreview"
            :before-upload="handleBeforeUpload"
            :http-request="uploadScreenshot"
            list-type="picture-card"
            :on-remove="handleRemove"
            :file-list="fileList"
            :class="{disabled:uploadDisabled}"
            :disabled="adInfo.ReadingTaskState >= 2"
          >
            <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="adInfo.ReadingTaskState < 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="OSSclientConfig.basePath + imageUrl" width="100%">
              <div slot="placeholder" class="image-slot">
                加载中<span class="dot">...</span>
              </div>
            </el-image>
          </el-dialog>
        </el-form-item>
        <el-form-item v-if="adInfo.ReadingTaskState < 2">
          <div style="text-align:center;">
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </div>

        </el-form-item>
      </el-form>
    </el-card>

    <el-card v-if="isReadingShowPreviousResults" :body-style="{ padding: '10px' }">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold;">既往裁判评估</span>
      </div>

      <el-table
        v-loading="priorLoading"
        :data="priorADList"
        style="width: 100%"
      >
        <el-table-column
          prop="TaskBlindName"
          label="裁判阅片"
          show-overflow-tooltip
          width="200"
        />
        <el-table-column
          :label="$t('common:action:action')"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              circle
              title="查看详情"
              icon="el-icon-view"
              @click="handleViewDetail(scope.row.VisitTaskId)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 签名框 -->
    <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 { getJudgeReadingInfo, uploadJudgeTaskImage, saveJudgeVisitTaskResult, submitJudgeVisitTaskResult, getReadingPastResultList } from '@/api/trials'
import const_ from '@/const/sign-code'
import { getToken } from '@/utils/auth'
import SignForm from '@/views/trials/components/newSignForm'
export default {
  name: 'AdReview',
  components: { SignForm },
  props: {
    trialId: {
      type: String,
      required: true
    },
    subjectId: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    readingCategory: {
      type: Number,
      required: true
    },
    subjectCode: {
      type: String,
      required: true
    },
    taskBlindName: {
      type: String,
      required: true
    },
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    },
    isReadingShowPreviousResults: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      adInfo: {},
      judgeQuestion: [],
      adForm: {
        visitTaskId: '',
        judgeResultTaskId: '',
        judgeResultRemark: '',
        judgeResultImagePath: ''
      },
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      signCode: null,
      accept: '.png,.jpg,.jpeg',
      imgVisible: false,
      imageUrl: '',
      uploadDisabled: false,
      fileList: [],
      loading: false,
      visitTaskArmList: [],
      priorADList: [],
      priorLoading: false
    }
  },
  mounted() {
    this.getAdInfo()
    if (this.isReadingShowPreviousResults) {
      this.getPriorAdList()
    }
  },
  methods: {
    getAdInfo() {
      this.loading = true
      getJudgeReadingInfo({ visitTaskId: this.visitTaskId }).then(res => {
        var judgeQS = []
        if (res.Result.VisitInfoList.length > 0) {
          res.Result.VisitInfoList[0].VisitTaskInfoList.map((v, index) => {
            var qsObj = { armEnum: v.ArmEnum, judgeQuestionList: [], index: index }
            v.JudgeQuestionList.map(q => {
              if (q.QuestionType === 1) {
                qsObj.judgeQuestionList.push(q.QuestionName)
              } else {
                qsObj.judgeQuestionList.push(this.$fd('JudgeReadingQuestionType', q.QuestionType))
              }
            })
            judgeQS.push(qsObj)
          })
        }
        this.judgeQuestion = judgeQS

        this.adInfo = res.Result
        this.adForm.judgeResultTaskId = res.Result.JudgeResultTaskId
        this.adForm.judgeResultRemark = res.Result.JudgeResultRemark

        if (res.Result.JudgeResultImagePath) {
          this.adForm.judgeResultImagePath = res.Result.JudgeResultImagePath
          this.fileList = [{ name: '', url: `/api/${res.Result.JudgeResultImagePath}` }]
          this.imageUrl = `/api/${res.Result.JudgeResultImagePath}`
          this.uploadDisabled = true
        }
        this.visitTaskArmList = res.Result.VisitTaskArmList
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    getPriorAdList() {
      this.priorLoading = true
      getReadingPastResultList({ visitTaskId: this.visitTaskId }).then(res => {
        this.priorADList = res.Result
        this.priorLoading = false
      }).catch(() => { this.priorLoading = false })
    },
    handleSave() {
      this.$refs['adForm'].validate((valid) => {
        if (!valid) return
        this.loading = true

        this.adForm.visitTaskId = this.visitTaskId
        saveJudgeVisitTaskResult(this.adForm).then(res => {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      })
    },
    handleSubmit() {
      this.$refs['adForm'].validate((valid) => {
        if (!valid) return
        const { ImageAssessmentReportConfirmation } = const_.processSignature
        this.signCode = ImageAssessmentReportConfirmation
        this.signVisible = true
      })
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名并确认
    signConfirm(signInfo) {
      this.loading = true
      var params = {
        data: {
          visitTaskId: this.visitTaskId,
          judgeResultTaskId: this.adForm.judgeResultTaskId,
          judgeResultRemark: this.adForm.judgeResultRemark,
          judgeResultImagePath: this.adForm.judgeResultImagePath
        },
        signInfo: signInfo
      }
      submitJudgeVisitTaskResult(params).then(res => {
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.isEdit = false
          this.$refs['signForm'].btnLoading = false
          this.signVisible = false
          window.location.reload()
          window.opener.postMessage('refreshTaskList', window.location)
        }
        this.loading = false
      }).catch(_ => {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      })
    },
    handleViewDetail(visitTaskId) {
      var token = getToken()
      const routeData = this.$router.resolve({
        path: `/readingPage?trialId=${this.trialId}&visitTaskId=${visitTaskId}&TokenKey=${token}&isReadingShowPreviousResults=false`
      })
      window.open(routeData.href, '_blank')
    },
    handleView(row, armEnum) {
      var token = getToken()
      var task = row.VisitTaskInfoList.find(item => item.ArmEnum === armEnum)
      const routeData = this.$router.resolve({
        path: `/readingPage?trialId=${this.trialId}&visitTaskId=${task.VisitTaskId}&TokenKey=${token}&isReadingShowPreviousResults=false`
      })
      window.open(routeData.href, '_blank')
    },
    uploadScreenshot(param) {
      this.loading = true
      this.uploadDisabled = false
      const formData = new FormData()
      formData.append('file', param.file)
      uploadJudgeTaskImage(this.$route.query.trialId, this.visitTaskId, formData).then(res => {
        this.loading = false
        if (res.IsSuccess) {
          this.fileList.push({ name: res.Result.FileName, url: `${res.Result.Path}` })
          this.imageUrl = `${res.Result.Path}`
          this.adForm.judgeResultImagePath = res.Result.Path
        }
        this.uploadDisabled = true
      }).catch(() => {
        this.loading = false
      })
    },
    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
      }
    },
    // 图片清空
    removeImage() {
      this.imageUrl = ''
      this.fileList = []
      this.adForm.judgeResultImagePath = ''
    },
    // 预览图片
    handlePictureCardPreview() {
      this.imgVisible = true
      this.uploadDisabled = true
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.uploadDisabled = false
      this.imageUrl = ''
      this.fileList = []
      this.adForm.judgeResultImagePath = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.adReview_wrapper{
  flex: 1;
  padding: 10px;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  .box-mr{
    margin:10px 0;
  }
  .disabled{
  /deep/ .el-upload--picture-card {
    display: none;
  }
}
}
</style>
