<template>
  <div class="study-info">
    <div class="functions" style="text-align: right">
      <!-- 删除 -->
      <el-button
        v-if="
          data.SubmitState * 1 < 2 ||
          (data.SubmitState === 2 && data.IsQCConfirmedReupload)
        "
        v-hasPermi="['trials:trials-panel:visit:crc-upload:delete']"
        :disabled="deleteArr.length === 0"
        type="primary"
        size="small"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >
        {{ $t('trials:uploadedDicoms:action:delete') }}
      </el-button>
      <!-- 预览 -->
      <el-button
        type="primary"
        size="small"
        :disabled="studyList.length === 0"
        icon="el-icon-view"
        @click="handlePreviewAllFiles"
      >
        {{ $t('trials:uploadedDicoms:action:preview') }}
      </el-button>
    </div>
    <el-table
      v-loading="studyLoading"
      :data="studyList"
      style="width: 100%"
      height="300"
      :row-class-name="tableRowClassName"
      @selection-change="handleSelectionChange"
      :default-sort="{ prop: 'UploadedTime', order: 'ascending' }"
    >
      <el-table-column
        v-if="!(data.SubmitState * 1 === 2) || data.IsQCConfirmedReupload"
        type="selection"
        width="55"
      />
      <!-- 检查编号 -->
      <el-table-column
        prop="StudyCode"
        :label="$t('trials:uploadedDicoms:table:studyId')"
        min-width="80"
        show-overflow-tooltip
        sortable
      />
      <!-- 检查名称 -->
      <el-table-column
        v-if="relationInfo.IsShowStudyName"
        prop="StudyName"
        :label="$t('trials:audit:table:StudyName')"
        sortable
      />
      <!-- 检查类型 -->
      <el-table-column
        prop="ModalityForEdit"
        :label="$t('trials:audit:table:modality')"
        sortable
      />
      <!-- 检查类型 -->
      <el-table-column
        prop="Modalities"
        :label="$t('trials:audit:table:modality1')"
        sortable
      />
      <!-- 检查部位 -->
      <el-table-column
        prop="BodyPartForEdit"
        :label="$t('trials:uploadedDicoms:table:bodyPart')"
        sortable
        min-width="100"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ getBodyPart(scope.row.BodyPartForEdit) }}
        </template>
      </el-table-column>
      <!-- 序列数量 -->
      <el-table-column
        prop="SeriesCount"
        :label="$t('trials:uploadedDicoms:table:seriesCount')"
        sortable
        min-width="100"
        show-overflow-tooltip
      />
      <!-- 图像数量 -->
      <el-table-column
        prop="InstanceCount"
        :label="$t('trials:uploadedDicoms:table:instanceCount')"
        sortable
        min-width="100"
        show-overflow-tooltip
      />
      <!-- 检查日期 -->
      <el-table-column
        prop="StudyTime"
        :label="$t('trials:uploadedDicoms:table:studyDate')"
        sortable
        min-width="120"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ moment(scope.row.StudyTime).format('YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <!-- 更新时间 -->
      <el-table-column
        prop="UpdateTime"
        :label="$t('trials:uploadedDicoms:table:UpdateTime')"
        min-width="120"
        show-overflow-tooltip
        sortable
      />
      <!-- 上传时间 -->
      <el-table-column
        prop="UploadedTime"
        :label="$t('trials:uploadedDicoms:table:uploadedTime')"
        sortable
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('common:action:action')"
        min-width="100"
      >
        <template slot-scope="scope">
          <!-- 预览 -->
          <el-button
            icon="el-icon-view"
            :disabled="scope.row.SeriesCount === 0 || scope.row.IsDeleted"
            :title="$t('trials:uploadedDicoms:action:preview')"
            circle
            @click="handleViewStudy(scope.row)"
          />
          <!-- 预览PET-CT数据 -->
          <el-button
            icon="el-icon-folder"
            :title="$t('trials:audit:tab:clinicalData')"
            v-if="
              ['PT、CT', 'CT、PT', 'PET-CT'].includes(scope.row.Modalities) &&
              relationInfo.IsHaveStudyClinicalData
            "
            circle
            :disabled="scope.row.IsDeleted"
            @click="handlePreviewClinicalData(scope.row)"
          />
          <!-- 编辑 -->
          <el-button
            icon="el-icon-edit-outline"
            v-if="
              data.SubmitState * 1 < 2 ||
              (data.SubmitState === 2 && data.IsQCConfirmedReupload)
            "
            v-hasPermi="['trials:trials-panel:visit:crc-upload:edit']"
            title="编辑"
            circle
            :disabled="scope.row.IsDeleted"
            @click="handleEditStudy(scope.row)"
          />
          <!-- 删除 -->
          <el-button
            v-if="
              data.SubmitState * 1 < 2 ||
              (data.SubmitState === 2 && data.IsQCConfirmedReupload)
            "
            v-hasPermi="['trials:trials-panel:visit:crc-upload:delete']"
            icon="el-icon-delete"
            :title="$t('trials:uploadedDicoms:action:delete')"
            circle
            @click="handleDeleteStudy(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-if="editStudyInfoVisible"
      :title="$t('trials:audit:action:edit')"
      :visible.sync="editStudyInfoVisible"
      :close-on-click-modal="false"
      append-to-body
      custom-class="base-dialog-wrapper"
      width="600px"
    >
      <div
        style="
          padding: 10px;
          border: 1px solid #e0e0e0;
          max-height: 650px;
          overflow-y: auto;
        "
      >
        <el-form ref="studyForm" :model="studyForm" label-width="100px">
          <!-- 检查编号 -->
          <el-form-item :label="$t('trials:audit:table:studyId')">
            <el-input v-model="studyForm.StudyCode" disabled />
          </el-form-item>
          <!-- 检查类型 -->
          <el-form-item
            v-if="studyForm.IsDicomData"
            :label="$t('trials:audit:table:modality')"
          >
            <el-input v-model="studyForm.Modalities" disabled />
          </el-form-item>
          <!-- 检查类型 -->
          <el-form-item
            v-else
            :label="$t('trials:audit:table:modality')"
            prop="Modalities"
            :rules="[
              {
                required: true,
                message: $t('common:ruleMessage:specify'),
                trigger: 'blur',
              },
            ]"
          >
            <el-radio-group v-model="studyForm.Modalities">
              <el-radio
                v-for="m in trialModalitys"
                v-show="m !== ''"
                :key="m"
                :label="m"
                style="margin-bottom: 15px"
              />
            </el-radio-group>
          </el-form-item>
          <!-- 检查部位 -->
          <el-form-item
            :label="$t('trials:audit:table:bodyPart')"
            prop="BodyPartForEdit"
            :rules="[
              {
                required: true,
                message: $t('common:ruleMessage:specify'),
                trigger: 'blur',
              },
            ]"
          >
            <el-checkbox-group v-model="studyForm.BodyPartForEdit">
              <el-checkbox
                v-for="bodyPart in trialBodyPartTypes"
                :key="bodyPart"
                :label="bodyPart"
                >{{
                  $fd('Bodypart', bodyPart, 'Code', BodyPart, 'Name')
                }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <!-- 序列数量 -->
          <el-form-item :label="$t('trials:audit:table:seriesCount')">
            <el-input v-model="studyForm.SeriesCount" disabled />
          </el-form-item>
          <!-- 图像数量 -->
          <el-form-item
            v-if="studyForm.InstanceCount"
            :label="$t('trials:audit:table:instanceCount')"
          >
            <el-input v-model="studyForm.InstanceCount" disabled />
          </el-form-item>
          <!-- 检查日期 -->
          <el-form-item :label="$t('trials:audit:table:studyDate')">
            <el-date-picker
              v-model="studyForm.StudyTime"
              disabled
              type="date"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="btnLoading"
          size="small"
          type="primary"
          @click="editStudyInfoVisible = false"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button
          :loading="btnLoading"
          size="small"
          type="primary"
          @click="handleUpdateStudyInfo"
        >
          {{ $t('common:button:save') }}
        </el-button>
      </div>
    </el-dialog>
    <!--pet-ct临床数据上传-->
    <el-dialog
      v-if="petVisible"
      :show-close="true"
      :visible.sync="petVisible"
      append-to-body
    >
      <uploadPetClinicalData
        :subject-visit-id="data.Id"
        :data="data"
        :studyData="rowData"
        :allow-add-or-edit="false"
      />
    </el-dialog>
  </div>
</template>
<script>
import {
  getSubjectVisitUploadedStudyList,
  deleteStudyList,
  updateModality,
} from '@/api/trials'
import moment from 'moment'
import { getToken } from '@/utils/auth'
import uploadPetClinicalData from './uploadPetClinicalData.vue'
export default {
  name: 'StudyInfo',
  components: { uploadPetClinicalData },
  props: {
    data: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      editStudyInfoVisible: false,
      studyForm: {
        StudyCode: '',
        IsDicomData: true,
        Modalities: '',
        BodyPartForEdit: [],
        SeriesCount: null,
        StudyTime: '',
      },
      deleteArr: [],
      studyLoading: false,
      studyList: [],
      trialId: this.$route.query.trialId,
      moment,
      relationInfo: {},
      trialBodyPartTypes: [],
      trialModalitys: [],
      btnLoading: false,

      // pet-ctlinc数据
      petVisible: false,
      rowData: {},

      BodyPart: {},
    }
  },
  async mounted() {
    this.getStudyInfo()
    this.BodyPart.Bodypart = await this.$getBodyPart(this.$route.query.trialId)
  },
  methods: {
    // 预览临床数据
    handlePreviewClinicalData(row) {
      this.rowData = row
      this.petVisible = true
    },
    // 打开检查信息编辑框
    handleEditStudy(row) {
      this.editStudyInfoVisible = true
      this.studyForm = { ...row }
      var bodyPart = []
      if (this.studyForm.BodyPartForEdit.indexOf('|') !== -1) {
        bodyPart = this.studyForm.BodyPartForEdit.split('|')
      } else if (this.studyForm.BodyPartForEdit !== '') {
        bodyPart.push(this.studyForm.BodyPartForEdit)
      }
      this.studyForm.BodyPartForEdit = bodyPart
    },
    // 更新拍片部位/拍片类型信息
    handleUpdateStudyInfo() {
      this.$refs['studyForm'].validate((valid) => {
        if (!valid) return
        this.btnLoading = true
        this.studyForm.BodyPart = this.studyForm.BodyPartForEdit.join('|')
        this.studyForm.Modality = this.studyForm.Modalities
        var params = {
          id: this.studyForm.StudyId,
          subjectVisitId: this.data.Id,
          type: 1,
          modality: this.studyForm.Modality,
          bodyPart: this.studyForm.BodyPart,
        }
        updateModality(this.data.TrialId, params)
          .then((res) => {
            this.btnLoading = false
            if (res.IsSuccess) {
              this.getStudyInfo()
              this.$message.success(this.$t('common:message:savedSuccessfully'))
              this.editStudyInfoVisible = false
            }
          })
          .catch(() => {
            this.btnLoading = false
          })
      })
    },
    getStudyInfo() {
      this.studyLoading = true
      getSubjectVisitUploadedStudyList(this.data.Id)
        .then((res) => {
          this.studyList = res.Result
          this.studyLoading = false
          this.relationInfo = res.OtherInfo
          this.trialBodyPartTypes = this.relationInfo.BodyPartTypes
            ? this.relationInfo.BodyPartTypes.split('|')
            : []
          this.trialModalitys = this.relationInfo.Modalitys
            ? this.relationInfo.Modalitys.split('|')
            : []
        })
        .catch(() => {
          this.studyLoading = false
        })
    },
    // 批量删除
    handleBatchDelete() {
      this.$confirm(this.$t('trials:uploadedDicoms:message:deleteMes'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.studyLoading = true
          deleteStudyList(this.trialId, this.data.Id, this.deleteArr)
            .then((res) => {
              if (res.IsSuccess) {
                this.getStudyInfo()
                this.$emit('getList')
                this.$message.success(
                  this.$t('trials:uploadedDicoms:message:deleteSuccessfully')
                )
              }
            })
            .catch(() => {
              this.studyLoading = true
            })
        })
        .catch(() => {})
    },
    // 预览所有影像
    handlePreviewAllFiles() {
      var tokenKey = getToken()
      const routeData = this.$router.resolve({
        path: `/showvisitdicoms?trialId=${this.data.TrialId}&visitInfo=${this.data.VisitName}(${this.data.VisitNum})&subjectVisitId=${this.data.Id}&isFromCRCUpload=1&TokenKey=${tokenKey}`,
      })
      var newWindow = window.open(routeData.href, '_blank')
      this.$emit('setOpenWindow', newWindow)
    },
    // 预览影像
    handleViewStudy(row) {
      var token = getToken()
      const routeData = this.$router.resolve({
        path: `/showdicom?studyId=${row.StudyId}&isFromCRCUpload=1&TokenKey=${token}&type=Study`,
      })
      var newWindow = window.open(routeData.href, '_blank')
      this.$emit('setOpenWindow', newWindow)
    },
    // 删除某个检查
    handleDeleteStudy(row) {
      this.$confirm(this.$t('trials:uploadedDicoms:message:deleteMes'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.studyLoading = true
          deleteStudyList(this.trialId, this.data.Id, [row.StudyId])
            .then((res) => {
              if (res.IsSuccess) {
                this.getStudyInfo()
                this.$emit('getList')
                this.$message.success(
                  this.$t('trials:uploadedDicoms:message:deleteSuccessfully')
                )
              }
            })
            .catch(() => {
              this.studyLoading = true
            })
        })
        .catch(() => {})
    },
    getBodyPart(bodyPart) {
      if (!bodyPart) return ''
      var separator = ','
      if (bodyPart.indexOf('|') > -1) {
        separator = '|'
      } else if (bodyPart.indexOf(',') > -1) {
        separator = ','
      } else if (bodyPart.indexOf('，') > -1) {
        separator = '，'
      }
      var arr = bodyPart.split(separator)
      var newArr = arr.map((i) => {
        return this.$fd('Bodypart', i.trim(), 'Code', this.BodyPart, 'Name')
      })
      return newArr.join(' | ')
    },
    // 获取勾选项
    handleSelectionChange(val) {
      this.deleteArr = []
      val.forEach((item) => {
        this.deleteArr.push(item.StudyId)
      })
    },
    // 设置已删除行勾选状态
    hasDeleted(row) {
      if (row.IsDeleted) {
        return false
      } else {
        return true
      }
    },
    // 设置已删除序列行样式
    tableRowClassName({ row, rowIndex }) {
      if (row.IsDeleted) {
        return 'delete-row'
      } else {
        return ''
      }
    },
  },
}
</script>
<style lang="scss">
.study-info {
  .delete-row {
    text-decoration-line: line-through;
    color: #c0c4cc;
  }
}
</style>
