<template>
  <BaseContainer v-loading="loading" style="background-color: #fff">
    <div slot="search-container">
      <el-form :inline="true">
        <!-- 受试者编号 -->
        <el-form-item :label="$t('trials:reviewTrack:table:subjectCode')">
          <el-input v-model="searchData.SubjectCode" style="width: 150px" clearable />
        </el-form-item>
        <!-- 患者编号 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
          <el-input v-model="searchData.PatientIdStr" style="width: 150px" clearable />
        </el-form-item>
        <!-- 患者姓名 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:patientName')">
          <el-input v-model="searchData.SubjectName" style="width: 150px" 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-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="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="SubjectName" min-width="100" :label="$t('trials:uploadDicomList:table:patientName')"
          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="SuggesteFinishedTime" min-width="100" :label="$t('trials:pendingReadingTasks:table:suggestedCompletionTime')
          " show-overflow-tooltip sortable="custom">
          <template slot-scope="scope">
            {{
              scope.row.SuggesteFinishedTime
                ? scope.row.SuggesteFinishedTime.split(":")[0] + ":00:00"
                : ""
            }}
          </template>
        </el-table-column>
        <!--操作-->
        <el-table-column :label="$t('common:action:action')" width="250" fixed="right">
          <template slot-scope="scope">
            <!-- 阅片 -->
            <el-button :disabled="scope.row.ExistReadingApply ||
              (scope.row.ClaimUserId && scope.row.ClaimUserId !== userId)
              " 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 :disabled="!scope.row.ClaimUserId ||
              (scope.row.ClaimUserId && scope.row.ClaimUserId !== userId)
              " circle :title="$t('trials:pendingReadingTasks:button:release')" icon="el-icon-s-release"
              @click="handleReleaseTasks(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
        @pagination="getList" />
    </div>
  </BaseContainer>
</template>
<script>
import {
  getIRUnReadSubjectTaskList,
  verifyReadingRestTime,
} from "@/api/trials";
import { claimOrCancelSubject, clearSkipReadingCache } from "@/api/reading";
import BaseContainer from "@/components/BaseContainer";
import { getAutoCutNextTask } from '@/api/user'
import Pagination from "@/components/Pagination";
import { getToken } from "@/utils/auth";
import { openWindow } from "@/utils/splitScreen";
const searchDataDefault = () => {
  return {
    SubjectCode: "",
    PatientIdStr: null,
    SubjectName: null,
    PageIndex: 1,
    PageSize: 20,
  };
};
export default {
  name: "ReadingTaskList",
  props: {
    trialCriterionInfo: {
      type: Object,
      required: true,
    },
  },
  components: { BaseContainer, Pagination },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      trialId: "",
      isReadingTaskViewInOrder: null,
      randomReadInfo: {},
      isRender: false,
      isTableShow: true,
      readingTool: null,
      criterionType: null,
      openWindow: null,
      userId: zzSessionStorage.getItem("userId"),
    };
  },
  mounted() {
    window.addEventListener("message", this.receiveMsg);
    this.trialId = this.$route.query.trialId;
    this.getList();
  },
  beforeDestroy() {
    window.removeEventListener("message", this.receiveMsg);
    if (this.openWindow) {
      this.openWindow.close();
    }
  },
  methods: {
    getList() {
      this.loading = true;
      this.searchData.TrialId = this.trialId;
      this.searchData.TrialReadingCriterionId =
        this.trialCriterionInfo.TrialReadingCriterionId;
      this.isRender = false;
      getIRUnReadSubjectTaskList(this.searchData)
        .then((res) => {
          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(() => {
          this.isRender = true;
          this.loading = false;
        });
    },
    // 释放
    handleReleaseTasks(row) {
      this.loading = true;
      var params = {
        isInOrder: true,
        subejctId: row.SubjectId,
        isClaim: false,
        trialReadingCriterionId:
          this.trialCriterionInfo.TrialReadingCriterionId,
      };
      claimOrCancelSubject(params)
        .then((res) => {
          // '释放成功!'
          this.$message.success(
            this.$t("trials:pendingReadingTasks:message:released")
          );
          this.loading = false;
          this.getList();
        })
        .catch(() => {
          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();
      }
      this.loading = true;
      await clearSkipReadingCache()
      verifyReadingRestTime()
        .then(async (_) => {
          this.loading = false;

          window.localStorage.setItem(
            "TrialReadingCriterionId",
            this.trialCriterionInfo.TrialReadingCriterionId
          );
          var token = getToken();
          var path = "";
          var criterionName = this.trialCriterionInfo.TrialReadingCriterionName;
          if (this.readingTool === 0) {
            path = `/readingDicoms?TrialReadingCriterionId=${this.trialCriterionInfo.TrialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${escape(row.SubjectCode)}&subjectId=${row.SubjectId}&isReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}&criterionType=${this.criterionType}&criterionName=${criterionName}&readingTool=${this.readingTool}&TokenKey=${token}`;
          } else {
            path = `/noneDicomReading?TrialReadingCriterionId=${this.trialCriterionInfo.TrialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${escape(row.SubjectCode)}&subjectId=${row.SubjectId}&isReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}&criterionType=${this.criterionType}&criterionName=${criterionName}&readingTool=${this.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");
          }
          // if (this.openWindow) {
          //   this.$setOpenWindow(this.openWindow);
          // }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    async handleOutOfOrderReading() {
      if (this.openWindow) {
        this.openWindow.close();
      }
      this.loading = true;
      await clearSkipReadingCache()
      verifyReadingRestTime()
        .then((_) => {
          this.loading = false;
          window.localStorage.setItem(
            "TrialReadingCriterionId",
            this.TrialReadingCriterionId
          );
          var token = getToken();
          var path = "";
          if (this.readingTool === 0) {
            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(() => {
          this.loading = false;
        });
    },
    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>
