<template>
  <BaseContainer class="visit-list">
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true" class="base-search-form">
        <!-- 中心编号 -->
<!--        <el-form-item :label="$t('trials:crcUpload:table:siteId')">-->
<!--          <el-select v-model="searchData.SiteId" clearable filterable style="width:120px;">-->
<!--            <el-option-->
<!--              v-for="(item,index) of siteOptions"-->
<!--              :key="index"-->
<!--              :label="item.TrialSiteCode"-->
<!--              :value="item.SiteId"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <!-- 受试者编号 -->
        <el-form-item :label="$t('trials:crcUpload:table:subjectId')">
          <el-input :maxLength="$inputMax" v-model="searchData.SubjectInfo" style="width:100px;" />
        </el-form-item>
        <!-- 访视名称 -->
        <el-form-item class="my_multiple" :label="$t('trials:crcUpload:table:visitName')">
          <el-select
            v-model="searchData.VisitPlanArray"
            clearable
            multiple
            style="width:140px"
          >
            <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="OutPlan"
              value="1.11"
            />
          </el-select>
        </el-form-item>

        <!-- 提交状态 -->
        <el-form-item :label="$t('trials:crcUpload:table:submitState')">
          <el-select v-model="searchData.SubmitState" clearable style="width:120px">
            <el-option v-for="item of $d.SubmitState" :value="item.value" :label="item.label" :key="item.label"/>
          </el-select>
        </el-form-item>
        <!-- 审核状态 -->
        <el-form-item v-if="otherInfo.QCProcessEnum !== 0" :label="$t('trials:crcUpload:table:auditState')">
          <el-select v-if="otherInfo.QCProcessEnum === 2" v-model="searchData.AuditStateArray" style="width:120px" multiple>
            <el-option v-for="(item, index) of $d.AuditStateRC" v-show="item.value <= 8" :value="item.value" :label="item.label"  :key="`AuditStateRC${item.label}${index}`"/>
          </el-select>
          <el-select v-if="otherInfo.QCProcessEnum === 1" v-model="searchData.AuditStateArray" style="width:120px" multiple>
            <el-option v-for="(item, index) of $d.AuditStatePE" v-show="item.value <= 8" :key="`AuditStatePE${item.label}${index}`" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <!-- 分配时间 -->
        <el-form-item style="margin-bottom:10px" :label="$t('trials:seletctedReviews:table:submissionTime')">
          <el-date-picker
            v-model="timeList"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            @change="changeTimeList"
          />
        </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>
      <span>
        <!-- 批量提交 -->
        <el-button
          v-hasPermi="['trials:trials-panel:visit:crc-upload:submit']"
          type="primary"
          icon="el-icon-check"
          :disabled="selectArr.length === 0"
          @click="handleBulkSubmit"
        >
          {{ $t('trials:crcUpload:button:submit') }}
        </el-button>
        <!-- 计划外访视 -->
        <el-button
          v-hasPermi="['trials:trials-panel:visit:crc-upload:new']"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          {{ $t('common:button:new') }}
        </el-button>
      </span>
    </template>

    <!-- 访视计划列表 -->
    <template slot="main-container">
      <el-table
        ref="visitList"
        v-loading="loading"
        v-adaptive="{bottomOffset:60}"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="left" width="45"  :selectable="handleSelectTable"/>
        <!-- 中心 -->
<!--        <el-table-column-->
<!--          prop="TrialSiteCode"-->
<!--          :label="$t('trials:crcUpload:table:siteId')"-->
<!--          show-overflow-tooltip-->
<!--          min-width="100"-->
<!--          sortable="custom"-->
<!--        />-->
        <!-- 受试者 -->
        <el-table-column
          prop="SubjectCode"
          :label="$t('trials:crcUpload:table:subjectId')"
          show-overflow-tooltip
          sortable="custom"
          min-width="120"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.SubjectCode }}</span>
          </template>
        </el-table-column>
        <!-- 访视 -->
        <el-table-column
          prop="VisitNum"
          :label="$t('trials:crcUpload:table:visitName')"
          show-overflow-tooltip
          min-width="160"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-button v-if="scope.row.VisitExecuted === 1" type="text" @click="handleOpenStudyDialog(scope.row)">
              <span>{{ scope.row.VisitName }}</span>
            </el-button>
            <span v-else>
              {{ scope.row.VisitName }}
            </span>
          </template>
        </el-table-column>
        <!-- 数据收集 -->
        <el-table-column
          prop="DicomStudyCount"
          :label="$t('trials:auditRecord:table:visit')"
          show-overflow-tooltip
          min-width="120"
        >
          <template slot-scope="scope">
            <el-tooltip placement="bottom">
              <div slot="content">
                <!-- DICOM/Non-DICOM/Clinical data -->
                <span>{{ $t('trials:crcUpload:label:dicom') }}: {{ scope.row.DicomStudyCount }}</span>
              </div>
              <span>
                {{ scope.row.DicomStudyCount }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 最早拍片日期 -->
        <el-table-column
          prop="EarliestScanDate"
          :label="$t('trials:crcUpload:table:earliestScanDate')"
          show-overflow-tooltip
          min-width="140"
          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:crcUpload:table:latestScanDate')"
          show-overflow-tooltip
          min-width="140"
          sortable="custom"
        >
          <template slot-scope="scope">
            {{ scope.row.LatestScanDate?moment(scope.row.LatestScanDate).format('YYYY-MM-DD'):'' }}
          </template>
        </el-table-column>
        <!-- 提交状态 -->
        <el-table-column
          prop="SubmitState"
          :label="$t('trials:crcUpload:table:submitState')"
          show-overflow-tooltip
          min-width="120"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.SubmitState*1 === 0" type="warning">{{ $fd('SubmitState', scope.row.SubmitState*1) }}</el-tag>
            <el-tag v-else-if="scope.row.SubmitState*1 === 1" type="danger">{{ $fd('SubmitState', scope.row.SubmitState*1) }}</el-tag>
            <el-tag v-else-if="scope.row.SubmitState*1 === 2">{{ $fd('SubmitState', scope.row.SubmitState*1) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 提交时间 -->
        <el-table-column
          prop="SubmitTime"
          :label="$t('trials:crcUpload:table:submitTime')"
          show-overflow-tooltip
          min-width="140"
          sortable="custom"
        />
        <el-table-column
          v-if="hasPermi(['trials:trials-panel:visit:crc-upload:upload', 'trials:trials-panel:visit:crc-upload:submit','trials:trials-panel:visit:crc-upload:edit','trials:trials-panel:visit:crc-upload:delete'], '||')"
          :label="$t('common:action:action')"
          width="250"
        >
          <template slot-scope="scope">
            <!-- 上传 -->
            <el-button
              v-hasPermi="['trials:trials-panel:visit:crc-upload:upload']"
              icon="el-icon-upload2"
              :disabled="scope.row.SubmitState*1 === 2 || scope.row.VisitExecuted === 2 ||scope.row.IsLostVisit"
              circle
              :title="$t('trials:crcUpload:action:upload')"
              @click="handleUpload(scope.row)"
            />
            <!-- 提交 -->
            <el-button
              v-hasPermi="['trials:trials-panel:visit:crc-upload:submit']"
              icon="el-icon-check"
              :disabled="scope.row.AuditState*1 > 0 || scope.row.SubmitState*1 !== 1 || scope.row.VisitExecuted === 2 ||scope.row.IsLostVisit"
              circle
              :title="$t('trials:crcUpload:action:submit')"
              @click="handleSubmit(scope.row)"
            />
            <!-- 编辑 -->
<!--            <el-button-->
<!--              v-hasPermi="['trials:trials-panel:visit:crc-upload:edit']"-->
<!--              icon="el-icon-edit-outline"-->
<!--              :disabled="scope.row.VisitExecuted === 2 || (scope.row.SubmitState*1 === 2 && scope.row.IsBaseLine === true)"-->
<!--              circle-->
<!--              :title="$t('trials:crcUpload:action:edit')"-->
<!--              @click="handleEdit(scope.row)"-->
<!--            />-->
            <!-- 删除 -->
            <el-button
              v-hasPermi="['trials:trials-panel:visit:crc-upload:delete']"
              icon="el-icon-delete"
              :disabled="scope.row.SubmitState*1 !== 0 || scope.row.InPlan ||scope.row.IsLostVisit || scope.row.IsFinalVisit"
              circle
              :title="$t('trials:crcUpload:action:delete')"
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" @pagination="getList" />
    </template>
    <!-- 新增/编辑 -->
    <el-dialog
      v-if="edit_cfg.visible"
      :visible.sync="edit_cfg.visible"
      :close-on-click-modal="false"
      :title="edit_cfg.title"
      width="600px"
      custom-class="base-dialog-wrapper"
    >
      <VisitForm v-if="edit_cfg.visible" :data="rowData" :other-info="otherInfo" @getList="getList" @closeDialog="closeEditDialog" />
    </el-dialog>

    <!-- 上传Dicom/非Dicom文件 -->
    <el-dialog
      v-if="uploadVisible"
      :visible.sync="uploadVisible"
      :fullscreen="true"
      :close-on-click-modal="false"
      custom-class="upload-dialog"
    >
      <span slot="title">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <label style="float: left;margin-right:10px;">Upload: </label>
          <!-- <el-breadcrumb-item>Upload</el-breadcrumb-item> -->
          <el-breadcrumb-item v-show="searchData.TrialCode">{{ searchData.TrialCode }}</el-breadcrumb-item>
<!--          <el-breadcrumb-item v-show="rowData.TrialSiteCode">{{ 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" style="display: flex;flex-direction: column;">
        <el-form
          v-show="(rowData.IsBaseLine && (otherInfo.IsHaveFirstGiveMedicineDate || otherInfo.IsEnrollementQualificationConfirm)) || (!rowData.IsBaseLine && otherInfo.IsPDProgressView)"
          :inline="true"
          class="base-search-form"
          style="height: 60px;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"
              :picker-options="pickerOption"
              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" :label="item.value" :key="`IsEnrollmentConfirm${item.label}`">{{ 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" :label="item.value" :key="`PDState${item.label}`">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-show="(rowData.IsBaseLine && (otherInfo.IsHaveFirstGiveMedicineDate || otherInfo.IsEnrollementQualificationConfirm)) || (!rowData.IsBaseLine && otherInfo.IsPDProgressView)">
            <!-- 编辑 -->
            <el-button
              v-hasPermi="['trials:trials-panel:visit:crc-upload:edit']"
              type="primary"
              icon="el-icon-edit"
              style="margin-left:10px;"
              @click="relationVisible = true"
            >
              {{ $t('common:button:edit') }}

            </el-button>
          </el-form-item>
        </el-form>
        <el-tabs v-model="activeName" type="border-card" style="flex:1;">
          <!-- DICOM影像上传 -->
          <el-tab-pane :label="$t('trials:uploadedDicoms:tab:uploadDicoms')" name="dicom">
            <upload-dicom-files :data="rowData" :subject-id="rowData.SubjectId" :subject-visit-id="rowData.Id" @getList="getList" @close="closeUpload" />
          </el-tab-pane>
          <!-- 非DICOM影像上传 -->
<!--          <el-tab-pane-->
<!--            :label="$t('trials:uploadNonDicoms:tab:uploadNonDicoms')"-->
<!--            name="non-dicom"-->
<!--          >-->
<!--            <upload-non-dicom-files v-if="activeName==='non-dicom'" :data="rowData" :body-parts="otherInfo.BodyPartTypes" :modalities="otherInfo.Modalitys" :subject-visit-id="rowData.Id" :allow-add-or-edit="true" @getList="getList" />-->
<!--          </el-tab-pane>-->
          <!-- 临床数据采集 -->
          <el-tab-pane
            v-if="rowData.IsBaseLine && otherInfo.ClinicalInformationTransmissionEnum > 0 && otherInfo.IsHaveSubjectClinicalData"
            :label="$t('trials:uploadClinicalData:tab:uploadClinicalData')"
            name="clinical-data"
          >
            <upload-clinical-data v-if="activeName==='clinical-data'" :subject-visit-id="rowData.Id" :data="rowData" :enum-type="otherInfo.ClinicalInformationTransmissionEnum" :allow-add-or-edit="true" @getList="getList" />
          </el-tab-pane>
          <!-- 临床数据采集2 -->
          <el-tab-pane
            v-if="!rowData.IsBaseLine && otherInfo.ClinicalInformationTransmissionEnum > 0 && otherInfo.IsHaveVisitClinicalData"
            :label="$t('trials:uploadClinicalData:tab:uploadClinicalData')"
            name="clinical-data"
          >
            <upload-clinical-data v-if="activeName==='clinical-data'" :subject-visit-id="rowData.Id" :data="rowData" :enum-type="otherInfo.ClinicalInformationTransmissionEnum" :allow-add-or-edit="true" @getList="getList" />
          </el-tab-pane>
        </el-tabs>
      </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.TrialSiteCode">{{ 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"
              :picker-options="pickerOption"
              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" :label="item.value" :key="`IsEnrollmentConfirm${item.label}`">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 疾病进展确认评估 -->
          <el-form-item
            v-show="!rowData.IsBaseLine && otherInfo.IsPDProgressView || rowData.PDState === 1"
            :label="$t('trials:crcUpload:form:pd')"
          >
            <el-radio-group v-model="rowData.PDState" disabled>
              <el-radio v-for="item of $d.YesOrNoForInt" :label="item.value" :key="`PDState${item.label}`">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <!-- DICOM影像  -->
        <h4 class="box-title">{{ $t('trials:crcUpload:label:dicom') }}</h4>
        <el-card class="box-card">
          <StudyInfo v-if="rowData.Id" :data="rowData" @getList="getList" />
        </el-card>
<!--        &lt;!&ndash; 非DICOM影像 &ndash;&gt;-->
<!--        <h4 class="box-title" style="margin-top:10px;">{{ $t('trials:crcUpload:label:noneDicom') }}</h4>-->
<!--        <el-card class="box-card">-->
<!--          <UploadNonDicomFiles v-if="rowData.Id" :data="rowData" :subject-visit-id="rowData.Id" :body-parts="otherInfo.BodyPartTypes" :modalities="otherInfo.Modalitys" :allow-add-or-edit="false" @getList="getList" />-->
<!--        </el-card>-->
        <!-- 临床数据 -->
        <h4 v-if="rowData.IsBaseLine && otherInfo.ClinicalInformationTransmissionEnum > 0 && otherInfo.IsHaveSubjectClinicalData" class="box-title" style="margin-top:10px;">
          {{ $t('trials:crcUpload:label:clinicalData') }}
        </h4>
        <el-card v-if="rowData.IsBaseLine && otherInfo.ClinicalInformationTransmissionEnum > 0 && otherInfo.IsHaveSubjectClinicalData" class="box-card">
          <UploadClinicalData v-if="rowData.Id && rowData.IsBaseLine" :enum-type="otherInfo.ClinicalInformationTransmissionEnum" :allow-add-or-edit="false" :data="rowData" :subject-visit-id="rowData.Id" @getList="getList" />
        </el-card>
        <h4 v-if="!rowData.IsBaseLine && otherInfo.ClinicalInformationTransmissionEnum > 0 && otherInfo.IsHaveVisitClinicalData" class="box-title" style="margin-top:10px;">
          {{ $t('trials:crcUpload:label:clinicalData') }}
        </h4>
        <el-card v-if="!rowData.IsBaseLine && otherInfo.ClinicalInformationTransmissionEnum > 0 && otherInfo.IsHaveVisitClinicalData" class="box-card">
          <UploadClinicalData v-if="rowData.Id" :enum-type="otherInfo.ClinicalInformationTransmissionEnum" :allow-add-or-edit="false" :data="rowData" :subject-visit-id="rowData.Id" @getList="getList" />
        </el-card>
      </div>
    </el-dialog>

    <!-- 历史质疑 -->
    <base-model :config="chat_cfg">
      <template slot="dialog-body">
        <HistoryChat v-if="rowData.Id" :data="rowData" :body-parts="otherInfo.BodyPartTypes" :modalities="otherInfo.Modalitys" :clinical-enum="otherInfo.ClinicalInformationTransmissionEnum" @getList="getList" />
      </template>
    </base-model>

    <!-- 编辑访视基准日期、入组合格性确认、PD进展 -->
    <el-dialog
      v-if="relationVisible"
      :visible.sync="relationVisible"
      :close-on-click-modal="false"
      :title="$t('trials:crcUpload:dialogTitle:edit')"
      width="500px"
      style="height:600px"
      custom-class="base-dialog-wrapper"
      append-to-body
    >
      <el-form size="small">
        <div class="base-dialog-body">
          <!-- 访视基准日期 -->
          <el-form-item
            v-if="rowData.IsBaseLine&& otherInfo.IsHaveFirstGiveMedicineDate"
            :label="$t('trials:crcUpload:form:baseDateOfVisit')"
          >
            <el-date-picker
              v-model="rowData.SubjectFirstGiveMedicineTime"
              type="date"
              :picker-options="pickerOption"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
          </el-form-item>
          <!-- 入组确认评估 -->
          <el-form-item
            v-if="rowData.IsBaseLine && otherInfo.IsEnrollementQualificationConfirm"
            :label="$t('trials:crcUpload:form:enrollmentConfirmation')"
          >
            <el-radio-group v-model="rowData.IsEnrollmentConfirm">
              <el-radio v-for="item of $d.YesOrNo" :label="item.value" :key="`IsEnrollmentConfirm${item.label}`">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 疾病进展确认评估 -->
          <el-form-item
            v-if="!rowData.IsBaseLine && otherInfo.IsPDProgressView"
            :label="$t('trials:crcUpload:form:pd')"
          >
            <el-radio-group v-model="rowData.PDState">
              <el-radio v-for="item of $d.YesOrNoForInt" :label="item.value" :key="`PDState${item.label}`">{{ 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 size="small" type="primary" :disabled="btnLoading" @click="relationVisible = false">
              {{ $t('common:button:cancel') }}
            </el-button>
            <el-button size="small" type="primary" :loading="btnLoading" @click="saveRelationInfo">
              {{ $t('common:button:save') }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>

    <!-- 临床数据签名框 -->
    <el-dialog
      v-if="signVisible"
      :visible.sync="signVisible"
      :close-on-click-modal="false"
      width="600px"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <div slot="title">
        <span style="font-size:18px;">{{ $t('common:dialogTitle:sign') }}</span>
        <span style="font-size:12px;margin-left:5px">{{ `(${$t('common:label:sign')}${ currentUser })` }}</span>
      </div>
      <SignForm ref="signForm" :sign-code-enum="signCode" :subject-visit-id="rowData.Id" @closeDialog="closeSignDialog" />
    </el-dialog>
    <el-dialog
      v-if="SubjectVisible"
      :visible.sync="SubjectVisible"
      :close-on-click-modal="false"
      width="600px"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <div slot="title">
        <span style="font-size:18px;">{{ $t('trials:crcUpload:dialogTitle:edit') }}</span>
      </div>
      <div style="color:#f66;margin-bottom: 20px;margin-left: 40px;">
        <!-- 该受试者访视基准日期未填写，请补充后，再提交访视影像。 -->
        {{ $t('trials:crcUpload:message:baseDate') }}
      </div>
      <!-- <SubjectsForm :data="SubjectInfo" :other-info="otherInfo" @submit="handleSubmit(rowData, true)" /> -->
      <SubjectsForm v-if="SubjectVisible" :data="SubjectInfo" :other-info="otherInfo" @submitFirstGiveMedicineTime="submitFirstGiveMedicineTime" @close="closeSubjectVisible" />
    </el-dialog>
  </BaseContainer>
</template>
<script>
import {
  getCRCVisitList,
  getTrialSiteSelect,
  getTrialVisitStageSelect, verifyCRCRequestToQC, deleteSubjectVisit, updateSubjectAndSVInfo } from '@/api/trials'
import { cRCRequestToQC } from '@/api/trials/visit'
import { cRCVisitList_Export } from '@/api/export'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import VisitForm from './components/visitForm'
import UploadDicomFiles from './components/uploadDicomFiles'
import UploadNonDicomFiles from './components/uploadNonDicomFiles'
import UploadClinicalData from './components/uploadClinicalData'
import HistoryChat from './components/historyChat'
import StudyInfo from './components/studyInfo'
import SubjectsForm from './components/SubjectsForm'
import SignForm from '@/views/trials/components/newSignForm'
import BaseModel from '@/components/BaseModel'
import dicomStore from '@/utils/dicom-store'
import moment from 'moment'
import const_ from '@/const/sign-code'
import { changeURLStatic } from '@/utils/history.js'
import { getToken } from '@/utils/auth'
const searchDataDefault = () => {
  return {
    SubjectInfo: '',
    SiteId: '',
    PageIndex: 1,
    PageSize: 20,
    VisitPlanArray: [],
    AuditStateArray: [],
    SubmitState: null,
    ChallengeState: null,
    BeginSubmitTime: null,
    EndSubmitTime: null
    // SortField: '',
    // Asc: false
  }
}
export default {
  name: 'VisitList',
  components: { BaseContainer, Pagination, BaseModel, SignForm, VisitForm, UploadDicomFiles, UploadNonDicomFiles, UploadClinicalData, HistoryChat, StudyInfo, SubjectsForm },
  data() {
    return {
      timeList: [],
      edit_cfg: { visible: false, title: '', width: '600px', showClose: true },
      SubjectVisible: false,
      searchData: searchDataDefault(),
      loading: false,
      uploadVisible: false,
      qcVisible: false,
      list: [],
      total: 0,
      siteOptions: [],
      visitPlanOptions: [],
      rowData: {},
      moment,
      activeName: 'dicom',
      studyVisible: false,
      studyLoading: false,
      studyList: [],
      deleteArr: [],
      currentVisitId: '',
      urgentForm: { isUrgent: null },
      btnLoading: false,
      chat_cfg: { visible: false, title: '', width: '1000px', showClose: true },
      relationVisible: false,
      otherInfo: {},
      SubjectInfo: {},
      selectArr: [],
      signVisible: false,
      signCode: null,
      currentUser: zzSessionStorage.getItem('userName'),
      pickerOption: {
        disabledDate: time => {
          return time.getTime() > Date.now()
        }
      },
      trialId: this.$route.query.trialId
    }
  },
  watch: {
    list() {
      this.$nextTick(() => {
        this.$refs.visitList.doLayout()
      })
    }
  },
  mounted() {
    this.getSite()
    if (this.$route.query.subjectCode) {
      this.searchData.SubjectInfo = this.$route.query.subjectCode
    }
    changeURLStatic('subjectCode', '')
    this.getList()
    this.getVisitPlanOptions()
  },
  methods: {
    // 通过提交状态决定该行的 CheckBox 是否可以勾选
    handleSelectTable(row) {
        return row.SubmitState === 1
    },
    changeTimeList() {
      if (this.timeList) {
        this.searchData.BeginSubmitTime = this.timeList[0]
        this.searchData.EndSubmitTime = this.timeList[1]
      } else {
        this.searchData.BeginSubmitTime = null
        this.searchData.EndSubmitTime = null
      }
    },
    handleExport() {
      cRCVisitList_Export(this.searchData).then(res => {
      }).catch(() => { this.loading = false })
    },
    // 获取访视计划列表
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      getCRCVisitList(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 })
    },
    // 新建计划外的访视信息
    handleAdd() {
      this.rowData = {}
      this.edit_cfg.title = this.$t('trials:crcUpload:dialogTitle:new')
      this.edit_cfg.visible = true
    },
    // 编辑访视信息
    handleEdit(row) {
      this.rowData = row
      this.edit_cfg.title = this.$t('trials:crcUpload:dialogTitle:edit')
      this.edit_cfg.visible = true
    },
    closeEditDialog() {
      this.edit_cfg.visible = false
    },
    // 预览影像
    handleView(row) {
      var tokenKey = getToken()
      const routeData = this.$router.resolve({
        path: `/showvisitdicoms?trialId=${row.TrialId}&visitInfo=${row.VisitName}(${row.VisitNum})&subjectVisitId=${row.Id}&TokenKey=${tokenKey}`
      })
      window.open(routeData.href, '_blank')
    },
    // 上传Dicoms/非Dicoms文件
    handleUpload(row) {
      dicomStore.studyList = []
      this.activeName = 'dicom'
      this.rowData = { ...row }
      this.uploadVisible = true
    },
    // 将影像提交给QC
    handleSubmit(row) {
      this.rowData = { ...row }
      // if (row.IsBaseLine) {
      //   if (this.otherInfo.ClinicalInformationTransmissionEnum > 0) {
      //     const { ClinicalDataConfirmation } = const_.processSignature
      //     this.signCode = ClinicalDataConfirmation
      //     this.signVisible = true
      //   } else {
      //     this.submit()
      //   }
      // } else {
      // 校验是否可提交
        this.verifyIsAllowSubmit()
      // }
    },
    verifyIsAllowSubmit() {
      this.loading = true
      var param = {
        trialId: this.trialId,
        subjectVisitIds: [this.rowData.Id]
      }
      verifyCRCRequestToQC(param).then(res => {
        this.loading = false
        if (res.IsSuccess) {
          this.$confirm(this.$t('trials:crcUpload:message:submit'), {
            type: 'warning',
            distinguishCancelAndClose: true
          })
            .then(() => {
              if (this.rowData.IsBaseLine) {
                if (this.otherInfo.ClinicalInformationTransmissionEnum > 0) {
                  const { ClinicalDataConfirmation } = const_.processSignature
                  this.signCode = ClinicalDataConfirmation
                  this.signVisible = true
                } else {
                  this.submit()
                }
              } else {
                this.checkNeedSignAndSubmit()
              }
            }).catch(() => {})
        }
      }).catch(res => {
        this.loading = false
        if (res.Result === 1) {
          this.$confirm(res.ErrorMessage, {
            showCancelButton: false,
            showConfirmButton: false,
            type: 'warning'
          })
        } else if (res.Result === 0) {
          this.$confirm(res.ErrorMessage, {
            distinguishCancelAndClose: true,
            type: 'warning'
          }).then(() => {
            this.checkNeedSignAndSubmit()
          }).catch(() => {})
        }
      })
    },
    checkNeedSignAndSubmit() {
      if (this.otherInfo.IsHaveFirstGiveMedicineDate && (this.rowData.SubjectFirstGiveMedicineTime === null || this.rowData.SubjectFirstGiveMedicineTime === '') && !this.rowData.IsBaseLine) {
        var item = Object.assign({}, this.rowData)
        item.Code = this.rowData.SubjectCode
        item.Id = this.rowData.SubjectId
        this.SubjectInfo = item
        this.SubjectVisible = true
      } else {
        if (this.otherInfo.ClinicalInformationTransmissionEnum > 0 && this.rowData.IsBaseLine) {
          const { ClinicalDataConfirmation } = const_.processSignature
          this.signCode = ClinicalDataConfirmation
          this.signVisible = true
        } else {
          this.submit()
        }
      }
    },
    submitFirstGiveMedicineTime(firstGiveMedicineTime) {
      this.rowData.SubjectFirstGiveMedicineTime = firstGiveMedicineTime
      this.SubjectVisible = false
      this.checkNeedSignAndSubmit()
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.submit(signInfo)
      } else {
        this.signVisible = false
      }
    },
    submit(signInfo) {
      this.loading = true
      var params = {
        data: { trialId: this.trialId, subjectVisitIds: [this.rowData.Id] }
      }
      if (signInfo) {
        params.signInfo = signInfo
      }
      cRCRequestToQC(params)
        .then(res => {
          this.loading = false
          if (res.IsSuccess) {
            if (signInfo) {
              this.$refs['signForm'].btnLoading = false
              this.signVisible = false
            }
            this.getList()
            this.$message.success(this.$t('trials:crcUpload:message:submittedSuccessfully'))
          }
        }).catch((res) => {
          this.loading = false
          if (res.Result === 3) {
            this.getList()
            this.signVisible = false
            this.$confirm(res.ErrorMessage, {
              showCancelButton: false,
              showConfirmButton: true,
              type: 'warning'
            })
          } else {
            if (signInfo) {
              this.$refs['signForm'].btnLoading = false
            }
          }
        })
    },
    // 将影像批量提交给QC
    handleBulkSubmit() {
      this.$confirm(this.$t('trials:crcUpload:message:bulkSubmit'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          var params = {
            data: { trialId: this.trialId, subjectVisitIds: this.selectArr }
          }
          cRCRequestToQC(params)
            .then(res => {
              if (res.IsSuccess) {
                this.getList()
                this.$message.success(this.$t('trials:crcUpload:message:submittedSuccessfully'))
              }
            }).catch((res) => {
              this.loading = false
              if (res.Result === 3) {
                this.$confirm(res.ErrorMessage, {
                  showCancelButton: false,
                  showConfirmButton: true,
                  type: 'warning'
                })
              }
              this.getList()
            })
        }).catch(() => {})
    },
    // 获取某个访视下的检查信息
    handleOpenStudyDialog(row) {
      this.studyVisible = true
      this.currentVisitId = row.Id
      this.rowData = { ...row }
    },
    // 关闭上传弹框
    closeUpload() {
      this.uploadVisible = false
    },
    // 打开历史质疑记录
    handleOpenHistoryChat(row) {
      this.rowData = { ...row }
      this.chat_cfg.title= `${this.$t('trials:crcUpload:dialogTitle:qsRecord')} (${row.SubjectCode} ${row.VisitName})`
      this.chat_cfg.visible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm(this.$t('trials:crcUpload:message:deleteVisit'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          deleteSubjectVisit(this.trialId, row.Id)
            .then(res => {
              if (res.IsSuccess) {
                // this.list.splice(this.list.findIndex(item => item.Id === row.Id), 1)
                this.getList()
                this.$message.success(this.$t('trials:crcUpload:message:deleteVisitSuccessfully'))
              }
              this.loading = false
            }).catch(() => { this.loading = false })
        })
    },
    // 重置
    handleReset() {
      this.timeList = []
      this.searchData = searchDataDefault()
      this.getList()
    },
    closeSubjectVisible() {
      this.SubjectVisible = false
    },
    // 查询
    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
        })
    },
    // 保存关联信息
    saveRelationInfo() {
      this.btnLoading = true
      const param = {
        subjectVisitId: this.rowData.Id,
        subjectId: this.rowData.SubjectId,
        pdState: this.rowData.PDState,
        isEnrollmentConfirm: this.rowData.IsEnrollmentConfirm,
        subjectFirstGiveMedicineTime: this.rowData.SubjectFirstGiveMedicineTime
      }
      updateSubjectAndSVInfo(this.trialId, param)
        .then(res => {
          this.btnLoading = false
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.relationVisible = false
          this.getList()
        }).catch(() => { this.btnLoading = false })
    },
    // 通过提交状态决定该行的 CheckBox 是否可以勾选
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      const arr = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].Id)
      }
      this.selectArr = arr
    }
  }
}
</script>
<style lang="scss">
.visit-list{
  position: relative;
  .status-primary-circle{
    display: inline-block;
    width:20px;
    height:20px;
    text-align: center;
    line-height: 18px;
    border-radius: 50%;
    // background: #f56c6c;
    border: 1px solid #f56c6c;
    color:#f56c6c;
    font-size: 10px;
  }
  .remark{
    position: absolute;
    left: 5px;
    bottom: 7px;
    font-size: 12px;
  }
  .box-title{
    padding: 12px;
    margin-bottom: 10px;
    background-color: #dcdfe6;
  }
  .is-circle-urgent-red{
    border-radius: 50%;
    padding: 7px;
    line-height: 1;
    background-color: #f56c6c;
    width: 28px;
    color: #fff;
    border: 1px solid #DCDFE6;
  }
  .is-circle-urgent{
    border-radius: 50%;
    padding: 7px;
    line-height: 1;
    width: 28px;
    border: 1px solid #DCDFE6;
    font-size: 12px;
  }

}
</style>
