<template>
  <BaseContainer v-loading="loading" class="reading-task">
    <el-tabs v-if="TrialReadingCriterionId" v-model="TrialReadingCriterionId" type="border-card">
      <el-tab-pane v-for="item of trialCriterionList" :key="item.TrialReadingCriterionId"
        :label="item.TrialReadingCriterionName" :name="item.TrialReadingCriterionId">
        <div v-if="
          (isReadingTaskViewInOrder === 1 ||
            isReadingTaskViewInOrder === 2) &&
          TrialReadingCriterionId === item.TrialReadingCriterionId
        ">
          <div slot="search-container">
            <el-form :inline="true" @submit.native.prevent="">
              <!-- 受试者编号 -->
              <el-form-item :label="$t('trials:pendingReadingTasks:table:subjectCode')">
                <el-input v-model="searchData.SubjectCode" style="width: 130px" clearable />
              </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="() => TargetSection_visible = true"
                  v-if="item.CriterionType === 19 || item.CriterionType === 20">
                  {{ $t('trials:pendingReadingTasks:button:TargetSection') }}
                </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">
              <el-table-column type="index" width="40" align="left" />
              <el-table-column prop="IsUrgent" :label="$t('trials:consistencyCheck:table:isUrgent')"
                show-overflow-tooltip min-width="100">
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark" :content="$t('trials:pendingReadingTasks:table:feedbackmsg')"
                    placement="bottom" v-if="scope.row.IsExistUnprocessedFeedback">
                    <i v-if="scope.row.IsExistUnprocessedFeedback" class="el-icon-warning"
                      style="color: #f44336; font-size: 16px" />
                  </el-tooltip>
                  <el-tag :type="scope.row.UrgentColor === 1
                    ? 'danger'
                    : scope.row.UrgentColor === 2
                      ? 'warning'
                      : 'primary'
                    ">{{ $fd('YesOrNo', scope.row.IsUrgent) }}</el-tag>
                </template>
              </el-table-column>
              <!-- 受试者编号 -->
              <el-table-column prop="SubjectCode" min-width="100"
                :label="$t('trials:pendingReadingTasks:table:subjectCode')" show-overflow-tooltip sortable="custom" />
              <!-- 剩余阅片量 -->
              <el-table-column prop="UnReadCanReadTaskCount" min-width="100" :label="$t('trials:pendingReadingTasks:table:remainingReadingVolume')
                " show-overflow-tooltip sortable="custom" />
              <el-table-column prop="UrgentCount" :label="$t('trials:sysDocBeSigned:table:UrgentCount')"
                show-overflow-tooltip min-width="100" sortable="custom">
                <template slot-scope="scope">
                  <span :style="{
                    color:
                      scope.row.UrgentColor === 1
                        ? '#F56C6C'
                        : scope.row.UrgentColor === 2
                          ? '#E6A23C'
                          : '#409EFF',
                  }">{{ scope.row.UrgentCount }}</span>
                </template>
              </el-table-column>
              <!-- 建议完成时间 -->
              <el-table-column prop="SuggesteFinishedTime" min-width="100" :label="$t('trials:pendingReadingTasks:table:suggestedCompletionTime')
                " show-overflow-tooltip sortable="custom">
                <template slot-scope="scope">
                  {{ scope.row.SuggesteFinishedTime.split(':')[0] + ':00:00' }}
                </template>
              </el-table-column>
              <el-table-column :label="$t('common:action:action')" width="250" >
                <template slot-scope="scope">
                  <!-- 阅片 -->
                  <el-button :disabled="scope.row.ExistReadingApply" circle :title="scope.row.ExistReadingApply
                    ? $t(
                      'trials:pendingReadingTasks:button:ExistReadingApply'
                    )
                    : $t('trials:pendingReadingTasks:button:review')
                    " icon="el-icon-edit-outline" @click="handleReadImage(scope.row)" />
                  <!-- 上传 -->
                  <!-- <el-button v-if="
                    item.ImageUploadEnum > 0 &&
                    item.IsReadingTaskViewInOrder > 1 &&
                    !scope.row.IsSubjectJudge
                  " v-hasPermi="['role:ir']" circle icon="el-icon-upload2"
                    :title="$t('trials:pendingReadingTasks:button:upload')"
                    @click="openUploadImage(scope.row, item, 'upload')" /> -->
                  <!-- 下载 -->
                  <!-- <el-button v-if="
                    item.ImageDownloadEnum > 0 &&
                    item.IsReadingTaskViewInOrder > 1 &&
                    !scope.row.IsSubjectJudge
                  " v-hasPermi="['role:ir']" circle icon="el-icon-download"
                    :title="$t('trials:pendingReadingTasks:button:download')"
                    @click="openUploadImage(scope.row, item, 'download')" /> -->
                </template>
              </el-table-column>
            </el-table>
            <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
              @pagination="getList" />
          </div>
        </div>
        <div v-else-if="
          isReadingTaskViewInOrder === 0 &&
          TrialReadingCriterionId === item.TrialReadingCriterionId
        ">
          <el-descriptions :column="2" border style="width: 800px">
            <!-- 剩余任务量 -->
            <el-descriptions-item :label="$t('trials:pendingReadingTasks:table:remainingTaskVolume')
              " :label-style="{ width: '200px' }">
              <el-tag size="small" type="danger">{{
                randomReadInfo.UnReadTaskCount
              }}</el-tag>
            </el-descriptions-item>
            <!-- 剩余裁判量 -->
            <el-descriptions-item :label="$t('trials:pendingReadingTasks:table:amountOfJudgesRemaining')
              " :label-style="{ width: '200px' }">
              <el-tag size="small" type="danger">{{
                randomReadInfo.UnReadJudgeTaskCount
              }}</el-tag>
            </el-descriptions-item>
            <!-- 已完成任务量 -->
            <el-descriptions-item :label="$t('trials:pendingReadingTasks:table:amountOfCompletedTasks')
              " :label-style="{ width: '200px' }">
              <el-tag size="small">{{ randomReadInfo.FinishTaskCount }}</el-tag>
            </el-descriptions-item>
            <!-- 已完成裁判量 -->
            <el-descriptions-item :label="$t('trials:pendingReadingTasks:table:numberOfJudgesCompleted')
              " :label-style="{ width: '200px' }">
              <el-tag size="small">{{
                randomReadInfo.FinishJudgeTaskCount
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <!-- 开始随机阅片 -->
              <el-button type="primary" size="small" :disabled="randomReadInfo.UnReadTaskCount +
                randomReadInfo.UnReadJudgeTaskCount ===
                0
                " @click="handleOutOfOrderReading">
                {{ $t('trials:pendingReadingTasks:button:beginRandomReview') }}
              </el-button>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- <upload-image
      v-if="uploadImageVisible"
      :visible.sync="uploadImageVisible"
      :subject-id="uploadSubjectId"
      :criterion="uploadTrialCriterion"
      :status="uploadStatus"
      @getList="getList"
    /> -->
    <upload-dicom-and-nonedicom v-if="uploadImageVisible" :SubjectId="uploadSubjectId" :SubjectCode="uploadSubjectCode"
      :Criterion="uploadTrialCriterion" :isReadingTaskViewInOrder="isReadingTaskViewInOrder"
      :visible.sync="uploadImageVisible" />
    <download-dicom-and-nonedicom v-if="downloadImageVisible" :SubjectId="uploadSubjectId"
      :SubjectCode="uploadSubjectCode" :Criterion="uploadTrialCriterion" :visible.sync="downloadImageVisible" />
    <el-dialog :title="$t('trials:pendingReadingTasks:button:TargetSection')" :visible.sync="TargetSection_visible"
      :fullscreen="true">
      <TargetSection v-if="TargetSection_visible" :TrialReadingCriterionId="TrialReadingCriterionId"
        :trialCriterionList="trialCriterionList" />
    </el-dialog>

  </BaseContainer>
</template>
<script>
import { getIRUnReadSubjectTaskList, verifyReadingRestTime } from '@/api/trials'
import { getTrialCriterionList } from '@/api/trials/reading'
import { clearSkipReadingCache } from '@/api/reading'
import BaseContainer from '@/components/BaseContainer'
import uploadDicomAndNonedicom from '@/components/uploadDicomAndNonedicom'
import downloadDicomAndNonedicom from '@/components/downloadDicomAndNonedicom'
import Pagination from '@/components/Pagination'
import { getToken } from '@/utils/auth'
import { getAutoCutNextTask } from '@/api/user'
import { openWindow } from "@/utils/splitScreen";
import TargetSection from "./components/TargetSection"
const searchDataDefault = () => {
  return {
    SubjectCode: '',
    PageIndex: 1,
    PageSize: 20,
  }
}
export default {
  name: 'ReadingTaskList',
  components: {
    BaseContainer,
    Pagination,
    'upload-dicom-and-nonedicom': uploadDicomAndNonedicom,
    'download-dicom-and-nonedicom': downloadDicomAndNonedicom,
    TargetSection
  },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      trialId: '',
      isReadingTaskViewInOrder: null,
      randomReadInfo: {},
      isRender: false,
      trialCriterionList: [],
      TrialReadingCriterionId: '',
      isTableShow: true,
      readingTool: null,
      criterionType: null,
      openWindow: null,

      // 上传
      downloadImageVisible: false,
      uploadImageVisible: false,
      uploadSubjectId: null,
      uploadSubjectCode: null,
      uploadTrialCriterion: {},
      uploadStatus: 'upload',

      TargetSection_visible: false
    }
  },
  watch: {
    TrialReadingCriterionId(v) {
      if (v) {
        this.searchData = searchDataDefault()
        this.getList()
      }
    },
    TargetSection_visible(v) {
      if (!v) {
        this.getList()
      }
    }
  },
  mounted() {
    window.addEventListener('message', this.receiveMsg)
    this.trialId = this.$route.query.trialId
    this.getTrialCriterionList()
  },
  beforeDestroy() {
    window.removeEventListener('message', this.receiveMsg)
    if (this.openWindow) {
      this.openWindow.close()
    }
  },
  methods: {
    // 打开上传下载弹框
    openUploadImage(item, trialCriterion, status) {
      this.uploadSubjectCode = item.SubjectCode
      this.uploadSubjectId = item.SubjectId
      this.uploadTrialCriterion = trialCriterion
      this.uploadStatus = status
      this[`${status}ImageVisible`] = true
    },
    async getTrialCriterionList() {
      try {
        const res = await getTrialCriterionList(this.trialId)
        if (res.IsSuccess) {
          this.trialCriterionList = res.Result
          this.TrialReadingCriterionId =
            this.trialCriterionList[0].TrialReadingCriterionId
        }
      } catch (e) {
        console.log(e)
      }
    },
    async getList() {
      try {
        this.loading = true
        this.searchData.TrialId = this.trialId
        this.searchData.TrialReadingCriterionId = this.TrialReadingCriterionId
        this.isRender = false
        const res = await getIRUnReadSubjectTaskList(this.searchData)
        if (res.IsSuccess) {
          this.isReadingTaskViewInOrder = res.OtherInfo.IsReadingTaskViewInOrder
          this.readingTool = res.OtherInfo.ReadingTool
          this.criterionType = res.OtherInfo.CriterionType
          if (res.OtherInfo.IsReadingTaskViewInOrder) {
            this.list = res.Result.CurrentPageData
            this.total = res.Result.TotalCount
          } else {
            this.randomReadInfo = res.OtherInfo.RandomReadInfo
          }
          this.isRender = true
          this.loading = false
        }
      } catch (e) {
        this.isRender = true
        this.loading = false
      }
    },
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },
    async handleReadImage(row) {
      if (this.openWindow) {
        this.openWindow.close()
      }
      try {
        this.loading = true
        await clearSkipReadingCache()
        await verifyReadingRestTime()
        this.loading = false
        window.localStorage.setItem(
          'TrialReadingCriterionId',
          this.TrialReadingCriterionId
        )
        var token = getToken()
        var path = ''
        if (this.readingTool === 0 || this.readingTool === 2 || this.readingTool === 3) {
          path = `/readingDicoms?TrialReadingCriterionId=${this.TrialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&isReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}&criterionType=${this.criterionType}&readingTool=${this.readingTool}&TokenKey=${token}`
        } else {
          path = `/noneDicomReading?TrialReadingCriterionId=${this.TrialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&isReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}&criterionType=${this.criterionType}&readingTool=${this.readingTool}&TokenKey=${token}`
        }
        var routeData = this.$router.resolve({ path })
        let imageToolType = this.readingTool === 1 ? 2 : 1
        const res = await getAutoCutNextTask({imageToolType})
        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");
        }
        // this.openWindow = window.open(routeData.href, '_blank')
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    async handleOutOfOrderReading() {
      if (this.openWindow) {
        this.openWindow.close()
      }
      try {
        this.loading = true
        await clearSkipReadingCache()
        await verifyReadingRestTime()
        this.loading = false
        window.localStorage.setItem(
          'TrialReadingCriterionId',
          this.TrialReadingCriterionId
        )
        var token = getToken()
        var path = ''
        if (this.readingTool === 0 || this.readingTool === 2|| this.readingTool === 3) {
          path = `/readingDicoms?TrialReadingCriterionId=${this.TrialReadingCriterionId}&trialId=${this.trialId}&isReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}&criterionType=${this.criterionType}&readingTool=${this.readingTool}&TokenKey=${token}`
        } else {
          path = `/noneDicomReading?TrialReadingCriterionId=${this.TrialReadingCriterionId}&trialId=${this.trialId}&isReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}&criterionType=${this.criterionType}&readingTool=${this.readingTool}&TokenKey=${token}`
        }
        var routeData = this.$router.resolve({ path })
        this.openWindow = window.open(routeData.href, '_blank')
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    receiveMsg(event) {
      if (event.data === 'refreshTaskList') {
        this.getList()
      }
    },
    // 排序
    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>
.reading-task {
  height: 100%;
  background-color: #fff;

  ::v-deep .search {
    padding: 0px !important;
  }
}
</style>
