<template>
  <BaseContainer class="qc-check-wrapper">
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true">
        <!-- 是否加急 -->
        <el-form-item :label="$t('trials:qcCheck:table:isUrgent')">
          <el-select v-model="searchData.IsUrgent" clearable style="width: 120px">
            <el-option v-for="item of $d.YesOrNo" :key="`IsUrgent${item.value}`" :value="item.value"
              :label="item.label" />
          </el-select>
        </el-form-item>
        <!-- 中心编号 -->
        <el-form-item :label="$t('trials:qcCheck:table:siteId')">
          <el-select v-model="searchData.TrialSiteId" clearable filterable style="width: 120px">
            <el-option v-for="(item, index) of siteOptions" :key="index" :label="item.TrialSiteCode"
              :value="item.TrialSiteId" />
          </el-select>
        </el-form-item>
        <!-- 受试者编号 -->
        <el-form-item :label="$t('trials:qcCheck:table:subjectId')">
          <el-input v-model="searchData.SubjectInfo" style="width: 100px" />
        </el-form-item>
        <!-- 访视名称 -->
        <el-form-item class="my_multiple" :label="$t('trials:qcCheck:table:visitName')">
          <el-select v-model="searchData.VisitPlanArray" style="width: 140px" clearable multiple>
            <el-option v-for="(item, index) of visitPlanOptions" :key="index" :label="item.VisitName"
              :value="item.VisitNum">
              <span style="float: left">{{ item.VisitName }}</span>
            </el-option>
            <el-option key="Other" label="Out of Plan" value="1.11" />
          </el-select>
        </el-form-item>

        <!-- 审核状态 -->
        <el-form-item v-if="OtherInfo.QCProcessEnum !== 0" :label="$t('trials:qcCheck:table:auditState')"
          class="my_multiple">
          <el-select v-if="OtherInfo.QCProcessEnum === 2" v-model="searchData.AuditStateArray" clearable multiple
            style="width: 140px">
            <el-option v-for="item of $d.AuditStateRC" v-show="item.value <= 8" :key="item.value" :value="item.value"
              :label="item.label" />
          </el-select>
          <el-select v-if="OtherInfo.QCProcessEnum === 1" v-model="searchData.AuditStateArray" clearable multiple
            style="width: 140px">
            <el-option v-for="item of $d.AuditStatePE" v-show="item.value <= 8" :key="item.value" :value="item.value"
              :label="item.label" />
          </el-select>
        </el-form-item>
        <!-- 参与人 -->
        <el-form-item v-if="OtherInfo.QCProcessEnum !== 0" :label="$t('trials:qcCheck:table:participant')">
          <el-select v-model="searchData.HandleUserId" clearable filterable style="width: 140px">
            <el-option v-for="(item, index) of participantOptions" :key="index" :label="item.HandleUser"
              :value="item.HandleUserId">
              <span style="float: left">{{ item.HandleUser }}</span>
              <span style="
                  float: right;
                  color: #8492a6;
                  font-size: 13px;
                  margin-left: 5px;
                ">
                {{ item.HandleUserRealName }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 审核通过时间 -->
        <el-form-item :label="$t('trials:qcCheck:table:auditTime')">
          <el-date-picker v-model="timeList" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange" :default-time="['00:00:00', '23:59:59']" @change="changeTimeList"
            style="width: 240px" />
        </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" icon="el-icon-download" :loading="exportLoading" @click="handleExport">
            {{ $t('common:button:export') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>

    <!-- qc审核列表 -->
    <template slot="main-container">
      <el-table ref="qcCheckList" v-loading="loading" v-adaptive="{ bottomOffset: 110 }" :data="list" stripe
        height="100" @sort-change="handleSortByColumn">
        <el-table-column prop="ChallengeState" :label="$t('trials:qcCheck:table:challengeState')" show-overflow-tooltip
          width="140" sortable="custom">
          <template slot-scope="scope">
            <span v-if="scope.row.ChallengeState * 1 === 0">--</span>

            <el-button v-else-if="scope.row.ChallengeState * 1 === 1" style="font-size: 15px" size="mini"
              icon="el-icon-question" circle type="primary" :title="$t('trials:crcQuestion:label:isClosed')"
              @click="handleChallengeState(scope.row.SubjectCode, 1)" />
            <el-button v-else-if="scope.row.ChallengeState * 1 === 2" style="font-size: 15px" size="mini"
              icon="el-icon-question" circle type="danger" :title="$t('trials:crcQuestion:label:isNotClose')"
              @click="handleChallengeState(scope.row.SubjectCode, 2)" />
          </template>
        </el-table-column>
        <!-- 是否加急 -->
        <el-table-column prop="IsUrgent" :label="$t('trials:qcCheck:table:isUrgent')" show-overflow-tooltip width="120"
          sortable="custom">
          <template slot-scope="scope">
            <el-button v-if="
              scope.row.IsUrgent &&
              hasPermi(['trials:trials-panel:visit:qc-check:set-urgent'])
            " type="danger" size="mini" :disabled="!(userTypeEnumInt === 1 || userTypeEnumInt === 3)"
              @click="handleUrgentStatus(scope.row)">
              {{ $fd('YesOrNo', scope.row.IsUrgent) }}
            </el-button>
            <el-button v-else-if="
              !scope.row.IsUrgent &&
              hasPermi(['trials:trials-panel:visit:qc-check:set-urgent'])
            " size="mini" type="primary" :disabled="!(userTypeEnumInt === 1 || userTypeEnumInt === 3)"
              @click="handleUrgentStatus(scope.row)">
              {{ $fd('YesOrNo', scope.row.IsUrgent) }}
            </el-button>
            <span v-else>
              <el-tag v-if="scope.row.IsUrgent" type="danger">
                {{ $fd('YesOrNo', scope.row.IsUrgent) }}
              </el-tag>
              <el-tag v-else type="primary">
                {{ $fd('YesOrNo', scope.row.IsUrgent) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <!-- 中心编号 -->
        <el-table-column prop="TrialSiteCode" :label="$t('trials:qcCheck:table:siteId')" show-overflow-tooltip
          min-width="100" sortable="custom" />
        <!-- 受试者编号 -->
        <el-table-column prop="SubjectCode" :label="$t('trials:qcCheck:table:subjectId')" show-overflow-tooltip
          min-width="120" sortable="custom" />
        <!-- 访视名称 -->
        <el-table-column prop="VisitName" :label="$t('trials:qcCheck:table:visitName')" show-overflow-tooltip
          width="130" sortable="custom">
          <template slot-scope="scope">
            <el-button v-if="scope.row.VisitExecuted === 1" type="text" @click="handleViewStudyInfo(scope.row)">
              {{ scope.row.VisitName }}
            </el-button>
            <span v-else>
              {{ scope.row.VisitName }}
            </span>
            <!-- PD -->
            <span v-if="scope.row.PDState" class="status-primary-circle">
              {{ $t('trials:crcUpload:label:pd') }}
            </span>
            <!-- 失 -->
            <span v-if="scope.row.IsLostVisit" class="status-primary-circle">
              {{ $t('trials:crcUpload:label:lostVisit') }}
            </span>
            <!-- 末 -->
            <span v-if="scope.row.IsFinalVisit" class="status-primary-circle">
              {{ $t('trials:crcUpload:label:finalVisit') }}
            </span>
            <!-- 入 -->
            <span v-if="scope.row.IsEnrollmentConfirm" class="status-primary-circle">
              {{ $t('trials:crcUpload:label:enrollmentConfirm') }}
            </span>
            <!-- 退回待审批 -->
            <span v-if="scope.row.IsImageBackApplying" class="status-primary-circle">
              {{ $t('trials:crcUpload:label:back') }}
            </span>
            <!-- 终止 -->
            <span v-if="scope.row.IsSubjectQuit" class="status-primary-circle">
              {{ $t('trials:crcUpload:label:ISQ') }}
            </span>
          </template>
        </el-table-column>
        <!-- 数据收集 -->
        <el-table-column prop="DicomStudyCount" :label="$t('trials:qcCheck:table:dataCollected')" show-overflow-tooltip
          min-width="110">
          <template slot-scope="scope">
            <el-tooltip placement="bottom">
              <div slot="content">
                <span>{{ $t('trials:crcUpload:label:dicom') }}:
                  {{ scope.row.DicomStudyCount }},
                </span>
                <span v-if="
                  scope.row.IsBaseLine &&
                  OtherInfo.ClinicalInformationTransmissionEnum > 0
                ">
                  <span>{{ $t('trials:crcUpload:label:noneDicom') }}:
                    {{ scope.row.NoneDicomStudyCount }},
                  </span>
                  <span>{{ $t('trials:crcUpload:label:clinicalData') }}:
                    {{ scope.row.IsHaveClinicalData ? 'w/' : 'w/o' }}</span>
                </span>
                <span v-else>{{ $t('trials:crcUpload:label:noneDicom') }}:
                  {{ scope.row.NoneDicomStudyCount }}</span>
              </div>
              <span>
                {{
                  scope.row.IsBaseLine &&
                    OtherInfo.ClinicalInformationTransmissionEnum > 0
                    ? [
                      scope.row.DicomStudyCount,
                      scope.row.NoneDicomStudyCount,
                      scope.row.IsHaveClinicalData ? 'w/' : 'w/o',
                    ].join(', ')
                    : [
                      scope.row.DicomStudyCount,
                      scope.row.NoneDicomStudyCount,
                    ].join(', ')
                }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 最早拍片日期 -->
        <!-- <el-table-column
          prop="EarliestScanDate"
          :label="$t('trials:qcCheck:table:eScanDate')"
          show-overflow-tooltip
          width="170"
          sortable="custom"
        >
          <template slot-scope="scope">
            {{
              scope.row.EarliestScanDate
                ? moment(scope.row.EarliestScanDate).format("YYYY-MM-DD")
                : ""
            }}
          </template>
        </el-table-column> -->
        <!-- 最晚拍片日期 -->
        <el-table-column prop="LatestScanDate" :label="$t('trials:qcCheck:table:lScanDate')" show-overflow-tooltip
          width="170" sortable="custom">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="`${scope.row.EarliestScanDate
              ? moment(scope.row.EarliestScanDate).format('YYYY-MM-DD')
              : ''
              } ~ ${scope.row.LatestScanDate
                ? moment(scope.row.LatestScanDate).format('YYYY-MM-DD')
                : ''
              }`" placement="top">
              <span>
                {{
                  scope.row.LatestScanDate
                    ? moment(scope.row.LatestScanDate).format('YYYY-MM-DD')
                    : ''
                }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 提交时间 -->
        <el-table-column prop="SubmitTime" :label="$t('trials:qcCheck:table:submitTime')" show-overflow-tooltip
          width="180" sortable="custom" />
        <!-- 上传人 -->
        <el-table-column prop="SubmitUserRealName" :label="$t('trials:studyList:table:uploader')" show-overflow-tooltip
          width="140" sortable="custom" />
        <!-- 审核状态 -->
        <el-table-column prop="AuditState" :label="$t('trials:qcCheck:table:auditState')" show-overflow-tooltip
          width="120" sortable="custom">
          <template slot-scope="scope">
            <span v-if="scope.row.AuditState * 1 === 0">--</span>
            <el-tag v-else-if="scope.row.AuditState * 1 === 3" type="warning">{{
              $fd('AuditStatePE', scope.row.AuditState * 1)
            }}</el-tag>
            <el-tag v-else-if="
              scope.row.AuditState * 1 === 4 && scope.row.QCProcessEnum === 1
            " type="warning">
              {{ $fd('AuditStatePE', scope.row.AuditState * 1) }}
            </el-tag>
            <el-tag v-else-if="
              scope.row.AuditState * 1 === 4 && scope.row.QCProcessEnum === 2
            " type="warning">
              {{ $fd('AuditStateRC', scope.row.AuditState * 1) }}
            </el-tag>
            <el-tag v-else-if="
              scope.row.AuditState * 1 === 5 && scope.row.QCProcessEnum === 2
            " type="warning">
              {{ $fd('AuditStateRC', scope.row.AuditState * 1) }}
            </el-tag>
            <el-tag v-else-if="
              scope.row.AuditState * 1 === 6 && scope.row.QCProcessEnum === 2
            " type="warning">
              {{ $fd('AuditStateRC', scope.row.AuditState * 1) }}
            </el-tag>
            <el-tag v-else-if="scope.row.AuditState * 1 === 7" type="danger">
              {{ $fd('AuditStateRC', scope.row.AuditState * 1) }}</el-tag>
            <el-tag v-else-if="scope.row.AuditState * 1 === 8" type="primary">
              {{ $fd('AuditStateRC', scope.row.AuditState * 1) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 审核完成时间 -->
        <el-table-column prop="AuditTime" :label="$t('trials:qcCheck:table:auditTime')" show-overflow-tooltip
          width="170" />
        <!-- 历史审核人 -->
        <el-table-column v-show="OtherInfo.QCProcessEnum !== 0" prop="PreliminaryAuditUserName"
          :label="$t('trials:qcCheck:table:reviewer')" show-overflow-tooltip min-width="200">
          <template slot-scope="scope">
            <!-- <span>{{ scope.row.PreliminaryAuditUserName }}</span> -->
            <el-button v-if="
              scope.row.PreliminaryAuditUserName &&
              (!(
                hasPermi(['role:iqc']) &&
                scope.row.AuditState < 7 &&
                userId !== scope.row.PreliminaryAuditUserId
              ) ||
                !hasPermi(['role:iqc']) ||
                scope.row.AuditState >= 7)
            " type="text" @click="handleViewPrimaryQC(scope.row)">
              {{ scope.row.PreliminaryAuditUserName }}
            </el-button>
            <span v-else>{{ scope.row.PreliminaryAuditUserName }}</span>
            <span v-if="
              scope.row.PreliminaryAuditUserName &&
              OtherInfo.QCProcessEnum === 2
            " class="status-primary-circle">
              {{ $t('trials:qcCheck:label:preliminary') }}
            </span>
            <span v-if="scope.row.ReviewAuditUserName"> , </span>
            <!-- <span>{{ scope.row.ReviewAuditUserName }}</span> -->
            <el-button v-if="scope.row.ReviewAuditUserName" type="text" @click="handleViewReviewQC(scope.row)">
              {{ scope.row.ReviewAuditUserName }}
            </el-button>
            <span v-if="
              scope.row.ReviewAuditUserName && OtherInfo.QCProcessEnum === 2
            " class="status-primary-circle">
              {{ $t('trials:qcCheck:label:review') }}
            </span>
          </template>
        </el-table-column>
        <!-- 领取人 -->
        <el-table-column v-show="OtherInfo.QCProcessEnum !== 0" prop="CurrentActionUserName"
          :label="$t('trials:qcCheck:table:crrentUser')" show-overflow-tooltip width="130" sortable="custom" />

        <el-table-column v-if="
          OtherInfo.QCProcessEnum !== 0 &&
          hasPermi([
            'trials:trials-panel:visit:qc-check:receive',
            'trials:trials-panel:visit:qc-check:release',
            'trials:trials-panel:visit:qc-check:audit',
            'trials:trials-panel:visit:qc-check:back',
            'trials:trials-panel:visit:qc-check:reviewTask'
          ])
        " :label="$t('common:action:action')" width="280" fixed="right">
          <template slot-scope="scope">
            <div v-if="scope.row.AuditState * 1 >= 3">
              <!--复核 -->
              <el-button v-if="scope.row.SecondReviewState === 1 && scope.row.AuditState * 1 === 8"
                v-hasPermi="['trials:trials-panel:visit:qc-check:reviewTask']"
                :title="$t('trials:qcCheck:button:reviewTask')" circle icon="el-icon-edit"
                :disabled="(scope.row.CurrentActionUserId && scope.row.CurrentActionUserId !== userId) || scope.row.IsImageBackApplying"
                @click="reviewTask(scope.row)" />
              <!-- 领取 -->
              <!-- ((scope.row.AuditState*1 === 3 || scope.row.AuditState*1 === 5)) ||(!scope.row.IsTake && (scope.row.AuditState*1 === 4 || scope.row.AuditState*1 === 6)) -->
              <el-button v-hasPermi="['trials:trials-panel:visit:qc-check:receive']"
                :title="$t('trials:qcCheck:button:receive')" circle icon="el-icon-lock" :disabled="scope.row.PreliminaryAuditUserId === userId ||
                  scope.row.IsTake ||
                  scope.row.AuditState > 6 || scope.row.IsImageBackApplying || (scope.row.IsSubjectQuit && scope.row.AuditState * 1 !== 8)
                  " @click="handleReciveTask(scope.row, true)" />
              <!-- 释放：当前领取人才能释放 -->
              <!-- v-if="(scope.row.IsTake && (scope.row.AuditState*1 === 4 || scope.row.AuditState*1 === 6))" -->
              <el-button v-hasPermi="['trials:trials-panel:visit:qc-check:release']"
                :title="$t('trials:qcCheck:button:release')" circle icon="el-icon-unlock" :disabled="!(scope.row.CurrentActionUserId === userId) ||
                  !scope.row.IsTake ||
                  scope.row.AuditState * 1 > 6 || scope.row.IsImageBackApplying || (scope.row.IsSubjectQuit && scope.row.AuditState * 1 !== 8)
                  " @click="handleReciveTask(scope.row, false)" />
              <!-- 替换：1、针对同一访视质控，初审人不能替换复审人；2、当前领取人不能替换自己； -->
              <!-- v-if="(scope.row.IsTake && (scope.row.AuditState*1 === 4 || scope.row.AuditState*1 === 6))" -->
              <el-button v-hasPermi="['trials:trials-panel:visit:qc-check:release']"
                :title="$t('trials:crcQuestion:button:replaceTask')" circle icon="el-icon-refresh" :disabled="scope.row.CurrentActionUserId === userId ||
                  scope.row.PreliminaryAuditUserId === userId ||
                  !scope.row.IsTake ||
                  scope.row.AuditState * 1 > 6 || scope.row.IsImageBackApplying || (scope.row.IsSubjectQuit && scope.row.AuditState * 1 !== 8)
                  " @click="handleReplaceTask(scope.row)" />
              <!-- 审核 -->
              <!-- v-if="scope.row.QCProcessEnum === 1 && scope.row.AuditState*1 === 4 && scope.row.IsTake" -->
              <el-button v-if="scope.row.QCProcessEnum === 1" v-hasPermi="['trials:trials-panel:visit:qc-check:audit']"
                :title="$t('trials:qcCheck:button:audit')" circle icon="el-icon-edit-outline" :disabled="(scope.row.CurrentActionUserId
                  ? scope.row.CurrentActionUserId !== userId
                  : false) ||
                  !scope.row.IsTake ||
                  scope.row.AuditState * 1 > 6 || scope.row.IsImageBackApplying || (scope.row.IsSubjectQuit && scope.row.AuditState * 1 !== 8)
                  " @click="handlePrimaryQC(scope.row)" />
              <!-- 初审 -->
              <!-- v-if="scope.row.QCProcessEnum === 2 && scope.row.AuditState*1 === 4 && scope.row.IsTake" -->
              <el-button v-if="
                scope.row.QCProcessEnum === 2 && scope.row.AuditState * 1 < 6
              " v-hasPermi="['trials:trials-panel:visit:qc-check:audit']"
                :title="$t('trials:qcCheck:button:preliminaryAudit')" circle icon="el-icon-edit-outline" :disabled="(scope.row.CurrentActionUserId
                  ? scope.row.CurrentActionUserId !== userId
                  : false) ||
                  !scope.row.IsTake ||
                  scope.row.AuditState * 1 > 6 || scope.row.IsImageBackApplying || (scope.row.IsSubjectQuit && scope.row.AuditState * 1 !== 8)
                  " @click="handlePrimaryQC(scope.row)" />
              <!-- 复审 -->
              <!-- v-if="scope.row.QCProcessEnum === 2 && scope.row.AuditState*1 === 6 && scope.row.IsTake && scope.row.PreliminaryAuditUserId!==userId" -->
              <el-button v-if="
                scope.row.QCProcessEnum === 2 && scope.row.AuditState * 1 >= 6
              " v-hasPermi="['trials:trials-panel:visit:qc-check:audit']" :title="$t('trials:qcCheck:button:review')"
                circle icon="el-icon-edit-outline" :disabled="scope.row.PreliminaryAuditUserId === userId ||
                  !scope.row.IsTake ||
                  scope.row.AuditState * 1 > 6 ||
                  scope.row.CurrentActionUserId !== userId
                  || scope.row.IsImageBackApplying"
                @click="handleSecondaryQC(scope.row) || (scope.row.IsSubjectQuit && scope.row.AuditState * 1 !== 8)" />
              <!-- 退回 -->
              <el-button
                :disabled="scope.row.SubmitState * 1 < 2 || scope.row.IsImageBackApplying || scope.row.ChallengeState * 1 === 2 || (scope.row.IsSubjectQuit && scope.row.AuditState * 1 !== 8)"
                v-hasPermi="['trials:trials-panel:visit:qc-check:back']" icon="el-icon-back" circle
                :title="$t('trials:qcCheck:button:back')" @click="imageBack(scope.row)" />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
        @pagination="getList" />
    </template>
    <div class="remark">
      <span class="status-primary-circle">
        {{ $t('trials:crcUpload:label:finalVisit') }}
      </span>
      <span>: {{ $t('trials:crcUpload:label:finalVisitDetail') }}</span>

      <span class="status-primary-circle" style="margin-left: 10px">
        {{ $t('trials:crcUpload:label:lostVisit') }}
      </span>
      <span>: {{ $t('trials:crcUpload:label:lostVisitDetail') }}</span>

      <span class="status-primary-circle" style="margin-left: 10px">
        {{ $t('trials:crcUpload:label:pd') }}
      </span>
      <span>: {{ $t('trials:crcUpload:label:pdDetail') }}</span>
      <span class="status-primary-circle" style="margin-left: 10px">
        {{ $t('trials:crcUpload:label:enrollmentConfirm') }}
      </span>
      <span>: {{ $t('trials:crcUpload:label:enrollmentConfirmDetail') }}</span>

      <span v-if="OtherInfo.QCProcessEnum === 2" class="status-primary-circle" style="margin-left: 10px">
        {{ $t('trials:qcCheck:label:preliminary') }}
      </span>
      <span v-if="OtherInfo.QCProcessEnum === 2">: {{ $t('trials:qcCheck:label:preliminaryAudit') }}</span>

      <span v-if="OtherInfo.QCProcessEnum === 2" class="status-primary-circle" style="margin-left: 10px">
        {{ $t('trials:qcCheck:label:review') }}
      </span>
      <span v-if="OtherInfo.QCProcessEnum === 2">: {{ $t('trials:qcCheck:label:reviewAudit') }}</span>
      <span class="status-primary-circle" style="margin-left: 10px">
        {{ $t('trials:crcUpload:label:back') }}
      </span>
      <span>: {{ $t('trials:crcUpload:label:backAudit') }}</span>
      <span class="status-primary-circle" style="margin-left: 10px">
        {{ $t('trials:crcUpload:label:ISQ') }}
      </span>
      <span>: {{ $t('trials:crcUpload:label:IsSubjectQuit') }}</span>
    </div>
    <!-- 指控 -->
    <el-dialog v-if="qcVisible" :visible.sync="qcVisible" :fullscreen="true" :close-on-click-modal="false"
      custom-class="qc-dialog">
      <span slot="title">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item v-if="trialCode">{{
            trialCode
          }}</el-breadcrumb-item>
          <el-breadcrumb-item v-if="rowData.TrialSiteCode">{{
            rowData.TrialSiteCode
          }}</el-breadcrumb-item>
          <el-breadcrumb-item v-if="rowData.SubjectCode">{{
            rowData.SubjectCode
          }}</el-breadcrumb-item>
          <el-breadcrumb-item v-if="rowData.VisitName">
            {{ `${rowData.VisitName} (${rowData.VisitNum})` }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </span>
      <div class="qc-dialog-body">
        <quality-assurance v-if="qcVisible" :data="rowData" :disabled="rowData.disabled ? rowData.disabled : false"
          :SecondReviewState="rowData.SecondReviewState" :q-type="rowData.qcType ? rowData.qcType : 1"
          :auditorId="auditorId" @getList="getList" @nextTask="nextTask" @openManuals="openManuals"
          @close="qcVisible = false" />
      </div>
    </el-dialog>
    <!-- 手册 -->
    <el-dialog v-if="manualsDialog.visible" :visible.sync="manualsDialog.visible" :custom-class="isFullscreen
      ? 'manuals-full-dialog-container'
      : 'manuals-dialog-container'
      " :show-close="false" :close-on-click-modal="false" :fullscreen="isFullscreen">
      <span slot="title" class="dialog-footer">
        <span>{{ $t('trials:reading:button:handbooks') }}</span>
        <span style="position: absolute; right: 20px">
          <svg-icon :icon-class="isFullscreen ? 'exit-fullscreen' : 'fullscreen'"
            style="margin-right: 10px; cursor: pointer; font-size: 20px" @click="isFullscreen = !isFullscreen" />
          <svg-icon icon-class="dClose" style="cursor: pointer; font-size: 24px"
            @click="manualsDialog.visible = false" />
        </span>
      </span>
      <div style="height: 100%; margin: 0">
        <Manuals :trial-id="trialId" />
      </div>
    </el-dialog>
    <!-- 检查信息 -->
    <el-dialog v-if="studyVisible" :visible.sync="studyVisible" :close-on-click-modal="false" :fullscreen="true"
      custom-class="upload-dialog">
      <span slot="title">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item v-show="searchData.TrialCode">{{
            searchData.TrialCode
          }}</el-breadcrumb-item>
          <el-breadcrumb-item v-show="rowData.SiteCode">{{
            rowData.TrialSiteCode
          }}</el-breadcrumb-item>
          <el-breadcrumb-item v-show="rowData.SubjectCode">{{
            rowData.SubjectCode
          }}</el-breadcrumb-item>
          <el-breadcrumb-item v-show="rowData.VisitName">{{
            `${rowData.VisitName} (${rowData.VisitNum})`
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </span>
      <div class="base-modal-body">
        <el-form :inline="true" class="base-search-form" style="padding: 10px">
          <!-- 访视基准日期 -->
          <el-form-item v-show="rowData.IsBaseLine && OtherInfo.IsHaveFirstGiveMedicineDate"
            :label="$t('trials:crcUpload:form:baseDateOfVisit')">
            <el-date-picker v-model="rowData.SubjectFirstGiveMedicineTime" type="date" value-format="yyyy-MM-dd"
              format="yyyy-MM-dd" disabled />
          </el-form-item>
          <!-- 入组确认评估 -->
          <el-form-item v-show="rowData.IsBaseLine && OtherInfo.IsEnrollementQualificationConfirm
            " :label="$t('trials:crcUpload:form:enrollmentConfirmation')">
            <el-radio-group v-model="rowData.IsEnrollmentConfirm" disabled>
              <el-radio v-for="item of $d.YesOrNo" :key="`IsEnrollmentConfirm${item.value}`" :label="item.value">{{
                item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 疾病进展确认评估 -->
          <el-form-item v-show="!rowData.IsBaseLine && OtherInfo.IsPDProgressView"
            :label="$t('trials:crcUpload:form:pd')">
            <el-radio-group v-model="rowData.PDState" disabled>
              <el-radio v-for="item of $d.YesOrNoForInt" :key="`PDState${item.value}`" :label="item.value">{{ item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div>
          <!-- DICOM影像 -->
          <h4 class="box-title" v-if="[0, 1].includes($store.state.trials.config.CollectImagesEnum)">
            {{ $t('trials:audit:tab:dicoms') }}
          </h4>
          <el-card class="box-card" v-if="[0, 1].includes($store.state.trials.config.CollectImagesEnum)">
            <DicomFiles v-if="rowData.Id" :data="rowData" />
          </el-card>
        </div>

        <div>
          <!-- 非DICOM影像 -->
          <h4 class="box-title" style="margin-top: 10px"
            v-if="[0, 2].includes($store.state.trials.config.CollectImagesEnum)">
            {{ $t('trials:audit:tab:nonDicoms') }}
          </h4>
          <el-card class="box-card" v-if="[0, 2].includes($store.state.trials.config.CollectImagesEnum)">
            <UploadNonDicomFiles v-if="rowData.Id" :body-parts="OtherInfo.BodyPartTypes"
              :modalities="OtherInfo.Modalitys" :data="rowData" :allow-add-or-edit="false"
              :subject-visit-id="rowData.Id" />
          </el-card>
        </div>

        <div>
          <!-- 临床数据 -->
          <h4 class="box-title" style="margin-top: 10px">
            {{ $t('trials:audit:tab:clinicalData') }}
          </h4>
          <el-card class="box-card">
            <UploadClinicalData v-if="rowData.Id" :enum-type="OtherInfo.ClinicalInformationTransmissionEnum"
              :data="rowData" :subject-visit-id="rowData.Id" :allow-add-or-edit="false" />
          </el-card>
        </div>
      </div>
    </el-dialog>

    <!-- 设置紧急状态 -->
    <el-dialog v-if="urgentVisible" :visible.sync="urgentVisible" :close-on-click-modal="false"
      :title="$t('trials:qcCheck:dialogTitle:setUrgent')" width="400px" style="height: 500px"
      custom-class="base-dialog-wrapper">
      <el-form :model="urgentForm" size="mini">
        <div class="base-dialog-body">
          <!-- 是否加急 -->
          <el-form-item :label="$t('trials:qcCheck:table:isUrgent')">
            <el-radio-group v-model="urgentForm.IsUrgent">
              <el-radio v-for="item of $d.YesOrNo" :key="`formIsUrgent${item.value}`" :label="item.value">{{ item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
          <el-form-item>
            <!-- 取消 -->
            <el-button :disabled="loading" size="small" type="primary" @click="urgentVisible = false">
              {{ $t('common:button:cancel') }}
            </el-button>
            <!-- 保存 -->
            <el-button size="small" type="primary" :loading="loading" @click="setUrgentStatus">
              {{ $t('common:button:save') }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
  </BaseContainer>
</template>
<script>
import {
  getQCVisitList,
  getTrialSiteSelect,
  getTrialVisitStageSelect,
  getQCParticipantList,
  replaceQCTaskActionUser,
  takeOrReleaseQCTask,
  setSubjectVisitUrgent,
  isQCCanOpt,
  getNextQCInfo,
} from '@/api/trials'
import { qCVisitList_Export } from '@/api/export'
import BaseContainer from '@/components/BaseContainer'
import QualityAssurance from './components/qualityAssurance'
import Manuals from './components/manuals'
import DicomFiles from './components/dicomFiles'
import UploadNonDicomFiles from '@/views/trials/trials-panel/visit/crc-upload/components/uploadNonDicomFiles'
import UploadClinicalData from '@/views/trials/trials-panel/visit/crc-upload/components/uploadClinicalData'
import { requestImageBack } from '@/api/trials/visit'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { changeURLStatic } from '@/utils/history.js'
import { getToken } from '@/utils/auth'

const searchDataDefault = () => {
  return {
    TrialId: '',
    TrialSiteId: '',
    SubjectInfo: '',
    VisitPlanArray: [],
    IsUrgent: null,
    AuditStateArray: [],
    HandleUserId: '',
    BeginAuditTime: null,
    EndAuditTime: null,
    PageIndex: 1,
    PageSize: 20,
    // SortField: '',
    // Asc: false
  }
}
export default {
  name: 'QcCheck',
  components: {
    BaseContainer,
    Pagination,
    QualityAssurance,
    DicomFiles,
    UploadNonDicomFiles,
    UploadClinicalData,
    Manuals,
  },
  data() {
    return {
      searchData: searchDataDefault(),
      total: 0,
      list: [],
      loading: false,
      qcVisible: false,
      rowData: {
        TrialSiteCode: '',
        SubjectCode: '',
        VisitName: '',
        VisitNum: '',
      },
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      userId: zzSessionStorage.getItem('userId'),
      moment,
      siteOptions: [],
      visitPlanOptions: [],
      OtherInfo: {},
      participantOptions: [],
      studyVisible: false,
      urgentVisible: false,
      urgentForm: { id: '', isUrgent: null },
      trialId: this.$route.query.trialId,
      trialCode: this.$route.query.trialCode,
      query: null,
      manualsDialog: { visible: false },
      isFullscreen: false,
      timeList: [],
      exportLoading: false,
      auditorId: null
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    },
    qcVisible() {
      if (!this.qcVisible) {
        this.auditorId = null
      }
    }
  },
  mounted() {
    this.query = this.$route.query
    if (this.$route.query.subjectCode) {
      this.searchData.SubjectInfo = this.$route.query.subjectCode
    }
    changeURLStatic('subjectCode', '')
    this.getList()
    this.getSite()
    this.getParticipantList()
    this.getVisitPlanOptions()
  },
  methods: {
    // 申请影像退回
    async imageBack(row) {
      try {
        this.$prompt(`<span style="color:#F56C6C">*</span><span>${this.$t("trials:crcUpload:confirmMessage:ApplyReason")}</span>`, this.$t("trials:crcUpload:confirmMessage:imageBack"), {
          confirmButtonText: this.$t("common:button:save"),
          cancelButtonText: this.$t("common:button:cancel"),
          dangerouslyUseHTMLString: true,
          inputValidator: (val) => {
            if (!val) return this.$t("common:ruleMessage:specify")
          },
          inputErrorMessage: this.$t("common:ruleMessage:specify")
        }).then(async ({ value }) => {
          let params = {
            SubjectVisitId: row.Id,
            ApplyReason: value
          }
          // return console.log(params)
          let res = await requestImageBack(params)

          if (res.IsSuccess) {
            this.getList()
          }
        }).catch(() => {

        });
        // let confirm = await this.$confirm(this.$t("trials:crcUpload:confirmMessage:imageBack"))
        // if (!confirm) return false
      } catch (err) {
        console.log(err)
      }
    },
    handleExport() {
      this.exportLoading = true
      qCVisitList_Export(this.searchData)
        .then(() => {
          this.exportLoading = false
        })
        .catch((err) => {
          this.exportLoading = false
        })
    },
    // 获取qc审核列表
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      getQCVisitList(this.searchData)
        .then((res) => {
          this.loading = false
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
          this.OtherInfo = res.OtherInfo
        })
        .catch(() => {
          this.loading = false
        })
    },
    doLayout() {
      const scope = this
      this.$nextTick(() => {
        scope.$refs.qcCheckList.doLayout()
      })
    },
    // 领取任务
    handleReciveTask(row, state) {
      let message = ''
      if (state) {
        // 是否确认领取？
        message = this.$t('trials:qcCheck:message:receive')
      } else {
        // 是否确认释放？
        message = this.$t('trials:qcCheck:message:release')
      }
      this.$confirm(message, {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.loading = true
          takeOrReleaseQCTask(row.TrialId, row.Id, state)
            .then((res) => {
              this.loading = false
              if (res.IsSuccess) {
                this.getList()
                if (state) {
                  // 领取成功
                  this.$message.success(
                    this.$t('trials:qcCheck:message:receivedSuccessfully')
                  )
                } else {
                  // 释放成功
                  this.$message.success(
                    this.$t('trials:qcCheck:message:releasedSuccessfully')
                  )
                }
              }
            })
            .catch((res) => {
              this.loading = false
              if (res.Code === 5 && res.ErrorMessage) {
                this.$confirm(res.ErrorMessage, {
                  type: 'warning',
                  showCancelButton: false,
                  callback: (action) => { },
                })
                this.getList()
              }
            })
        })
        .catch(() => { })
    },
    // 复审
    async reviewTask(row) {
      if (!this.OtherInfo.IsQCQuestionConfirmed) return this.$alert(this.$t("trials:qcCheck:alert:questionNoConfirm"))
      try {
        this.loading = true
        let res = await takeOrReleaseQCTask(row.TrialId, row.Id, true)
        this.loading = false
        if (res.IsSuccess) {
          this.rowData = { ...row }
          this.qcVisible = true
        }
      } catch (err) {
        console.log(err)
        this.loading = false
        if (err.Code === 5 && err.ErrorMessage) {
          this.$confirm(err.ErrorMessage, {
            type: 'warning',
            showCancelButton: false,
            callback: (action) => { },
          })
          this.getList()
        }
      }

    },
    // 初审
    handlePrimaryQC(row) {
      if (!this.OtherInfo.IsQCQuestionConfirmed) return this.$alert(this.$t("trials:qcCheck:alert:questionNoConfirm"))
      this.loading = true
      isQCCanOpt(row.Id)
        .then((res) => {
          this.loading = false
          if (res.IsSuccess) {
            this.rowData = { ...row }
            this.qcVisible = true
          }
        })
        .catch((res) => {
          this.loading = false
          if (res.Code === 2) {
            this.getList()
          }
        })
    },
    // 复审
    handleSecondaryQC(row) {
      if (!this.OtherInfo.IsQCQuestionConfirmed) return this.$alert(this.$t("trials:qcCheck:alert:questionNoConfirm"))
      this.loading = true
      isQCCanOpt(row.Id)
        .then((res) => {
          this.loading = false
          if (res.IsSuccess) {
            this.rowData = { ...row }
            this.qcVisible = true
          }
        })
        .catch((res) => {
          this.loading = false
          if (res.Code === 2) {
            this.getList()
          }
        })
    },
    handleViewPrimaryQC(row) {
      this.rowData = { ...row }
      this.rowData.disabled = true
      this.rowData.qcType = 1
      this.qcVisible = true
      this.auditorId = row.PreliminaryAuditUserId
    },
    handleViewReviewQC(row) {
      this.rowData = { ...row }
      this.rowData.disabled = true
      this.rowData.qcType = 2
      this.qcVisible = true
      this.auditorId = row.ReviewAuditUserId
    },
    // 预览影像
    handleViewImages() {
      var tokenKey = getToken()
      const routeData = this.$router.resolve({
        path: `/showvisitdicoms?trialId=${this.rowData.TrialId}&visitInfo=${this.rowData.VisitName}(${this.rowData.VisitNum})&subjectVisitId=${this.rowData.Id}&TokenKey=${tokenKey}`,
      })
      window.open(routeData.href, '_blank')
    },
    // 查看检查信息
    handleViewStudyInfo(row) {
      this.studyVisible = true
      this.rowData = { ...row }
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.timeList = []
      this.getList()
      this.$nextTick(() => {
        this.$refs.qcCheckList.clearSort()
      })
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 排序
    handleSortByColumn(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()
    },
    // 获取site下拉框数据
    getSite() {
      getTrialSiteSelect(this.trialId).then((res) => {
        this.siteOptions = res.Result
      })
    },
    // 获取访视下拉框数据
    getVisitPlanOptions() {
      getTrialVisitStageSelect(this.trialId).then((res) => {
        this.visitPlanOptions = res.Result
      })
    },
    // 获取质询参与者下拉框数据
    getParticipantList() {
      getQCParticipantList(this.trialId).then((res) => {
        this.participantOptions = res.Result
      })
    },
    // 打开设置紧急状态弹窗
    handleUrgentStatus(row) {
      this.urgentForm = Object.assign({}, { ...row })
      this.urgentVisible = true
    },
    // 设置访视加急/不加急
    setUrgentStatus() {
      // 是否确认将当前访视设置为加急？
      // 是否确认将当前访视设置为不加急？
      var message = this.urgentForm.IsUrgent
        ? this.$t('trials:qcCheck:message:isUrgent')
        : this.$t('trials:qcCheck:message:isNotUrgent')
      this.$confirm(message, {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        this.loading = true

        setSubjectVisitUrgent(
          this.urgentForm.TrialId,
          this.urgentForm.Id,
          this.urgentForm.IsUrgent
        )
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.urgentVisible = false
              this.getList()
              this.$message.success(this.$t('common:message:savedSuccessfully'))
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    handleChallengeState(subjectCode, state) {
      this.$router.push({
        path: `/trials/trials-panel/visit/qc-question?trialId=${this.trialId}&trialCode=${this.query.trialCode}&researchProgramNo=${this.query.researchProgramNo}&subjectCode=${subjectCode}&challengeState=${state}`,
      })
    },
    // 替换
    handleReplaceTask(row) {
      var message = this.$t('trials:crcQuestion:message:replaceTask')
      message = message.replace('xxx', row.CurrentActionUserName)
      this.$confirm(message, {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          // 替换并刷新列表
          this.loading = true
          replaceQCTaskActionUser(row.TrialId, row.Id)
            .then((res) => {
              this.loading = false
              if (res.IsSuccess) {
                // 替换成功
                this.$message.success(
                  this.$t('trials:crcQuestion:message:replaceTaskSuccessfully')
                )
                this.getList()
              }
            })
            .catch((res) => {
              this.loading = false
              this.getList()
              if (res.ErrorMessage) {
                this.$confirm(res.ErrorMessage, {
                  type: 'warning',
                  showCancelButton: false,
                  callback: (action) => { },
                })
              }
            })
        })
        .catch(() => { })
    },
    nextTask(visitId = null) {
      this.loading = true
      let obj = {
        trialId: this.trialId,
      }
      if (visitId) {
        obj.visitId = visitId
      }
      getNextQCInfo(obj)
        .then((res) => {
          this.loading = false
          this.qcVisible = false
          if (res.Result) {
            this.$nextTick(() => {
              this.rowData = { ...res.Result }
              this.qcVisible = true
            })
          } else {
            this.$message.success(this.$t('trials:qcQuality:title:title3')) // '当前领取的质控任务已全部完成！'
            this.qcVisible = false
          }
        })
        .catch(() => {
          this.loading = false
          this.qcVisible = false
        })
    },
    changeTimeList() {
      if (this.timeList) {
        this.searchData.BeginAuditTime = this.timeList[0]
        this.searchData.EndAuditTime = this.timeList[1]
      } else {
        this.searchData.BeginAuditTime = null
        this.searchData.EndAuditTime = null
      }
    },
    openManuals() {
      this.manualsDialog.visible = true
    },
  },
}
</script>
<style lang="scss">
.qc-check-wrapper {
  position: relative;

  .remark {
    position: absolute;
    left: 5px;
    bottom: 7px;
    font-size: 12px;
  }

  height: 100%;

  .qc-dialog {
    .el-dialog__headerbtn {
      top: 10px;
      font-size: 30px;
    }

    .el-dialog__body {
      height: calc(100% - 70px);
      padding: 0 10px;

      .qc-dialog-body {
        padding: 10px 20px;
        height: 100%;
        overflow-y: auto;
      }
    }

    .link-breadcrumb {
      cursor: pointer;
      color: #428bca;
    }
  }

  .box-title {
    padding: 12px;
    margin-bottom: 10px;
    background-color: #dcdfe6;
  }

  .status-primary-circle {
    display: inline-block;
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 18px;
    border-radius: 50%;
    border: 1px solid #f56c6c;
    color: #f56c6c;
    font-size: 10px;
  }

  .manuals-dialog-container {
    margin-top: 50px !important;
    width: 75%;
    height: 80%;

    .el-dialog__body {
      padding: 10px;
      height: calc(100% - 50px) !important;
    }

    .el-dialog__header {
      position: relative;
    }
  }

  .manuals-full-dialog-container {
    .el-dialog__body {
      padding: 10px;
      height: calc(100% - 50px) !important;
    }

    .el-dialog__header {
      position: relative;
    }
  }
}
</style>
