<template>
  <div v-loading="loading" class="clinical-data-wrapper">
    <el-tabs type="border-card" v-model="activeName" @tab-click="tabClick">
      <el-tab-pane 
        v-for="cd in clinicalDatas" 
        :key="cd.ClinicalDataTrialSetId" 
        :label="$i18n.locale === 'zh' ? cd.ClinicalDataSetName: cd.ClinicalDataSetEnName"
        :name="cd.ClinicalDataTrialSetId"
      >
        <!-- 格式化录入 -->
        <div v-if="cd.ClinicalUploadType === 0">
          <!-- 既往放疗史 -->
          <h4>{{ $t('trials:uploadClinicalData:title:pastTreatment') }}</h4>
          <div v-if="allowAddOrEdit" style="text-align: right">
            <!-- 新增 -->
            <el-button type="primary" icon="el-icon-plus" size="small" @click.native.prevent="
              addPreviousHistory(cd.ClinicalDataTrialSetId)
              ">
              {{ $t('common:button:new') }}
            </el-button>
          </div>

          <el-table :data="cd.ClinicalTableData.PreviousHistoryList" style="width: 100%">
            <el-table-column type="index" width="50" />
            <!-- 放疗部位 -->
            <el-table-column prop="Position" :label="$t('trials:uploadClinicalData:table:bodyPart')" />
            <!-- 开始日期 -->
            <el-table-column prop="StartTime" :label="$t('trials:uploadClinicalData:table:beginDate')">
              <template slot-scope="scope">
                {{
                  scope.row.StartTime
                    ? moment(scope.row.StartTime).format('YYYY-MM-DD')
                    : ''
                }}
              </template>
            </el-table-column>
            <!-- 结束日期 -->
            <el-table-column prop="EndTime" :label="$t('trials:uploadClinicalData:table:endDate')">
              <template slot-scope="scope">
                {{
                  scope.row.EndTime
                    ? moment(scope.row.EndTime).format('YYYY-MM-DD')
                    : ''
                }}
              </template>
            </el-table-column>
            <!-- 病灶是否PD -->
            <el-table-column prop="IsPD" :label="$t('trials:uploadClinicalData:table:isPD')">
              <template slot-scope="scope">
                {{ $fd('IsPdEnum', scope.row.IsPD) }}
              </template>
            </el-table-column>
            <el-table-column v-if="allowAddOrEdit" :label="$t('common:action:action')" min-width="120">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button v-if="allowAddOrEdit" icon="el-icon-edit-outline" circle :title="$t('common:button:edit')"
                  size="small" @click.native.prevent="editRow(scope.row, 1)" />
                <!-- 移除 -->
                <el-button v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                " icon="el-icon-delete" circle :title="$t('common:button:delete')" size="small"
                  @click.native.prevent="deletePreviousHistory(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <!-- 既往手术史 -->
          <h4>{{ $t('trials:uploadClinicalData:title:pastSurgery') }}</h4>
          <div v-if="allowAddOrEdit" style="text-align: right">
            <el-button type="primary" icon="el-icon-plus" size="small"
              @click="addPreviousSurgery(cd.ClinicalDataTrialSetId)">
              {{ $t('common:button:new') }}
            </el-button>
          </div>
          <el-table :data="cd.ClinicalTableData.PreviousSurgeryList" style="width: 100%">
            <el-table-column type="index" width="50" />
            <!-- 手术名称 -->
            <el-table-column prop="OperationName" :label="$t('trials:uploadClinicalData:table:surgeryName')" />
            <!-- 手术日期 -->
            <el-table-column prop="OperationTime" :label="$t('trials:uploadClinicalData:table:surgeryDate')">
              <template slot-scope="scope">
                {{
                  scope.row.OperationTime
                    ? moment(scope.row.OperationTime).format('YYYY-MM-DD')
                    : ''
                }}
              </template>
            </el-table-column>

            <el-table-column v-if="allowAddOrEdit" :label="$t('common:action:action')" min-width="200">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button v-if="allowAddOrEdit" icon="el-icon-edit-outline" circle :title="$t('common:button:edit')"
                  size="small" @click.native.prevent="editRow(scope.row, 2)" />
                <!-- 移除 -->
                <el-button v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                " icon="el-icon-delete" circle :title="$t('common:button:delete')" size="small"
                  @click.native.prevent="deletePreviousSurgery(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <!-- 既往其他治疗史 -->
          <h4>{{ $t('trials:uploadClinicalData:title:others') }}</h4>
          <div v-if="allowAddOrEdit" style="text-align: right">
            <!-- 新增 -->
            <el-button type="primary" icon="el-icon-plus" size="small"
              @click="addPreviousOther(cd.ClinicalDataTrialSetId)">
              {{ $t('common:button:new') }}
            </el-button>
          </div>
          <el-table :data="cd.ClinicalTableData.PreviousOtherList" style="width: 100%">
            <el-table-column type="index" width="50" />
            <!-- 治疗类型 -->
            <el-table-column prop="TreatmentType" :label="$t('trials:uploadClinicalData:table:treatmentType')" />
            <!-- 开始日期 -->
            <el-table-column prop="StartTime" :label="$t('trials:uploadClinicalData:table:treatmentbeginDate')">
              <template slot-scope="scope">
                {{
                  scope.row.StartTime
                    ? moment(scope.row.StartTime).format('YYYY-MM-DD')
                    : ''
                }}
              </template>
            </el-table-column>
            <!-- 结束日期 -->
            <el-table-column prop="EndTime" :label="$t('trials:uploadClinicalData:table:treatmentendDate')">
              <template slot-scope="scope">
                {{
                  scope.row.EndTime
                    ? moment(scope.row.EndTime).format('YYYY-MM-DD')
                    : ''
                }}
              </template>
            </el-table-column>

            <el-table-column v-if="allowAddOrEdit" :label="$t('common:action:action')" min-width="200">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button v-if="allowAddOrEdit" icon="el-icon-edit-outline" circle :title="$t('common:button:edit')"
                  size="small" @click.native.prevent="editRow(scope.row, 3)" />
                <!-- 移除 -->
                <el-button v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                " icon="el-icon-delete" circle :title="$t('common:button:delete')" size="small"
                  @click.native.prevent="deletePreviousOther(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- PDF录入 -->
        <div v-if="cd.ClinicalUploadType === 1">
          <div v-if="allowAddOrEdit" style="text-align: right; display: flex; justify-content: flex-end">
            <!-- 下载模板 -->
            <el-button v-if="cd.Path" type="primary" icon="el-icon-download" size="small" :loading="downloadLoading"
              @click.native.prevent="handleDownloadTpl(cd)" style="margin-right: 10px">
              {{ $t('trials:uploadClinicalData:button:downloadTemplate') }}
            </el-button>
            <!-- 新增 -->
            <!-- <el-button
              icon="el-icon-plus"
              type="primary"
              size="small"
              @click.native.prevent="addFile(cd.Id, cd.ClinicalDataTrialSetId)"
            >
              {{ $t("common:button:new") }}
            </el-button> -->
            <!-- 新增 -->
            <div style="position: relative">
              <el-button icon="el-icon-plus" type="primary" size="small" :disabled="btnLoading" :loading="btnLoading">
                {{ $t('common:button:new') }}
              </el-button>
              <input type="file" name="file" multiple ref="addFile" :title="$t('common:button:new')" style="
                  position: absolute;
                  top: 0;
                  left: 0;
                  width: 100%;
                  height: 100%;
                  opacity: 0;
                  cursor: pointer;
                " :accept="faccept.join(',')" @change="
                  ($event) =>
                    beginScanFiles($event, cd.Id, cd.ClinicalDataTrialSetId)
                " />
            </div>
          </div>
          <el-table :data="cd.PDFFileList" style="width: 100%" height="300">
            <el-table-column type="index" width="50" />
            <!-- 文件名称 -->
            <el-table-column prop="FileName" :label="$t('trials:uploadClinicalData:table:fileName')" width="250" />
            <!-- 文件大小 -->
            <el-table-column prop="Size" :label="$t('trials:uploadClinicalData:table:fileSize')" width="150">
              <template slot-scope="scope">
                <span>{{
                  $FormatSize(scope.row.Size)
                }}</span>
              </template>
            </el-table-column>
            <!-- 上传时间 -->
            <el-table-column prop="CreateTime" :label="$t('trials:uploadClinicalData:table:uploadedTime')"
              width="200" />
            <el-table-column :label="$t('common:action:action')" width="200">
              <template slot-scope="scope">
                <!-- 预览 -->
                <el-button icon="el-icon-view" circle :title="$t('trials:uploadClinicalData:action:preview')"
                  size="small" @click.native.prevent="preview(scope.row)" />
                <!-- 移除 -->
                <el-button v-if="allowAddOrEdit" icon="el-icon-delete" circle :title="$t('common:button:delete')"
                  size="small" @click.native.prevent="deleteFile(scope.row.Id)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- PDF录入 -->
        <div v-if="cd.ClinicalUploadType === 2">
          <clinicalDataQuestions v-if="cd.ClinicalFromList.length > 0" :data="cd"
            :trial-clinical-id="cd.ClinicalDataTrialSetId" :is-viewer="false" :visit-id="subjectVisitId"
            :subject-id="data.SubjectId" :trial-id="trialId" :clinical-form-id="cd.ClinicalFromList[0].ClinicalFormId"
            :open-type="allowAddOrEdit ? 'edit' : 'look'" @close="getClinicalData" />
          <clinicalDataQuestions v-else :data="cd" :trial-clinical-id="cd.ClinicalDataTrialSetId"
            :is-viewer="!allowAddOrEdit" :visit-id="subjectVisitId" :subject-id="data.SubjectId" :trial-id="trialId"
            :open-type="'add'" @close="getClinicalData" />
        </div>
      </el-tab-pane>
      <!-- 患者数据 -->
      <el-tab-pane :label="$t('trials:tab:patientData')" name="patientForm">
        <el-form
          ref="patientForm"
          :model="formData"
          :rules="rules"
          label-width="100"
          v-loading="formLoading"
        >
          <div class="form-row">
            <!-- 性别 -->
            <el-form-item class="form-item-half" :label="$t('trials:ptData:label:patientSex')" prop="PatientSex">
              <el-select
                v-model="formData.PatientSex"
                :placeholder="$t('common:ruleMessage:select')"
                style="width: 100%"
                :disabled="!isPatientFormCanEdit"
              >
                <el-option :label="$t('trials:patientSex:male')" value="M"></el-option>
                <el-option :label="$t('trials:patientSex:female')" value="F"></el-option>
              </el-select>
            </el-form-item>
            <!-- 体重（kg） 例如 70.5-->
            <el-form-item class="form-item-half" :label="$t('trials:ptData:label:patientWeight')" prop="PatientWeight">
              <el-input
                v-model.number="formData.PatientWeight"
                :placeholder="$t('trials:patientWeight:eg')"
                style="width: 100%"
                :disabled="!isPatientFormCanEdit"
              ></el-input>
            </el-form-item>
          </div>
          <div class="form-row">
            <!-- 总剂量（Bq） 例如 740000000-->
            <el-form-item class="form-item-half" :label="$t('trials:ptData:label:totalDose')" prop="RadionuclideTotalDose">
              <el-input
                v-model.number="formData.RadionuclideTotalDose"
                :placeholder="$t('trials:totalDose:eg')"
                style="width: 100%"
                :disabled="!isPatientFormCanEdit"
              ></el-input>
            </el-form-item>
            <!-- 半衰期（s） 例如 21600-->
            <el-form-item class="form-item-half" :label="$t('trials:ptData:label:halfLife')" prop="RadionuclideHalfLife">
              <el-input
                v-model.number="formData.RadionuclideHalfLife"
                :placeholder="$t('trials:halfLife:eg')"
                style="width: 100%"
                :disabled="!isPatientFormCanEdit"
              ></el-input>
            </el-form-item>
          </div>
          <div class="form-row">
            <!-- 注射时间 HHMMSS-->
            <el-form-item class="form-item-half" :label="$t('trials:ptData:label:injectTime')" prop="RadiopharmaceuticalStartTime">
              <el-input
                v-model.trim="formData.RadiopharmaceuticalStartTime"
                :placeholder="$t('trials:injectTime:eg')"
                style="width: 100%"
                @input="computeTimeRelation"
                @blur="handleTimeBlur('RadiopharmaceuticalStartTime')"
                maxlength="6"
                :disabled="!isPatientFormCanEdit"
              ></el-input>
            </el-form-item>
            <!-- 成像时间 HHMMSS-->
            <el-form-item class="form-item-half" :label="$t('trials:ptData:label:acquisitionTime')" prop="AcquisitionTime">
              <el-input
                v-model.trim="formData.AcquisitionTime"
                :placeholder="$t('trials:injectTime:eg')"
                style="width: 100%"
                @input="computeTimeRelation"
                @blur="handleTimeBlur('AcquisitionTime')"
                maxlength="6"
                :disabled="!isPatientFormCanEdit"
              ></el-input>
            </el-form-item>
          </div>

          <!-- 时间一致性检查 -->
          <el-form-item :label="$t('trials:ptData:label:timeCheck')">
            <el-input
              v-model="formData.TimeCheck"
              disabled
              style="width: 100%"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="isAudit" :label="$t('trials:ptData:label:reason')" prop="Reason">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              v-model="formData.Reason"
              style="width: 100%"
            ></el-input>
          </el-form-item>
          <!-- 提交 -->
          <el-form-item style="margin-top: 20px;text-align: right;" v-if="isPatientFormCanEdit">
            <el-button type="primary" @click="submitForm">{{ $t('trials:ptData:button:submit') }}</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 既往放疗史 -->
    <el-dialog v-if="prVisible" :visible.sync="prVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadClinicalData:title:pastTreatment')" width="600px" append-to-body
      custom-class="base-dialog-wrapper">
      <PreviousRadiotherapy v-if="prVisible" :data="currentRow" :subject-visit-id="subjectVisitId"
        @closePRDialog="closePRDialog" @refresh="refresh" />
    </el-dialog>
    <!-- 既往手术史  -->
    <el-dialog v-if="psVisible" :visible.sync="psVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadClinicalData:title:pastSurgery')" width="600px" append-to-body
      custom-class="base-dialog-wrapper">
      <PreviousSurgery v-if="psVisible" :data="currentRow" :parent-data="data" :subject-visit-id="subjectVisitId"
        @closePSDialog="closePSDialog" @refresh="refresh" />
    </el-dialog>
    <!-- 既往其他治疗史 -->
    <el-dialog v-if="poVisible" :visible.sync="poVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadClinicalData:title:others')" width="600px" append-to-body
      custom-class="base-dialog-wrapper">
      <PreviousOther v-if="poVisible" :data="currentRow" :parent-data="data" :subject-visit-id="subjectVisitId"
        @closePODialog="closePODialog" @refresh="refresh" />
    </el-dialog>
    <!-- 上传文件 -->
    <el-dialog v-if="upVisible" :visible.sync="upVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadClinicalData:title:uploadFile')" width="600px" append-to-body
      custom-class="base-dialog-wrapper">
      <PreviousFiles v-if="upVisible" :data="currentRow" :parent-data="data" :subject-visit-id="subjectVisitId"
        :studyData="studyData" @closeUpDialog="closeUpDialog" @refresh="refresh" />
    </el-dialog>
    <!-- 预览文件 -->
    <el-dialog v-if="previewObj.visible" :visible.sync="previewObj.visible" :title="previewObj.fileName"
      :fullscreen="true" append-to-body custom-class="base-dialog-wrapper">
      <div class="base-modal-body" style="border: 2px solid #ccc; padding: 10px">
        <PreviewFile v-if="previewObj.visible" :file-path="previewObj.filePath" :file-type="previewObj.fileType" />
      </div>
    </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="subjectVisitId"
        @closeDialog="closeSignDialog" />
    </el-dialog>
  </div>
</template>
<script>
import {
  deleteReadingClinicalDataPDF,
  deletePreviousHistory,
  deletePreviousOther,
  deletePreviousSurgery,
  getCRCClinicalData,
  addOrUpdateReadingClinicalData,
  getPatientInfo,
  editPatientInfo,
  amendmentPatientInfo
} from '@/api/trials'
import PreviousRadiotherapy from './previousRadiotherapy'
import PreviousSurgery from './previousSurgery'
import PreviousOther from './previousOther'
import PreviousFiles from './previousFiles'
import clinicalDataQuestions from '@/components/clinicalDataQuestions'
import PreviewFile from '@/components/PreviewFile/index'
import SignForm from '@/views/trials/components/newSignForm'
import moment from 'moment'
import const_ from '@/const/sign-code'
export default {
  name: 'uploadPetClinicalData',
  components: {
    PreviousRadiotherapy,
    PreviousSurgery,
    PreviousOther,
    PreviousFiles,
    clinicalDataQuestions,
    PreviewFile,
    SignForm
  },
  props: {
    data: {
      type: Object,
      default() {
        return {}
      },
    },
    studyData: {
      required: true,
      type: Object,
      default() {
        return {}
      },
    },
    subjectVisitId: {
      type: String,
      required: true,
    },
    enumType: {
      type: Number,
      default: 0,
    },
    allowAddOrEdit: {
      type: Boolean,
      default: false,
    },
    isPatientFormAllowEdit: {
      type: Boolean,
      default: false,
    },
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      faccept: ['.pdf'],
      isShow: false,
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      loading: false,
      btnLoading: false,
      PreviousHistoryList: [],
      PreviousSurgeryList: [],
      PreviousOtherList: [],
      PreviousPDFList: [],
      fileList: [],
      currentRow: {},
      prVisible: false,
      psVisible: false,
      poVisible: false,
      upVisible: false,
      trialId: this.$route.query.trialId,
      moment,
      downloadLoading: false,
      clinicalDatas: [],
      previewObj: { visible: false, filePath: '', fileType: '' },
      activeName: '',
      formData: {
        Id: '',
        PatientSex: '',
        PatientWeight: null,
        RadionuclideTotalDose: null,
        RadionuclideHalfLife: null,
        RadiopharmaceuticalStartTime: '',
        AcquisitionTime: '',
        TimeCheck: '',
        Reason: ''
      },
      rules: {
        PatientSex: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'change' }
        ],
        PatientWeight: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { type: 'number', min: 0, message: this.$t('trials:ptData:ruleMessage:number1'), trigger: 'blur' }//数值必须大于0
        ],
        RadionuclideTotalDose: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { type: 'number', min: 0, message: this.$t('trials:ptData:ruleMessage:number1'), trigger: 'blur' }//数值必须大于0
        ],
        RadionuclideHalfLife: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { type: 'number', min: 0, message: this.$t('trials:ptData:ruleMessage:number1'), trigger: 'blur' }
        ],
        RadiopharmaceuticalStartTime: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { validator: this.validateDicomTime, trigger: 'blur' }
        ],
        AcquisitionTime: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { validator: this.validateDicomTime, trigger: 'blur' },
          // 自定义校验：确保成像时间不早于注射时间
          { validator: this.validateTime, trigger: 'blur' }
        ],
        Reason: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }
        ],
      },
      formLoading: false,
      isPatientFormCanEdit: false,
      signVisible: false,
      signCode: '',
      currentUser: zzSessionStorage.getItem('userName')
    }
  },
  mounted() {
    this.isPatientFormCanEdit = this.allowAddOrEdit || this.isPatientFormAllowEdit 
    this.getClinicalData()
  },
  methods: {
    beginScanFiles(e, id, clinicalDataTrialSetId) {
      this.currentRow = {
        Id: id,
        ClinicalDataTrialSetId: clinicalDataTrialSetId,
        SubjectId: this.data.SubjectId,
      }
      this.currentRow.TrialId = this.$route.query.trialId
      var files = e.target.files
      this.fileList = []
      for (var i = 0; i < files.length; ++i) {
        const fileName = files[i].name
        var extendName = fileName
          .substring(fileName.lastIndexOf('.'))
          .toLocaleLowerCase()
        if (this.faccept.indexOf(extendName) !== -1) {
          let obj = {
            size: files[i].size,
            type: extendName.split('.')[1],
            file: files[i],
            fileType: files[i].type
          }
          this.fileList.push(obj)
        }
      }
      this.handleUploadFile()
      this.$refs.addFile.forEach((item) => {
        item.value = null
      })
    },
    async handleUploadFile() {
      this.btnLoading = true
      this.loading = true
      this.addFileList = []
      try {
        for (var i = 0; i < this.fileList.length; ++i) {
          const file = await this.fileToBlob(this.fileList[i].file)
          var timestamp = Date.now()
          const res = await this.OSSclient.put(
            `/${this.trialId}/ClinicalData/${timestamp}_${this.fileList[i].file.name}`,
            file,
            {
              fileName: `${this.fileList[i].file.name}`,
              fileSize: this.fileList[i].size,
              fileType: this.fileList[i].fileType,
              uploadBatchId: this.$guid(),
              batchDataType: 4,
              trialId: this.trialId,
              subjectId: this.data.SubjectId,
              subjectVisitId: this.subjectVisitId
            }
          )
          this.addFileList.push({
            fileName: this.fileList[i].file.name,
            path: this.$getObjectName(res.url),
            url: this.$getObjectName(res.url),
            type: this.fileList[i].type,
            size: this.fileList[i].size,
          })
        }
        this.saveClinicalData()
      } catch (err) {
        console.log(err)
        this.btnLoading = false
        this.loading = false
      }
    },
    saveClinicalData() {
      this.btnLoading = true
      this.loading = true
      var param = {
        id: this.currentRow.Id,
        trialId: this.currentRow.TrialId,
        subjectId: this.currentRow.SubjectId,
        readingId: this.subjectVisitId,
        clinicalDataTrialSetId: this.currentRow.ClinicalDataTrialSetId,
        isVisit: true,
        deleteFileIds: [],
        addFileList: this.addFileList,
      }
      if (this.studyData.StudyId) {
        param.StudyId = this.studyData.StudyId
      }
      addOrUpdateReadingClinicalData(param)
        .then((response) => {
          this.btnLoading = false
          this.loading = false
          // 刷新文件列表并关闭弹窗
          this.getClinicalData()
          this.$message.success(
            this.$t('trials:uploadClinicalData:message:uploadSuccessfully')
          )
          this.$emit('getStudyInfo')
        })
        .catch(() => {
          this.btnLoading = false
          this.loading = false
        })
    },
    getClinicalData() {
      this.loading = true
      this.data.TrialId = this.$route.query.trialId
      var param = {
        SubjectVisitId: this.studyData.SubjectVisitId,
        StudyId: this.studyData.StudyId,
        TrialId: this.$route.query.trialId,
        SubjectId: this.studyData.SubjectId,
      }
      getCRCClinicalData(param)
        .then((res) => {
          this.clinicalDatas = res.Result
          this.activeName = res.Result.length > 0 ? res.Result[0].ClinicalDataTrialSetId : ''
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 打开编辑框
    editRow(row, type) {
      if (type === 1) {
        this.prVisible = true
      } else if (type === 2) {
        this.psVisible = true
      } else if (type === 3) {
        this.poVisible = true
      }
      this.currentRow = { ...row }
      this.currentRow.TrialId = this.$route.query.trialId
    },
    // 根据ID删除既往放疗史
    deletePreviousHistory(row) {
      this.$confirm(this.$t('trials:uploadedDicoms:message:deleteMes'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        this.loading = true
        deletePreviousHistory(
          this.$route.query.trialId,
          this.subjectVisitId,
          row.Id
        )
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.getClinicalData()
              this.$message.success(
                this.$t('trials:uploadedDicoms:message:deleteSuccessfully')
              )
              this.$emit('getStudyInfo')
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    // 根据ID删除既往手术史
    deletePreviousSurgery(row) {
      console.log(this.$route.query.trialId)
      this.$confirm(this.$t('trials:uploadedDicoms:message:deleteMes'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        // row.Type = '既往手术史'
        this.loading = true
        deletePreviousSurgery(
          this.$route.query.trialId,
          this.subjectVisitId,
          row.Id
        )
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.getClinicalData()
              this.$message.success(
                this.$t('trials:uploadedDicoms:message:deleteSuccessfully')
              )
              this.$emit('getStudyInfo')
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    // 根据ID删除既往其他资料史
    deletePreviousOther(row) {
      this.$confirm(this.$t('trials:uploadedDicoms:message:deleteMes'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        // row.Type = '既往其他治疗史'
        this.loading = true
        deletePreviousOther(
          this.$route.query.trialId,
          this.subjectVisitId,
          row.Id
        )
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.getClinicalData()
              this.$message.success(
                this.$t('trials:uploadedDicoms:message:deleteSuccessfully')
              )
              this.$emit('getStudyInfo')
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    // 文件预览
    preview(row) {
      if (!row.Path) return
      this.previewObj.fileName = row.FileName
      this.previewObj.filePath = row.Path
      this.previewObj.fileType = 'pdf'
      this.previewObj.visible = true
      // window.open(this.OSSclientConfig.basePath + path, '_blank')
    },
    addPreviousHistory(clinicalDataTrialSetId) {
      console.log(clinicalDataTrialSetId)
      this.currentRow = { ClinicalDataTrialSetId: clinicalDataTrialSetId }
      this.currentRow.TrialId = this.$route.query.trialId
      this.prVisible = true
    },
    addPreviousSurgery(clinicalDataTrialSetId) {
      this.currentRow = { ClinicalDataTrialSetId: clinicalDataTrialSetId }
      this.currentRow.TrialId = this.$route.query.trialId
      this.psVisible = true
    },
    addPreviousOther(clinicalDataTrialSetId) {
      this.currentRow = { ClinicalDataTrialSetId: clinicalDataTrialSetId }
      this.currentRow.TrialId = this.$route.query.trialId
      this.poVisible = true
    },
    // 关闭既往放疗史窗口并刷新列表
    closePRDialog() {
      this.prVisible = false
      this.currentRow.TrialId = this.$route.query.trialId
    },
    closePSDialog() {
      this.psVisible = false
      this.currentRow.TrialId = this.$route.query.trialId
    },
    closePODialog() {
      this.poVisible = false
      this.currentRow.TrialId = this.$route.query.trialId
    },
    closeUpDialog() {
      this.upVisible = false
      this.currentRow.TrialId = this.$route.query.trialId
    },
    refresh() {
      this.getClinicalData()
      this.$emit('getStudyInfo')
    },
    // 添加文件
    addFile(id, clinicalDataTrialSetId) {
      this.currentRow = {
        Id: id,
        ClinicalDataTrialSetId: clinicalDataTrialSetId,
        SubjectId: this.data.SubjectId,
      }
      this.currentRow.TrialId = this.$route.query.trialId
      this.upVisible = true
    },
    // 删除文件
    deleteFile(id) {
      this.$confirm(this.$t('trials:uploadedDicoms:message:deleteMes'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        this.loading = true
        deleteReadingClinicalDataPDF(id)
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.getClinicalData()
              this.$emit('getStudyInfo')
              this.$message.success(
                this.$t('trials:uploadedDicoms:message:deleteSuccessfully')
              )
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    handleDownloadTpl(cd) {
      window.open(this.OSSclientConfig.basePath + cd.Path)
    },
    // 时间一致性校验
    validateTime(rule, value, callback) {
      const { RadiopharmaceuticalStartTime } = this.formData
      const acquireSeconds = this.timeToSeconds(value)
      const startSeconds = this.timeToSeconds(RadiopharmaceuticalStartTime)
      if (acquireSeconds !== null && startSeconds !== null && acquireSeconds < startSeconds) {
        callback(new Error(this.$t('trials:ptData:ruleMessage:number3')))//成像时间不能早于注射时间
      } else {
        callback()
      }
    },
    validateDicomTime(rule, value, callback) {
      if (value === undefined || value === null || value === '') {
        callback()
        return
      }
      const raw = String(value).trim()
      if (!/^\d{1,6}$/.test(raw)) {
        callback(new Error(this.$t('trials:ptData:ruleMessage:number2')))
        return
      }
      const normalized = this.normalizeClinicalTime(raw)
      if (!this.isValidDicomTime(normalized)) {
        callback(new Error(this.$t('trials:ptData:ruleMessage:number4')))//请输入有效时间（HHMMSS）
        return
      }
      callback()
    },
    normalizeClinicalTime(value) {
      if (value === undefined || value === null || value === '') return ''
      const digits = String(value).trim().replace(/[^\d]/g, '')
      if (!digits) return ''
      return digits.slice(0, 6).padStart(6, '0')
    },
    isValidDicomTime(value) {
      if (!/^\d{6}$/.test(String(value || ''))) return false
      const normalized = String(value)
      const hh = Number(normalized.slice(0, 2))
      const mm = Number(normalized.slice(2, 4))
      const ss = Number(normalized.slice(4, 6))
      return hh >= 0 && hh <= 23 && mm >= 0 && mm <= 59 && ss >= 0 && ss <= 59
    },
    timeToSeconds(value) {
      const normalized = this.normalizeClinicalTime(value)
      if (!this.isValidDicomTime(normalized)) return null
      const hh = Number(normalized.slice(0, 2))
      const mm = Number(normalized.slice(2, 4))
      const ss = Number(normalized.slice(4, 6))
      return hh * 3600 + mm * 60 + ss
    },
    handleTimeBlur(field) {
      const value = this.formData[field]
      if (value === undefined || value === null || value === '') return
      this.formData[field] = this.normalizeClinicalTime(value)
      this.computeTimeRelation()
    },
    normalizeTimeFields() {
      this.formData.RadiopharmaceuticalStartTime = this.normalizeClinicalTime(
        this.formData.RadiopharmaceuticalStartTime
      )
      this.formData.AcquisitionTime = this.normalizeClinicalTime(
        this.formData.AcquisitionTime
      )
      this.computeTimeRelation()
    },
    computeTimeRelation() {
      const startTime = this.formData.RadiopharmaceuticalStartTime
      const acquireTime = this.formData.AcquisitionTime

      if (!startTime || !acquireTime) {
        this.formData.TimeCheck = ''
        return
      }

      const startSeconds = this.timeToSeconds(startTime)
      const acquireSeconds = this.timeToSeconds(acquireTime)
      if (startSeconds === null || acquireSeconds === null) {
        this.formData.TimeCheck = ''
        return
      }

      if (startSeconds <= acquireSeconds) {
        this.formData.TimeCheck = this.$t('trials:ptData:timeCheck:val1') //注射时间 ≤ 成像时间
      } else {
        this.formData.TimeCheck = this.$t('trials:ptData:timeCheck:val2') //注射时间 > 成像时间
      }
    },
    async tabClick(tab) {
      try {
        const name = tab.name
        if (name === 'patientForm' && !this.formData.Id) {
          this.formLoading = true
          let res = await getPatientInfo({studyId: this.studyData.StudyId})
          this.formData = {
            Id: res.Result.Id || '',
            PatientSex: res.Result.PatientSex || '',
            PatientWeight: parseFloat(res.Result.PatientWeight) || null,
            RadionuclideTotalDose: parseFloat(res.Result.RadionuclideTotalDose) || null,
            RadionuclideHalfLife: parseFloat(res.Result.RadionuclideHalfLife) || null,
            RadiopharmaceuticalStartTime: this.normalizeClinicalTime(res.Result.RadiopharmaceuticalStartTime),
            AcquisitionTime: this.normalizeClinicalTime(res.Result.AcquisitionTime),
            TimeCheck: '',
            Reason: res.Result.Reason
          }
          this.computeTimeRelation()
          this.formLoading = false
        }
      } catch(e) {
        this.formLoading = false
        console.log(e)
      }
    },
    async submitForm() {
      try {
        let valid = await this.$refs.patientForm.validate()
        if (!valid) return
        if (this.isAudit) {
          this.normalizeTimeFields()
          const { CorrectImageExaminationInformation } = const_.processSignature
          this.signCode = CorrectImageExaminationInformation
          this.signVisible = true
        } else {
          this.normalizeTimeFields()
          this.formLoading = true
          let res = await editPatientInfo(this.formData)
          this.formLoading = false
          if (res && res.IsSuccess) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.$emit('close')
          }
        }
        
      } catch(e) {
        this.formLoading = false
        console.log(e)
      }
      
    },
    async closeSignDialog(isSign, signInfo) {
      try {
        if (isSign) {
          let data = {
            data: this.formData,
            signInfo
          }
          let res = await amendmentPatientInfo(data)
          if (res && res.IsSuccess) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.signVisible = false
            this.$emit('close')
          }
        } else {
          this.signVisible = false
        }
      } catch(e) {
        console.log(e)
      }
    }
  }
}
</script>
<style lang="scss">
.clinical-data-wrapper {
  .box-title {
    padding: 12px;
    margin-bottom: 10px;
    background-color: #dcdfe6;
  }
  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 0px;
    .el-form-item {
      margin-bottom: 15px;
    }
  }
  .form-item-half {
    flex: 1;
  }
}
</style>
