<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <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 CriterionTypeList"
              :key="item.TrialReadingCriterionId"
              :label="item.TrialReadingCriterionName"
              :value="item.TrialReadingCriterionId"
            />
          </el-select>
        </el-form-item>
        <!-- 受试者编号 -->
        <el-form-item :label="$t('trials:uploadMonitor:table:subjectId')">
          <el-input v-model="searchData.SubjectCode" style="width: 140px" />
        </el-form-item>
        <!-- 患者编号 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
          <el-input v-model="searchData.PatientIdStr" style="width: 140px" />
        </el-form-item>
        <!-- 患者姓名 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:patientName')">
          <el-input v-model="searchData.SubjectName" style="width: 140px" />
        </el-form-item>
        <!-- 任务创建时间 -->
        <el-form-item :label="$t('trials:reviewTrack:table:createTime')">
          <el-date-picker
            v-model="dateValue2"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <!-- 任务状态 -->
        <el-form-item :label="$t('trials:readTask:table:taskState')">
          <el-select
            v-model="searchData.taskState"
            clearable
            filterable
            style="width: 150px"
          >
            <el-option
              v-for="item of $d.TaskState"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 阅片状态 -->
        <el-form-item :label="$t('trials:readTask:table:readingTaskState')">
          <el-select
            v-model="searchData.ReadingTaskState"
            clearable
            filterable
            style="width: 150px"
          >
            <el-option
              v-for="item of $d.ReadModuleEnum"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 阅片完成时间 -->
        <el-form-item :label="$t('trials:reviewTrack:table:signTime')">
          <el-date-picker
            v-model="dateValue"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </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-form-item>
      </el-form>
    </template>

    <!-- 阅片管理列表 -->
    <template slot="main-container">
      <el-table
        v-loading="loading"
        v-adaptive="{ bottomOffset: 60 }"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
        ref="redManagenentTable"
        :default-sort="{ prop: 'CreateTime', order: 'descending' }"
      >
        <el-table-column type="index" width="40" />
        <!-- 受试者编号 -->
        <el-table-column
          prop="SubjectCode"
          :label="$t('trials:uploadMonitor:table:subjectId')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 患者编号 -->
        <el-table-column
          prop="StudyCode"
          :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"
          :label="$t('trials:researchStaff:table:Name')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 任务名称 -->
        <el-table-column
          prop="TaskBlindName"
          :label="$t('trials:auditRecord:table:taskName')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 任务创建时间 -->
        <el-table-column
          prop="CreateTime"
          :label="$t('trials:reviewTrack:table:createTime')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 任务状态 -->
        <el-table-column
          prop="TaskState"
          :label="$t('trials:readTask:table:taskState')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <span>{{ $fd("TaskState", scope.row.TaskState) }}</span>
          </template>
        </el-table-column>
        <!-- 阅片人 -->
        <el-table-column
          prop="DoctorUser"
          :label="$t('trials:reviewAssign:searchForm:reader')"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ (scope.row.DoctorUser || {}).UserName }}</span>
          </template>
        </el-table-column>
        <!-- 阅片状态 -->
        <el-table-column
          prop="ReadingTaskState"
          :label="$t('trials:reviewTrack:table:readingStatus')"
          width="160"
          sortable="custom"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.ReadingTaskState === 2 ? 'primary' : 'danger'"
              >{{ $fd("ReadingTaskState", scope.row.ReadingTaskState) }}</el-tag
            >
          </template>
        </el-table-column>
        <!-- 阅片完成时间 -->
        <el-table-column
          prop="SignTime"
          :label="$t('trials:reviewTrack:table:signTime')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 阅片标准 -->
        <el-table-column
          prop="TrialReadingCriterionName"
          :label="$t('trials:processCfg:form:criterion')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 建议完成时间 -->
        <!-- <el-table-column
          prop="StudyCode"
          :label="$t('trials:consistencyAnalysis:table:suggesteFinishedTime')"
          show-overflow-tooltip
          sortable="custom"
        /> -->
        <!--操作-->
        <el-table-column
          :label="$t('common:action:action')"
          min-width="100"
          fixed="right"
        >
          <template slot-scope="scope">
            <!--阅片结果-->
            <el-button
              circle
              icon="el-icon-view"
              :title="$t('trials:auditRecord:table:readingResult')"
              @click="readResult(scope.row)"
              :disabled="scope.row.ReadingTaskState !== 2"
            />
            <el-dropdown
              style="margin-left: 10px"
              @command="(command) => handleCommand(command, scope.row)"
            >
              <el-button
                class="el-dropdown-link"
                circle
                icon="el-icon-more"
                :title="$t('common:action:action')"
              >
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <!--评估报告disabled-->
                <el-dropdown-item command="showReport">{{
                  $t("trials:trials-panel:hirVisit:EvaluationReport")
                }}</el-dropdown-item>
                <!--数据导出-->
                <el-dropdown-item command="downloadImage">{{
                  $t("trials:reading:button:uploadImages")
                }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        class="page"
        :total="total"
        :page.sync="searchData.PageIndex"
        :limit.sync="searchData.PageSize"
        @pagination="getList"
      />
    </template>
  </BaseContainer>
</template>
<script>
import BaseContainer from "@/components/BaseContainer";
import Pagination from "@/components/Pagination";
import { getPatientVisitTaskList } from "@/api/readManagenent.js";
import { getToken } from "@/utils/auth";
// import { getSystemConfirmedCreiterionList } from "@/api/trials";
import { getTrialCriterionList } from "@/api/trials/reading";
import { showReadReport } from "@/api/export";
import { downloadImage } from "@/utils/uploadZip.js";
const defaultSearchData = () => {
  return {
    SubjectCode: null,
    ReadingCategory: 1,
    ReadingTaskState: null,
    TaskState: null,
    BeginSignTime: null,
    EndSignTime: null,
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: "CreateTime",
    TrialReadingCriterionId: null,
    TaskState: null,
    SubjectShortName: null,
    PatientName: null,
    PatientIdStr: null,
    PatientSex: null,
    BeginTaskCreateTime: null,
    EndTaskCreateTime: null,
    SubjectName: null,
  };
};
export default {
  name: "readManagenent",
  components: { BaseContainer, Pagination },
  data() {
    return {
      // 查询
      searchData: defaultSearchData(),
      dateValue: [],
      dateValue2: [],
      CriterionTypeList: [],
      // 列表
      list: [],
      loading: false,
      total: 0,
      // 修改检查
      reportFlag: {},
    };
  },
  created() {
    this.getList();
    this.getTrialConfirmedCreiterionList();
  },
  methods: {
    // 下拉菜单操作
    handleCommand(command, item) {
      this[command](item);
    },
    // 评估报告
    async showReport(item) {
      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 = await showReadReport(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 getTrialConfirmedCreiterionList() {
      try {
        let trialId = this.$route.query.trialId;
        let res = await getTrialCriterionList(trialId);
        if (res.IsSuccess) {
          this.CriterionTypeList = res.Result;
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 查询
    handleSearch() {
      this.getList();
    },
    // 重置
    handleReset() {
      this.reset();
      this.getList();
    },
    // 初始化
    reset() {
      this.searchData = defaultSearchData();
      this.dateValue = [];
      this.dateValue2 = [];
      this.$refs.redManagenentTable.clearSort();
    },
    // 排序
    handleSortByColumn(sort) {
      this.searchData.SortField = sort.prop;
      if (sort.order === "ascending") this.searchData.Asc = true;
      if (sort.order === "descending") this.searchData.Asc = false;
      if (!sort.order) this.searchData.SortField = null;
      this.getList();
    },
    // 获取列表
    async getList() {
      try {
        let data = {};
        Object.keys(this.searchData).forEach((key) => {
          data[key] = this.searchData[key];
        });
        data.TrialId = this.$route.query.trialId;
        if (this.dateValue[0] && this.dateValue[1]) {
          data.earliestStudyTime = this.dateValue[0].toISOString();
          data.latestStudyTime = this.dateValue[1].toISOString();
        } else {
          data.EarliestStudyTime = null;
          data.LatestStudyTime = null;
        }
        if (this.dateValue2[0] && this.dateValue2[1]) {
          data.BeginTaskCreateTime = this.dateValue2[0].toISOString();
          data.EndTaskCreateTime = this.dateValue2[1].toISOString();
        } else {
          data.BeginTaskCreateTime = null;
          data.EndTaskCreateTime = null;
        }
        this.loading = true;
        let res = await getPatientVisitTaskList(data);
        this.loading = false;
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData;
          this.total = res.Result.TotalCount;
        }
      } catch (err) {
        this.loading = false;
        console.log(err);
      }
    },
    // 下载影像
    async downloadImage(item) {
      downloadImage(item.SubjectId, item.SourceSubjectVisitId);
    },
    // 阅片结果
    readResult(row) {
      if (this.openWindow) {
        this.openWindow.close();
      }
      var token = getToken();
      var path;
      // if (row.ReadingTool === 0) {
      path = `/readingDicoms?TrialReadingCriterionId=${
        row.TrialReadingCriterionId
      }&trialId=${this.$route.query.trialId}&subjectCode=${
        row.SubjectCode
      }&subjectId=${row.SubjectId}&visitTaskId=${
        row.Id
      }&isReadingTaskViewInOrder=${true}&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}`;
      // }
      // const routeData = this.$router.resolve({
      //   path: `/readingPage?subjectId=${row.SubjectId}&trialId=${row.TrialId}&visitTaskId=${row.Id}&TokenKey=${token}`
      // })
      this.openWindow = window.open(path, "_blank");
    },
  },
};
</script>
