<template>
  <BaseContainer>
    <el-tabs 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="TrialReadingCriterionId === item.TrialReadingCriterionId">
          <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: 100px"
                />
              </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.PatientName"
                  style="width: 140px"
                />
              </el-form-item>
              <!-- 任务名称 -->
              <el-form-item
                style="margin-bottom: 10px"
                :label="$t('trials:reviewTrack:table:taskName')"
              >
                <el-input v-model="searchData.TaskName" style="width: 140px" />
              </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
                style="margin-bottom: 10px"
                :label="$t('trials:reviewTrack:table:reader')"
              >
                <el-select
                  v-model="searchData.DoctorUserId"
                  clearable
                  style="width: 120px"
                >
                  <el-option
                    v-for="item of DoctorUserList"
                    :key="'DoctorUserId' + item.DoctorUserId"
                    :value="item.DoctorUserId"
                    :label="`${item.UserName}(${item.FullName})`"
                  />
                </el-select>
              </el-form-item>
              <!-- 审核结果 -->
              <el-form-item
                style="margin-bottom: 10px"
                :label="$t('trials:auditRecord:table:auditResult')"
              >
                <el-select
                  v-model="searchData.PIAuditState"
                  clearable
                  style="width: 120px"
                >
                  <el-option
                    v-for="item of $d.PIAuditState"
                    :key="'PIAuditState' + item.label"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              <!-- 是否入组 -->
              <el-form-item
                style="margin-bottom: 10px"
                :label="$t('trials:auditRecord:table:isEnrollment')"
              >
                <el-select
                  v-model="searchData.IsEnrollment"
                  clearable
                  style="width: 120px"
                >
                  <el-option
                    v-for="item of $d.YesOrNo"
                    :key="item.id"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              <!-- 是否PD -->
              <el-form-item
                style="margin-bottom: 10px"
                :label="$t('trials:auditRecord:table:isPDConfirm')"
              >
                <el-select
                  v-model="searchData.IsPDConfirm"
                  clearable
                  style="width: 120px"
                >
                  <el-option
                    v-for="item of $d.YesOrNo"
                    :key="item.id"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item style="margin-bottom: 10px">
                <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: 80 }"
              v-loading="loading"
              :data="list"
              ref="reviewTable"
              height="100%"
              stripe
              @sort-change="handleSortChange"
            >
              <!-- 受试者编号 -->
              <el-table-column
                prop="SubjectCode"
                :label="$t('trials:reviewTrack:table:subjectCode')"
                min-width="120"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 患者编号 -->
              <el-table-column
                prop="PatientList.PatientIdStr"
                :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"
                :label="$t('trials:researchStaff:table:Name')"
                show-overflow-tooltip
                sortable="custom"
                min-width="120"
              />
              <!-- 任务名称 -->
              <el-table-column
                prop="TaskName"
                :label="$t('trials:reviewTrack:table:taskName')"
                width="140"
                sortable="custom"
                show-overflow-tooltip
              >
              </el-table-column>
              <!-- 任务状态 -->
              <el-table-column
                prop="TaskState"
                :label="$t('trials:readTask:table:taskState')"
                min-width="120"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag
                    :type="
                      ['primary', 'info', 'danger', 'warning', 'danger'][
                        scope.row.TaskState
                      ]
                    "
                    >{{ $fd("TaskState", scope.row.TaskState) }}</el-tag
                  >
                </template>
              </el-table-column>
              <!-- 阅片标准 -->
              <el-table-column
                prop="TrialReadingCriterionName"
                :label="$t('trials:reviewTrack:table:criterionName')"
                min-width="180"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 角色 -->
              <el-table-column
                prop="UserTypeShortName"
                :label="$t('trials:auditRecord:table:role')"
                min-width="120"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 阅片人 -->
              <el-table-column
                prop="UserName"
                :label="$t('trials:reviewTrack:table:reader')"
                width="130"
                sortable="custom"
                show-overflow-tooltip
              >
                <template v-if="scope.row.UserName" slot-scope="scope">
                  {{ scope.row.UserName }}({{ scope.row.FullName }})
                </template>
              </el-table-column>
              <!-- 阅片完成时间 -->
              <el-table-column
                prop="SignTime"
                :label="$t('trials:reviewTrack:table:signTime')"
                min-width="180"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 审核结果 -->
              <el-table-column
                prop="PIAuditState"
                :label="$t('trials:auditRecord:table:auditResult')"
                min-width="140"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag
                    v-if="
                      scope.row.PIAuditState >= 0 && scope.row.PIAuditState < 3
                    "
                    :type="
                      ['danger', 'primary', 'warning'][scope.row.PIAuditState]
                    "
                    >{{ $fd("PIAuditState", scope.row.PIAuditState) }}</el-tag
                  >
                  <span v-else>{{
                    $fd("PIAuditState", scope.row.PIAuditState)
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('trials:adReview:title:result')">
                <el-table-column
                  prop="item.QuestionId"
                  :label="item.QuestionName"
                  min-width="140"
                  v-for="(item, index) of QuestionList"
                  :key="'QuestionId' + index"
                  show-overflow-tooltip
                >
                  <template slot-scope="scope">
                    {{
                      item.DictionaryCode
                        ? $fd(
                            item.DictionaryCode,
                            parseInt(
                              scope.row.PIReadingResultList.find(
                                (v) => v.QuestionId === item.QuestionId
                              ).Answer
                            )
                          )
                        : scope.row.PIReadingResultList.find(
                            (v) => v.QuestionId === item.QuestionId
                          ).Answer
                    }}
                  </template>
                </el-table-column>
              </el-table-column>
              <!-- 是否入组 -->
              <el-table-column
                prop="IsEnrollment"
                :label="$t('trials:auditRecord:table:isEnrollment')"
                min-width="110"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.IsEnrollment === true" type="primary">
                    {{ $fd("YesOrNo", scope.row.IsEnrollment) }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.IsEnrollment === false"
                    type="danger"
                    >{{ $fd("YesOrNo", scope.row.IsEnrollment) }}</el-tag
                  >
                </template>
              </el-table-column>
              <!-- 是否PD -->
              <el-table-column
                prop="IsPDConfirm"
                :label="$t('trials:auditRecord:table:isPDConfirm')"
                min-width="110"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.IsPDConfirm === true" type="primary">
                    {{ $fd("YesOrNo", scope.row.IsPDConfirm) }}
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.IsPDConfirm === false"
                    type="danger"
                    >{{ $fd("YesOrNo", scope.row.IsPDConfirm) }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                :label="$t('common:action:action')"
                width="200"
              >
                <template slot-scope="scope">
                  <!-- 阅片结果 -->
                  <el-button
                    circle
                    icon="el-icon-view"
                    :title="$t('trials:auditRecord:table:readingResult')"
                    :disabled="scope.row.TaskState !== 0"
                    @click="handleView(scope.row)"
                  />
                  <!-- 审核 -->
                  <el-button
                    circle
                    icon="el-icon-edit-outline"
                    :title="$t('trials:pendingReview:button:audit')"
                    :disabled="
                      scope.row.TaskState !== 0 ||
                      scope.row.UserTypeShortName === 'PI'
                    "
                    @click="handleAudit(scope.row)"
                  />
                  <!-- 入组确认 -->
                  <el-button
                    v-if="scope.row.VisitTaskNum === 0"
                    circle
                    icon="el-icon-s-claim"
                    :title="$t('trials:pendingReview:button:enrollmentConfirm')"
                    :disabled="
                      !(
                        scope.row.TaskState === 0 &&
                        scope.row.PIAuditState === 2 &&
                        scope.row.IsEnrollmentConfirm &&
                        otherInfo.EnrollConfirmDefaultUserType === 8
                      )
                    "
                    @click="handleEnrollConfirm(scope.row)"
                  />
                  <!-- PD确认 -->
                  <el-button
                    v-if="scope.row.VisitTaskNum !== 0"
                    circle
                    icon="el-icon-s-claim"
                    :title="$t('trials:pendingReview:button:pdConfirm')"
                    :disabled="
                      !(
                        scope.row.TaskState === 0 &&
                        scope.row.PIAuditState === 2 &&
                        scope.row.PDState &&
                        otherInfo.PDProgressDefaultUserType === 8
                      )
                    "
                    @click="handlePDConfirm(scope.row)"
                  />
                  <!-- 审核记录 -->
                  <el-button
                    circle
                    icon="el-icon-tickets"
                    :title="$t('trials:pendingReview:button:auditRecords')"
                    :disabled="
                      scope.row.TaskState !== 0 ||
                      scope.row.PIAuditState === 0 ||
                      scope.row.UserTypeShortName === 'PI'
                    "
                    @click="handleAuditRecords(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="auditVisible"
      :visible.sync="auditVisible"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      :title="`${$t('trials:pendingReview:button:audit')}（${
        currentRow.SubjectCode
      } | ${currentRow.TaskName} | ${currentRow.UserName}）`"
      width="600px"
    >
      <AuditForm
        :row-data="currentRow"
        @viewReaingResult="viewReaingResult"
        @getList="getList"
        @close="auditVisible = false"
      />
    </el-dialog>
    <!-- 入组确认 -->
    <el-dialog
      v-if="enrollVisible"
      :visible.sync="enrollVisible"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      :title="`${$t('trials:pendingReview:button:enrollmentConfirm')}（${
        currentRow.SubjectCode
      } | ${currentRow.TaskName} | ${currentRow.UserName}）`"
      width="400px"
    >
      <EnrollForm
        :row-data="currentRow"
        @viewReaingResult="viewReaingResult"
        @getList="getList"
        @close="enrollVisible = false"
      />
    </el-dialog>
    <!-- PD确认 -->
    <el-dialog
      v-if="pdVisible"
      :visible.sync="pdVisible"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      :title="`${$t('trials:pendingReview:button:pdConfirm')}（${
        currentRow.SubjectCode
      } | ${currentRow.TaskName} | ${currentRow.UserName}）`"
      width="400px"
    >
      <PdForm
        :row-data="currentRow"
        @viewReaingResult="viewReaingResult"
        @getList="getList"
        @close="pdVisible = false"
      />
    </el-dialog>
    <!-- 审核记录 -->
    <el-dialog
      v-if="auditRecordVisible"
      :visible.sync="auditRecordVisible"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      :title="`${$t('trials:pendingReview:button:auditRecords')}（${
        currentRow.SubjectCode
      } | ${currentRow.TaskName} | ${currentRow.UserName}）`"
      width="600px"
    >
      <ChatForm
        :row-data="currentRow"
        @getList="getList"
        @close="auditRecordVisible = false"
      />
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getPIReadingAuditList } from "@/api/reading";
import {
  getTrialCriterionList,
  getDoctorUserSelectList,
} from "@/api/trials/reading";
import { getTrialSiteSelect } from "@/api/trials";
import { getToken } from "@/utils/auth";
import BaseContainer from "@/components/BaseContainer";
import Pagination from "@/components/Pagination";
import AuditForm from "./components/AuditForm";
import EnrollForm from "./components/EnrollForm";
import PdForm from "./components/PdForm";
import ChatForm from "./components/ChatForm";
const searchDataDefault = () => {
  return {
    SubjectCode: "",
    TaskCode: "",
    PageIndex: 1,
    PageSize: 20,
    Asc: true,
    SortField: "",
    IsUrgent: null,
    TaskName: null,
    TaskState: null,
    DoctorUserId: null,
    ReadingTaskState: 2,
    PIAuditState: null,
    IsWaitPIAudit: null,
    IsEnrollment: null,
    IsPDConfirm: null,
    PatientIdStr: null,
    PatientName: null,
  };
};
export default {
  name: "PendingReview",
  components: {
    BaseContainer,
    Pagination,
    AuditForm,
    EnrollForm,
    PdForm,
    ChatForm,
  },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      userListLoading: "",
      trialId: "",
      trialCriterionList: [],
      siteOptions: [],
      DoctorUserList: [],
      auditVisible: false,
      currentRow: {},
      enrollVisible: false,
      pdVisible: false,
      auditRecordVisible: false,
      otherInfo: {},
      openWindow: null,
      TrialReadingCriterionId: "0",
      QuestionList: [],
    };
  },
  watch: {
    TrialReadingCriterionId(v) {
      if (v) {
        this.getList();
      }
    },
  },
  created() {
    this.trialId = this.$route.query.trialId;
    this.getTrialCriterionList();
    // this.getList()
    // this.getSite();
    this.getDoctorUserSelectList();
  },
  methods: {
    getList() {
      this.loading = true;
      this.searchData.TrialId = this.trialId;
      this.searchData.TrialReadingCriterionId = this.TrialReadingCriterionId;
      getPIReadingAuditList(this.searchData)
        .then((res) => {
          this.loading = false;
          this.QuestionList = res.OtherInfo.OtherObj;
          this.list = res.Result.CurrentPageData;
          this.total = res.Result.TotalCount;
          this.otherInfo = res.OtherInfo;
          // this.$nextTick(() => {
          //   if (this.$refs.reviewTable) {
          //     this.$refs.reviewTable[0].doLayout();
          //   }
          // });
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 审核
    handleAudit(row) {
      this.handleView(row);
      this.currentRow = { ...row };
      this.auditVisible = true;
    },
    // 入组确认
    handleEnrollConfirm(row) {
      this.handleView(row);
      this.currentRow = { ...row };
      this.enrollVisible = true;
    },
    // PD确认
    handlePDConfirm(row) {
      this.handleView(row);
      this.currentRow = { ...row };
      this.pdVisible = true;
    },
    handleAuditRecords(row) {
      this.currentRow = { ...row };
      this.auditRecordVisible = true;
    },
    viewReaingResult() {
      if (!this.currentRow) return;
      this.handleView(this.currentRow);
    },
    // 查看阅片结果
    handleView(row) {
      if (this.openWindow) {
        this.openWindow.close();
      }
      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}`;
      }
      this.openWindow = window.open(path, "_blank");
    },
    getTrialCriterionList() {
      getTrialCriterionList(this.trialId)
        .then((res) => {
          this.trialCriterionList = res.Result;
          this.TrialReadingCriterionId =
            this.trialCriterionList[0].TrialReadingCriterionId;
        })
        .catch(() => {});
    },
    getDoctorUserSelectList() {
      getDoctorUserSelectList(this.$route.query.trialId).then((res) => {
        this.DoctorUserList = res.Result;
      });
    },
    getSite() {
      getTrialSiteSelect(this.trialId).then((res) => {
        this.siteOptions = res.Result;
      });
    },
    handleSearch() {
      this.searchData.PageIndex = 1;
      this.getList();
    },
    handleReset() {
      this.searchData = searchDataDefault();
      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>
