<template>
  <BaseContainer v-loading="loading" style="height: 100%; background-color: #fff">
    <el-tabs v-model="TrialReadingCriterionId" type="border-card">
      <el-tab-pane v-for="i in trialCriterionList" :key="i.TrialReadingCriterionId" :label="i.TrialReadingCriterionName"
        :name="i.TrialReadingCriterionId">
        <div v-if="TrialReadingCriterionId === i.TrialReadingCriterionId">
          <div slot="search-container" style="position: relative">
            <el-form :inline="true">
              <!-- 阅片标准 -->
              <!-- <el-form-item :label="$t('trials:processCfg:form:criterion')">
            <el-select
              v-model="searchData.TrialReadingCriterionId"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="item of trialCriterionList"
                :key="item.TrialReadingCriterionId"
                :label="item.TrialReadingCriterionName"
                :value="item.TrialReadingCriterionId"
              />
            </el-select>
          </el-form-item> -->
              <!-- 受试者编号 -->
              <el-form-item :label="$t('trials:reviewTrack:table:subjectCode')">
                <el-input v-model="searchData.SubjectCode" style="width: 100px" clearable />
              </el-form-item>
              <!-- 患者编号 -->
              <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
                <el-input v-model="searchData.PatientIdStr" style="width: 140px" clearable />
              </el-form-item>
              <!-- 患者姓名 -->
              <el-form-item :label="$t('trials:uploadDicomList:table:patientName')">
                <el-input v-model="searchData.SubjectName" style="width: 140px" clearable />
              </el-form-item>
              <!-- 访视名称 -->
              <el-form-item style="margin-bottom: 10px" :label="$t('trials:adReview:table:visitName')">
                <el-input v-model="searchData.TaskName" style="width: 140px" clearable />
              </el-form-item>
              <!-- 任务状态 -->
              <el-form-item style="margin-bottom: 10px" :label="$t('trials:readTask:table:taskState')">
                <el-select v-model="searchData.TaskState" clearable style="width: 120px">
                  <el-option v-for="i of $d.TaskState" :key="'TaskState' + i.label" :value="i.value" :label="i.label" />
                </el-select>
              </el-form-item>
              <!-- 任务类型 -->
              <!-- <el-form-item
          style="margin-bottom: 10px"
          :label="$t('trials:readTask:table:readingCategory')"
        >
          <el-select
            v-model="searchData.ReadingCategory"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="i of $d.ReadingCategory"
              :key="'ReadingCategory' + i.label"
              :value="i.value"
              :label="i.label"
            />
          </el-select>
        </el-form-item> -->
              <!-- 签名时间 -->
              <el-form-item :label="$t('trials:readTask:table:signTime')">
                <el-date-picker v-model="dateValue" type="datetimerange" range-separator="-"
                  :start-placeholder="$t('trials:uploadClinicalData:table:beginDate')"
                  :end-placeholder="$t('trials:uploadClinicalData:table:endDate')" clearable
                  :default-time="['00:00:00', '23:59:59']">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <!-- 查询 -->
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">
                  {{ $t('common:button:search') }}
                </el-button>
                <!-- 重置 -->
                <el-button type="primary" icon="el-icon-refresh-left" @click="handleReset">
                  {{ $t('common:button:reset') }}
                </el-button>
                <!-- 下载影像 -->
                <el-button type="primary" @click="getDownloadSubjectVisitStudyInfo(multipleSelection)"
                  v-hasPermi="['trials:readTask:report']" :disabled="multipleSelection.length <= 0">
                  {{ $t('trials:inspection:button:downloadImage') }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div slot="main-container">
            <el-table v-adaptive="{ bottomOffset: 75 }" :data="list" stripe height="100" @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" v-if="hasPermi(['trials:readTask:report'])" />
              <!-- 受试者编号 -->
              <el-table-column prop="SubjectCode" min-width="100" :label="$t('trials:reviewTrack:table:subjectCode')"
                show-overflow-tooltip sortable="custom" />
              <!-- 患者编号 -->
              <el-table-column prop="PatientIdStr" min-width="100" :label="$t('trials:uploadDicomList:table:pId')"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-for="(item, index) in scope.row.PatientList" :key="`${index}${item.PatientId}`">
                    {{
                      index === scope.row.PatientList.length - 1
                        ? item.PatientIdStr
                        : `${item.PatientIdStr}, `
                    }}
                  </span>
                </template>
              </el-table-column>
              <!-- 患者姓名 -->
              <el-table-column prop="SubjectShortName" min-width="100"
                :label="$t('trials:uploadDicomList:table:patientName')" show-overflow-tooltip sortable="custom" />
              <!-- 访视名称 -->
              <el-table-column prop="TaskName" :label="$t('trials:adReview:table:visitName')" min-width="100"
                sortable="custom" show-overflow-tooltip />
              <!-- 阅片标准 -->
              <el-table-column prop="TrialReadingCriterionName"
                :label="$t('trials:adReview:table:TrialReadingCriterionName')" min-width="100" sortable="custom"
                show-overflow-tooltip />
              <!-- 任务状态 -->
              <el-table-column prop="TaskState" :label="$t('trials:readTask:table:taskState')" min-width="100"
                sortable="custom" 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="90"
          :label="$t('trials:readTask:table:readingCategory')"
          sortable="custom"
          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="SignTime" min-width="120" :label="$t('trials:readTask:table:signTime')"
                sortable="custom" show-overflow-tooltip />
              <!-- 打包状态 -->
              <!-- <el-table-column
                prop="PackState"
                :label="$t('trials:hirVisit:table:PackState')"
                show-overflow-tooltip
                sortable="custom"
              >
                <template slot-scope="scope">
                  <el-tag
                    :type="
                      Number(scope.row.PackState) === 0
                        ? 'danger'
                        : Number(scope.row.PackState) === 1
                        ? 'warning'
                        : 'success'
                    "
                    >{{
                      $fd('PackState', Number(scope.row.PackState) || 0)
                    }}</el-tag
                  >
                </template>
              </el-table-column> -->
              <!-- 申请状态 -->
              <!-- <el-table-column
          v-if="!hasPermi(['role:air'])"
          prop="ReReadingApplyState"
          :label="$t('trials:readTask:table:reReadingApplyState')"
          min-width="140"
          sortable="custom"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag
              v-if="
                scope.row.ReReadingApplyState === 4 ||
                scope.row.ReReadingApplyState === 5
              "
              type="danger"
              >{{
                $fd("ReReadingApplyState", scope.row.ReReadingApplyState)
              }}</el-tag
            >
            <el-tag v-if="scope.row.ReReadingApplyState === 2" type="primary">{{
              $fd("ReReadingApplyState", scope.row.ReReadingApplyState)
            }}</el-tag>
            <el-tag v-if="scope.row.ReReadingApplyState === 3" type="warning">{{
              $fd("ReReadingApplyState", scope.row.ReReadingApplyState)
            }}</el-tag>
          </template>
        </el-table-column> -->
              <!--操作-->
              <el-table-column :label="$t('common:action:action')" min-width="140" fixed="right" v-if="
                hasPermi([
                  'trials:readTask:view',
                  'trials:readTask:reread',
                  'trials:readTask:report',
                  'trials:readTask:auditRecord',
                ])
              ">
                <template slot-scope="scope">
                  <!-- 查看 -->
                  <el-button v-hasPermi="['trials:readTask:view']" circle :title="$t('trials:readTask:button:view')"
                    icon="el-icon-view" @click="handleReadImage(scope.row)" />
                  <!-- 重阅 -->
                  <el-button v-hasPermi="['trials:readTask:reread']" circle :disabled="scope.row.TaskState > 0"
                    :title="$t('trials:readTask:button:reread')" icon="el-icon-collection"
                    @click="openApplyReReading(scope.row)" />
                  <!--肿瘤负荷报告-->
                  <el-button circle v-hasPermi="['trials:readTask:report']" icon="el-icon-document"
                    :title="$t('trials:trials-panel:hirVisit:EvaluationReport')"
                    @click="handleCommand('showReport', scope.row, 'evaluate')"
                    :disabled="scope.row.ReadingTaskState !== 2" />
                  <!--疗效评估报告-->
                  <el-button circle v-hasPermi="['trials:readTask:report']" icon="el-icon-document"
                    :title="$t('trials:trials-panel:hirVisit:TumorReport')"
                    @click="handleCommand('showReport', scope.row, 'tumor')"
                    :disabled="scope.row.ReadingTaskState !== 2 || CriterionType === 10" />
                  <!--下载影像-->
                  <el-button circle v-hasPermi="['trials:readTask:report']" icon="el-icon-download"
                    :loading="downloading" :title="$t('trials:reading:button:uploadImages')" @click="
                      handleCommand(
                        'getDownloadSubjectVisitStudyInfo',
                        [scope.row]
                      )
                      " />
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
              @pagination="getList" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-if="ApplyforReasonVisible" :title="$t('trials:readTask:dagTitle:apply')"
      :visible.sync="ApplyforReasonVisible" width="1460px" append-to-body :close-on-click-modal="false"
      custom-class="base-dialog-wrapper">
      <el-form ref="reasonForm" :rules="rules" :model="ApplyforReasonForm" class="demo-ruleForm" size="small"
        label-width="380px">
        <!-- 申请原因 -->
        <el-divider content-position="left">{{
          $t('trials:readTask:title:applyReason')
        }}</el-divider>
        <!-- 申请原因 -->
        <el-form-item :label="$t('trials:readTask:title:applyReason')" prop="Type" :rules="[
          { required: true, message: $t('common:ruleMessage:select') },
        ]">
          <el-radio-group v-model="ApplyforReasonForm.Type">
            <!-- 阅片记录错误 -->
            <el-radio :label="1">{{
              $t('trials:readTask:option:errorRecords')
            }}</el-radio>
            <!-- 其他 -->
            <el-radio :label="2">{{
              $t('trials:readTask:option:other')
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item v-if="ApplyforReasonForm.Type === 2" :label="$t('trials:readTask:title:remark')"
          prop="RequestReReadingReason">
          <el-input v-model="ApplyforReasonForm.RequestReReadingReason" type="textarea" style="width: 400px"
            :autosize="{ minRows: 2, maxRows: 4 }" :placeholder="$t('common:ruleMessage:specify')" maxlength="500"
            show-word-limit />
        </el-form-item>
        <!-- 是否复制阅片表单 -->
        <el-form-item :label="$t('trials:readTask:title:copyForm')" prop="IsCopyOrigenalForms" :rules="[
          { required: true, message: $t('common:ruleMessage:select') },
        ]">
          <el-radio-group v-model="ApplyforReasonForm.IsCopyOrigenalForms">
            <el-radio v-for="item of $d.YesOrNo" :key="`IsCopyOrigenalForms${item.raw.Id}`" :label="item.value">{{
              item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 影响的任务列表 -->
      <el-divider content-position="left">{{
        $t('trials:readTask:title:influenceList')
      }}</el-divider>
      <div style="
          padding: 10px;
          border: 1px solid #e0e0e0;
          max-height: 650px;
          overflow-y: auto;
        ">
        <el-table v-loading="loading" :data="InfluenceTaskList" stripe height="100" style="min-height: 400px">
          <!-- 任务编号 -->
          <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="TaskName" :label="$t('trials:readTask:table:TaskName')" 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 slot="footer" class="dialog-footer">
        <!-- 取消 -->
        <el-button :disabled="btnLoading" size="small" type="primary" @click="
          ApplyforReasonVisible = false
        ApplyforReasonForm = { Type: null, RequestReReadingReason: null }
          ">
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 保存 -->
        <el-button :loading="btnLoading" size="small" type="primary" @click="applyReReading">
          {{ $t('common:button:save') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 审核记录 -->
    <el-dialog v-if="auditRecordVisible" :visible.sync="auditRecordVisible" :close-on-click-modal="false"
      custom-class="base-dialog-wrapper" :title="`审核记录（${currentRow.SubjectCode} | ${currentRow.TaskName}）`"
      width="600px">
      <ChatForm :row-data="currentRow" @getList="getList" @close="auditRecordVisible = false" />
    </el-dialog>
    <el-dialog :title="$t('dialog:title:downLoadProgress')" :visible.sync="downloadVisible" width="35%"
      :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleClose">
      <div v-if="downloadType == 'downLoad' || downloadType == 'start'">
        <span style="margin-bottom: 5px;">{{ $t('dialog:sattus:downLoading') }}</span>
        <span>{{ speed }}</span>
        <el-progress :percentage="percentage * 1"></el-progress>
      </div>
      <div v-else>
        <span>{{ $t('dialog:sattus:ziping') }}</span>
      </div>
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getIRHaveReadTaskList, aIRReReading } from '@/api/trials'
import {
  applyReReading,
  getReReadingOrBackInfluenceTaskList,
  getTrialCriterionList,
} from '@/api/trials/reading'

import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import ChatForm from './components/ChatForm'
import { getToken } from '@/utils/auth'
import * as signalR from '@microsoft/signalr'
import { showReadReport, showTumorReport } from '@/api/export'
import { downLoadFile } from '@/utils/stream.js'
import { getAutoCutNextTask } from '@/api/user'
import {
  getDownloadSubjectVisitStudyInfo,
  VisitImageDownload,
  downloadImageSuccess,
} from '@/api/trials.js'
import { openWindow } from "@/utils/splitScreen";
const searchDataDefault = () => {
  return {
    SubjectCode: '',
    PatientIdStr: null,
    SubjectName: null,
    SortField: '',
    PageIndex: 1,
    PageSize: 20,
    TaskState: null,
    ReadingCategory: null,
    PIAuditState: null,
    TaskName: null,
    BeginSignDate: null,
    EndSignDate: null,
  }
}
export default {
  name: 'ReadTask',
  components: { BaseContainer, Pagination, ChatForm },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      dateValue: [],
      total: 0,
      loading: false,
      btnLoading: false,
      trialId: '',
      ApplyforReasonVisible: false,
      ApplyforReasonForm: {
        Type: null,
        RequestReReadingReason: null,
        IsCopyOrigenalForms: null,
        IsCopyFollowForms: null,
      },
      InfluenceTaskList: [],
      rules: {
        Type: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
        ],
        IsCopyOrigenalForms: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
        ],
        RequestReReadingReason: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
        ],
      },
      trialCriterionList: [],
      TrialReadingCriterionId: '0',
      openWindow: null,
      auditRecordVisible: false,
      reportFlag: {},

      // 下载相关
      downloading: false,
      downloadId: null,
      downloadVisible: false,
      downloadType: '',
      percentage: 0,
      downLoadImageCount: 0,
      speed: '0KB/s',
      multipleSelection: []
    }
  },
  watch: {
    TrialReadingCriterionId(v) {
      if (v) {
        this.getList()
      }
    },
  },
  computed: {
    CriterionType() {
      return this.trialCriterionList.find(item => item.TrialReadingCriterionId === this.TrialReadingCriterionId).CriterionType
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getTrialCriterionList()
    let connection = new signalR.HubConnectionBuilder()
      .withUrl("/DownloadHub", { accessTokenFactory: () => getToken() })
      .configureLogging(signalR.LogLevel.Information)
      .withAutomaticReconnect()
      .build()
    connection.start()
    connection.on("ReceivProgressAsync", (id, obj) => {
      console.log(obj)
      this.speed = obj.speed
      this.onUploadProgress(id, obj.sizePercent, 'downLoad')
    });
  },
  beforeDestroy() {
    if (this.openWindow) {
      this.openWindow.close()
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleClose(done) {
      this.downLoadType = 'start'
      this.percentage = 0
      this.downLoadImageCount = 0
      this.downloadVisible = false
      this.downloadId = null
      this.speed = '0KB/s'
      done()
    },
    generate() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },
    async onUploadProgress(id, num, type = 'start') {
      if (id !== this.downloadId) return false
      this.downloadType = type
      if (type === 'start') {
        this.downloadVisible = true
      }
      if (type === 'downLoad') {
        this.percentage = num
      }
      if (num >= 100) {
        this.downLoadType = 'start'
        this.percentage = 0
        this.downLoadImageCount = 0
        this.downloadVisible = false
        this.speed = '0KB/s'
      }
    },
    // 下拉菜单操作
    handleCommand(command, item, key) {
      this[command](item, key)
    },
    // 评估报告
    async showReport(item, key) {
      if (this.reportFlag[item.Id]) return
      let data = {
        VisitTaskId: item.Id,
      }
      try {
        if (!this.reportFlag.hasOwnProperty(item.Id)) {
          this.$set(this.reportFlag, item.Id, true)
        }
        if (!this.reportFlag[item.Id]) {
          this.reportFlag[item.Id] = true
        }
        let res = null;
        if (key === 'evaluate') {
          res = await showReadReport(data);
        } else {
          res = await showTumorReport(data);
        }
        if (res.IsSuccess) {
          let a = document.createElement('a')
          let href = this.OSSclientConfig.basePath + res.Result
          let fileName = res.Result.split('/')[res.Result.split('/').length - 1]
          a.download = fileName
          a.href = href
          a.click()
          URL.revokeObjectURL(href)
          this.$nextTick(() => {
            a = null
            href = null
          })
        }
        this.reportFlag[item.Id] = false
      } catch (err) {
        this.reportFlag[item.Id] = false
        console.log(err)
      }
    },
    // 获取下载文件信息
    async getDownloadSubjectVisitStudyInfo(arr) {
      if (this.downloading) return
      try {
        let data = {
          // SubjectVisitId: row.SourceSubjectVisitId,
          SubjectVisitIdList: arr.map(item => item.SourceSubjectVisitId),
          TrialId: this.$route.query.trialId,
        }
        this.downloadId = this.generate()
        data.CurrentNoticeId = this.downloadId
        this.onUploadProgress(this.downloadId)
        // this.downloading = true
        await VisitImageDownload(data)
        // this.downloading = false
        // if (res.IsSuccess) {
        //   this.downloadId = res.OtherInfo
        //   this.downloadImage(res.Result)
        // }
      } catch (err) {
        this.downloading = false
        console.log(err)
      }
    },
    // 打包下载
    async downloadImage(data) {
      try {
        let { files, name } = this.formatDownloadFile(data)
        let res = await downLoadFile(files, name, 'zip')

        if (res && this.downloadId) {
          this.downloadImageSuccess()
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化下载文件路径
    formatDownloadFile(data) {
      let files = [],
        name = `${data.SubjectCode}_${data.VisitName}_ImageStudy.zip`
      if (Array.isArray(data.StudyList) && data.StudyList.length > 0) {
        data.StudyList.forEach((study) => {
          if (Array.isArray(study.SeriesList) && study.SeriesList.length > 0) {
            study.SeriesList.forEach((series) => {
              if (
                Array.isArray(series.InstanceList) &&
                series.InstanceList.length > 0
              ) {
                series.InstanceList.forEach((instance) => {
                  let fileName = instance.Path.split('/').pop()
                  let obj = {
                    name: `${data.SubjectCode}_${data.VisitName}/${study.StudyCode
                      }_${study.StudyTime.split(' ')[0]}_${series.Modality
                      }/${fileName}`,
                    url: this.OSSclientConfig.basePath + instance.Path,
                  }
                  files.push(obj)
                })
              }
            })
          }
        })
      }

      return { files, name }
    },
    // 影像下载成功确认
    async downloadImageSuccess() {
      try {
        let params = {
          TrialImageDownloadId: this.downloadId,
        }
        await downloadImageSuccess(params)
      } catch (err) {
        console.log(err)
      }
    },
    getTrialCriterionList() {
      getTrialCriterionList(this.trialId)
        .then((res) => {
          this.trialCriterionList = res.Result
          this.TrialReadingCriterionId =
            this.trialCriterionList[0].TrialReadingCriterionId
        })
        .catch(() => { })
    },
    // 重阅历史
    reReadingHistory(row) {
      this.$router.push({
        path: `/trials/trials-panel/reading/rereadTask?trialId=${this.$route.query.trialId}&trialCode=${this.$route.query.trialCode}&researchProgramNo=${this.$route.query.researchProgramNo}&SiteId=${row.SiteId}&SubjectCode=${row.SubjectCode}&TaskName=${row.TaskName}`,
      })
    },
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      this.searchData.TrialReadingCriterionId = this.TrialReadingCriterionId
      if (this.dateValue && this.dateValue[0] && this.dateValue[1]) {
        this.searchData.BeginSignDate = this.$moment(this.dateValue[0]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        this.searchData.EndSignDate = this.$moment(this.dateValue[1]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      } else {
        this.searchData.BeginSignDate = null
        this.searchData.EndSignDate = null
      }
      getIRHaveReadTaskList(this.searchData)
        .then((res) => {
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    handleReset() {
      this.searchData = searchDataDefault()
      this.dateValue = []
      this.getList()
    },
    async handleReadImage(row) {
      if (this.openWindow) {
        this.openWindow.close()
      }
      // var token = getToken()
      // var routeData = ''
      // routeData = this.$router.resolve({
      //   path: `/readingPage?subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&trialId=${this.trialId}&visitTaskId=${row.Id}&TokenKey=${token}`
      // })
      window.localStorage.setItem(
        'TrialReadingCriterionId',
        this.TrialReadingCriterionId
      )
      var token = getToken()
      var path = ''
      if (row.ReadingTool === 0) {
        path = `/readingDicoms?TrialReadingCriterionId=${row.TrialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&visitTaskId=${row.Id}&isReadingTaskViewInOrder=${row.IsReadingTaskViewInOrder}&criterionType=${row.CriterionType}&readingTool=${row.ReadingTool}&TokenKey=${token}`
      } else {
        path = `/noneDicomReading?TrialReadingCriterionId=${row.TrialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&visitTaskId=${row.Id}&isReadingTaskViewInOrder=${row.IsReadingTaskViewInOrder}&criterionType=${row.CriterionType}&readingTool=${row.ReadingTool}&TokenKey=${token}`
      }
      var routeData = this.$router.resolve({ path })
      const res = await getAutoCutNextTask()
      let IsDoubleScreen = false
      if (res.IsSuccess) {
        IsDoubleScreen = res.Result.IsDoubleScreen
      }
      if (IsDoubleScreen) {
        this.openWindow = await openWindow(routeData.href)
        if (!this.openWindow) {
          let html = `<div><span>${this.$t("trials:reading:tip:MultiScreen2")}</span><a style="color:#409EFF"
              href="/screen.pdf"
              target="blank">${this.$t("trials:reading:tip:openFile")}</a></div>`
          let confirm = await this.$confirm(html, '', { dangerouslyUseHTMLString: true })
          if (!confirm) return false
          this.openWindow = await openWindow(routeData.href, '', true)
        }
      } else {
        this.openWindow = window.open(routeData.href, "_blank");
      }
    },
    async openApplyReReading(row) {
      try {
        let confirm = await this.$confirm(
          this.$t('trials:readTask:message:msg2'),
          {
            type: 'warning',
            distinguishCancelAndClose: true,
          }
        )
        if (!confirm) return
        let params = {
          TrialId: row.TrialId,
          TrialReadingCriterionId: row.TrialReadingCriterionId,
          VisitTaskId: row.Id,
        }
        this.loading = true
        let res = await aIRReReading(params)
        this.loading = false
        if (res.IsSuccess) {
          this.getList()
          this.$message({
            message: this.$t('trials:readTask:message:msg3'),
            type: 'success',
          })
        }
      } catch (err) {
        console.log(err)
        this.loading = false
      }
    },
    // 申请重阅
    applyReReading() {
      this.$refs.reasonForm.validate((valid) => {
        if (!valid) return
        this.loading = true
        this.btnLoading = true
        var params = {
          TaskIdList: [this.rowData.Id],
          TrialId: this.$route.query.trialId,
          IsCopyOrigenalForms: this.ApplyforReasonForm.IsCopyOrigenalForms,
          IsCopyFollowForms: this.ApplyforReasonForm.IsCopyFollowForms,
          RequestReReadingType: 1,
          RequestReReadingReason:
            this.ApplyforReasonForm.Type === 2
              ? this.ApplyforReasonForm.RequestReReadingReason
              : this.$t('trials:readTask:option:errorRecords'), // '阅片记录错误'
        }
        applyReReading(params)
          .then((res) => {
            this.loading = false
            this.btnLoading = false
            this.$message.success(this.$t('trials:readTask:message:msg1')) // '申请重阅成功'
            this.getList()
            this.ApplyforReasonVisible = false
          })
          .catch(() => {
            this.loading = false
            this.btnLoading = false
          })
      })
    },
    // 批量重阅
    handleReread() {
      this.$confirm(this.$t('trials:readTask:message:msg2'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.loading = true
          var params = {
            trialId: this.trialId,
            trialReadingCriterionId: this.TrialReadingCriterionId,
          }
          aIRReReading(params)
            .then((res) => {
              this.$message({
                message: this.$t('trials:readTask:message:msg3'),
                type: 'success',
              })
              this.getList()
            })
            .catch(() => {
              this.loading = false
            })
          console.log(params)
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleAuditRecords(row) {
      this.currentRow = { ...row }
      this.auditRecordVisible = true
    },
    // 排序
    handleSortChange(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.searchData.PageIndex = 1
      this.getList()
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-progress {
  display: flex;
  align-items: center;
}
</style>
