<template>
  <div v-loading="loading" class="non-dicom-wrapper">
    <!-- <h4 class="box-title">既往放疗史</h4> -->
    <div style="text-align: right">
      <el-button v-if="allowAddOrEdit" v-hasPermi="['trials:trials-panel:visit:crc-upload:edit']" icon="el-icon-plus"
        type="primary" size="small" @click.native.prevent="handleAdd">
        {{ $t('common:button:new') }}
      </el-button>
      <el-button icon="el-icon-view" type="primary" size="small" :disabled="nonDicomStudyList.length === 0"
        @click="handlePreviewAllVisitFiles">
        {{ $t('trials:uploadNonDicoms:button:preview') }}
      </el-button>
    </div>

    <el-table :data="nonDicomStudyList" style="width: 100%" :default-sort="{ prop: 'CreateTime', order: 'ascending' }"
      :row-class-name="tableRowClassName">
      <!-- 检查编号 -->
      <el-table-column prop="CodeView" :label="$t('trials:uploadNonDicoms:table:studyId')" sortable />
      <!-- 检查名称 -->
      <el-table-column v-if="relationInfo.IsShowStudyName" prop="StudyName"
        :label="$t('trials:uploadNonDicoms:table:StudyName')" sortable />
      <!-- 检查类型 -->
      <el-table-column prop="Modality" :label="$t('trials:uploadNonDicoms:table:modality')" sortable />
      <!-- 检查部位 -->
      <el-table-column prop="BodyPart" :label="$t('trials:uploadNonDicoms:table:bodyPart')" sortable>
        <template slot-scope="scope">
          {{ getBodyPart(scope.row.BodyPart) }}
        </template>
      </el-table-column>
      <!-- 文件 -->
      <el-table-column prop="FileCount" :label="$t('trials:uploadNonDicoms:table:files')" sortable>
        <template slot-scope="scope">
          <el-popover v-if="scope.row.FileCount" trigger="click" placement="bottom" popper-class="imgTable">
            <el-table v-loading="filesLoading" :data="nonDicomfilesList" height="300" size="small"
              :row-class-name="tableRowClassName">
              <!-- 文件名称 -->
              <el-table-column prop="FileName" :label="$t('trials:uploadNonDicoms:table:fileName')" width="200" />
              <el-table-column prop="FileSize" :label="$t('trials:audit:table:nonDicomsFileSize')" width="100">
                <template slot-scope="scope">
                  <span>{{
                    scope.row.FileSize && scope.row.FileSize > 0
                      ? `${(scope.row.FileSize / 1024 / 1024).toFixed(3)}MB`
                      : ''
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common:action:action')" width="120">
                <template slot-scope="files">
                  <div style="display: flex">
                    <!-- 预览 -->
                    <viewer v-if="files.row.type !== 'MP4'" :ref="files.row.FullFilePath" style="margin: 0 10px"
                      :images="[
                        `${OSSclientConfig.basePath}${files.row.FullFilePath}`,
                      ]">
                      <el-button icon="el-icon-view" circle :title="$t('trials:uploadNonDicoms:action:preview')"
                        size="small" :disabled="files.row.FileType &&
                          files.row.FileType.indexOf('zip') >= 0
                          " @click.native.prevent="handlePreviewImg(files.row)">
                      </el-button>
                      <img v-show="false" crossorigin="anonymous"
                        :src="`${OSSclientConfig.basePath}${files.row.FullFilePath}`" alt="Image" />
                    </viewer>

                    <el-button v-if="files.row.type === 'MP4'" icon="el-icon-view" circle
                      :title="$t('trials:uploadNonDicoms:action:preview')" size="small" :disabled="files.row.FileType &&
                        files.row.FileType.indexOf('zip') >= 0
                        " @click.native.prevent="handleLookVideo(scope.row)" />
                    <!-- 删除 -->
                    <el-button v-if="allowAddOrEdit" v-hasPermi="[
                      'trials:trials-panel:visit:crc-upload:delete',
                    ]" icon="el-icon-delete" circle :title="$t('trials:uploadNonDicoms:action:delete')" size="small"
                      @click.native.prevent="
                        files.row.type === 'MP4'
                          ? hadnleDeleteVideo(scope.row)
                          : handleDeleteFile(files.row.Id)
                        " />
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div slot="reference" class="name-wrapper">
              <el-button type="text" @click.native.prevent="handleGetFilesList(scope.row)">
                {{ scope.row.FileCount }}
              </el-button>
            </div>
          </el-popover>
          <span v-else>{{ scope.row.FileCount }}</span>
        </template>
      </el-table-column>
      <!-- 检查日期 -->
      <el-table-column prop="ImageDate" :label="$t('trials:uploadNonDicoms:table:studyDate')" sortable>
        <template slot-scope="scope">
          {{ moment(scope.row.ImageDate).format('YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <!-- 更新时间 -->
      <el-table-column prop="UpdateTime" :label="$t('trials:uploadNonDicoms:table:updateTime')" sortable />
      <!-- 创建时间 -->
      <el-table-column prop="CreateTime" :label="$t('trials:uploadNonDicoms:table:CreateTime')" sortable />
      <el-table-column :label="$t('common:action:action')" min-width="200">
        <template slot-scope="scope">
          <!-- 预览 -->
          <el-button icon="el-icon-view" circle :title="$t('trials:uploadNonDicoms:action:preview')"
            :disabled="scope.row.FileCount === 0" @click.native.prevent="handlePreviewAllFiles(scope.row)" />
          <!-- 上传 -->
          <el-button v-if="allowAddOrEdit" icon="el-icon-upload2" circle :disabled="scope.row.IsDeleted"
            :title="$t('trials:uploadNonDicoms:action:upload')" @click.native.prevent="handleUpload(scope.row)" />
          <!-- 上传视频 -->
          <!-- <el-button
            v-if="( allowAddOrEdit)"
            icon="el-icon-video-camera-solid"
            circle
            :title="$t('trials:uploadNonDicoms:action:xfuploadvideo')"
            @click.native.prevent="handleUploadVideo(scope.row)"
          /> -->
          <!-- 编辑 -->
          <el-button v-if="allowAddOrEdit" v-hasPermi="['trials:trials-panel:visit:crc-upload:edit']"
            icon="el-icon-edit-outline" circle :title="$t('trials:uploadNonDicoms:action:edit')"
            @click.native.prevent="handleEdit(scope.row)" />
          <!-- 删除 -->
          <el-button v-if="allowAddOrEdit" v-hasPermi="['trials:trials-panel:visit:crc-upload:delete']"
            icon="el-icon-delete" circle :title="$t('trials:uploadNonDicoms:action:delete')"
            @click.native.prevent="handleDelete(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑 -->
    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible" :close-on-click-modal="false" :title="title"
      width="600px" append-to-body custom-class="base-dialog-wrapper">
      <el-form ref="editForm" :model="form" label-width="100px">
        <div class="base-dialog-body">
          <!-- 检查编号 -->
          <el-form-item v-if="!!form.CodeView" :label="$t('trials:uploadNonDicoms:table:studyId')">
            <el-input v-model="form.CodeView" disabled />
          </el-form-item>
          <!-- 检查名称 -->
          <el-form-item v-if="relationInfo.IsShowStudyName" :label="$t('trials:uploadNonDicoms:table:StudyName')"
            prop="StudyName" :rules="[
              {
                required: true,
                message: $t('common:ruleMessage:specify'),
                trigger: 'blur',
              },
            ]">
            <el-radio-group v-model="form.StudyName">
              <template v-for="m in relationInfo.StudyNameList">
                <el-radio v-if="m.IsChoose" :key="m.Name" :label="isEN ? m.EnName : m.Name" style="line-height: 40px" />
              </template>
            </el-radio-group>
          </el-form-item>
          <!-- 检查类型 -->
          <el-form-item :label="$t('trials:uploadNonDicoms:table:modality')" prop="Modality" :rules="[
            {
              required: true,
              message: $t('common:ruleMessage:specify'),
              trigger: 'blur',
            },
          ]">
            <el-radio-group v-model="form.Modality">
              <template v-for="m in trialModalitys">
                <el-radio v-if="m !== ''" :key="m" :label="m" style="line-height: 40px" />
              </template>
            </el-radio-group>
          </el-form-item>
          <!-- 检查部位 -->
          <el-form-item :label="$t('trials:uploadNonDicoms:table:bodyPart')" prop="BodyParts" :rules="[
            {
              required: true,
              message: $t('common:ruleMessage:specify'),
              trigger: 'blur',
            },
          ]">
            <el-checkbox-group v-model="form.BodyParts">
              <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:uploadNonDicoms:table:studyDate')" prop="ImageDate" :rules="[
            {
              required: true,
              message: $t('common:ruleMessage:specify'),
              trigger: 'blur',
            },
          ]">
            <el-date-picker v-model="form.ImageDate" type="date" :picker-options="pickerOption"
              value-format="yyyy-MM-dd" format="yyyy-MM-dd" style="width: 100%" />
          </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="dialogVisible = false">
              {{ $t('common:button:cancel') }}
            </el-button>
            <el-button size="small" type="primary" :loading="btnLoading" @click="handleSave">
              {{ $t('common:button:save') }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>

    <!-- 上传非dicom文件 -->
    <el-dialog v-if="uploadVisible" :visible.sync="uploadVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadNonDicoms:dialogTitle:upload')" width="800px" append-to-body
      custom-class="base-dialog-wrapper" @close="resetFileDiaolg">
      <!-- 多文件上传 -->
      <form id="inputForm" ref="uploadForm">
        <el-divider content-position="left">{{
          $t('trials:uploadNonDicoms:label:fileType').replace(
            'xxx',
            relationInfo.ImageFormatList.join('/')
          )
        }}</el-divider>
        <div class="form-group">
          <div class="upload" style="margin-right: 10px">
            <input multiple="multiple" webkitdirectory="" directory accept="*/*" type="file" name="uploadFolder"
              class="select-file" title="" @change="beginScanFiles($event)" v-if="!btnLoading" />
            <div class="btn-select">
              {{ $t('trials:uploadNonDicoms:button:selectFolder') }}
            </div>
          </div>
          <div class="upload">
            <input class="select-file" multiple="" :accept="faccept.join(',')" type="file" name="uploadFile" title=""
              @change="beginScanFiles($event)" v-if="!btnLoading" />
            <div class="btn-select">
              {{ $t('trials:uploadNonDicoms:button:select') }}
            </div>
          </div>
        </div>
      </form>
      <!-- 文件列表 -->
      <el-table ref="filesTable" :data="fileList" class="dicomFiles-table" height="300"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="(row, index) => row.status !== 2 && !btnLoading" />
        <el-table-column type="index" width="50" />
        <!-- 文件名称 -->
        <el-table-column prop="name" :label="$t('trials:uploadNonDicoms:table:fileName')" min-width="100" />
        <!-- 文件大小 -->
        <el-table-column prop="size" :label="$t('trials:uploadNonDicoms:table:fileSize')">
          <template slot-scope="scope">
            <span>{{
              scope.row.size && scope.row.size > 0
                ? `${(scope.row.size / 1024 / 1024).toFixed(3)}MB`
                : '0MB'
            }}</span>
          </template>
        </el-table-column>
        <!-- 文件类型 -->
        <el-table-column prop="type" :label="$t('trials:uploadNonDicoms:table:fileType')" />
        <!-- 上传状态 -->
        <el-table-column prop="status" :label="$t('trials:uploadNonDicoms:table:uploadStatus')" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="['warning', 'info', 'success', 'danger'][scope.row.status]"
              v-if="scope.row.status || scope.row.status === 0">{{ $fd('NoneDicomUploadStatus', scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('trials:uploadNonDicoms:table:failedFileCount')" min-width="150"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <el-progress color="#409eff" :percentage="scope.row.size && scope.row.size > 0 ? ((scope.row.uploadFileSize * 100) / scope.row.size).toFixed(2) *
                1
                : ((scope.row.uploadFileSize * 100) / 1).toFixed(2) *
                1
              " />
          </template>
        </el-table-column>
        <el-table-column :label="$t('common:action:action')">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-delete" circle :disabled="btnLoading"
              :title="$t('trials:crcUpload:action:delete')" @click="handleRemoveFile(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right; padding: 10px 0px">
        <span style="margin-right: 10px">{{
          $store.state.trials.uploadTip
        }}</span>
        <el-button size="small" type="primary" :disabled="selectArr.length == 0" :loading="btnLoading"
          @click="beginUpload">
          {{ $t('trials:uploadNonDicoms:action:upload') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 上传非dicom视频文件 -->
    <!-- <el-dialog
      v-if="uploadVideoVisible"
      :visible.sync="uploadVideoVisible"
      upload-video-visible
      :close-on-click-modal="false"
      :title="$t('trials:uploadNonDicoms:title:xfuploadvideo')"
      width="480px"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <upload-videos @uploadOver="uploadOver" />
    </el-dialog> -->
    <!-- 预览非DICOM视频文件 -->
    <el-dialog v-if="lookVideoVisible" :visible.sync="lookVideoVisible" upload-video-visible
      :close-on-click-modal="false" :title="$t('trials:uploadNonDicoms:title:xflookvideo')" width="480px" append-to-body
      custom-class="base-dialog-wrapper">
      <div style="display: flex; justify-content: center">
        <video v-if="lookVideoVisible" id="video" controls crossorigin="anonymous" width="400" height="270">
          <source :src="currentRow.VideoUrl" type="video/mp4" />
        </video>
      </div>
      <div style="text-align: right; padding: 10px 0px">
        <el-button size="small" @click="lookVideoVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="previewImgVisible" :visible.sync="previewImgVisible"
      :title="$t('trials:uploadNonDicoms:dialogTitle:preview')" append-to-body width="565px">
      <div v-loading="imageLoading" class="base-modal-body" style="border: 2px solid #ccc; padding: 10px">
        <el-image :src="`${OSSclientConfig.basePath}${imgUrl}`" crossorigin="anonymous" fit="fit"
          style="height: 500px; width: 500px" @error="imageLoading = false" @load="imageLoading = false"
          :preview-src-list="[`${OSSclientConfig.basePath}${imgUrl}`]" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  preArchiveStudy,
  getNoneDicomStudyList,
  getNoneDicomStudyFileList,
  uploadNoneDicomFile,
  addOrUpdateNoneDicomStudy,
  deleteNoneDicomStudy,
  deleteNoneDicomStudyFile,
} from '@/api/trials'
import { getToken } from '@/utils/auth'
// import PreviewFiles from './previewFiles'
// import uploadVideos from '@/components/videos'
import moment from 'moment'
import store from '@/store'
export default {
  name: 'UploadNonDicomFiles',
  // components: { uploadVideos },
  props: {
    bodyParts: {
      type: String,
      default: '',
    },
    modalities: {
      type: String,
      default: '',
    },
    data: {
      type: Object,
      default() {
        return {}
      },
    },
    subjectVisitId: {
      type: String,
      required: true,
    },
    allowAddOrEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      lookVideoVisible: false,
      nonDicomStudyList: [],
      dialogVisible: false,
      loading: false,
      trialBodyPartTypes: [],
      trialModalitys: [],
      btnLoading: false,
      title: '',
      form: {
        CodeView: '',
        Id: '',
        BodyPart: '',
        BodyParts: [],
        Modality: '',
        ImageDate: '',
        StudyName: '',
      },
      pickerOption: {
        disabledDate: (time) => {
          return time.getTime() > Date.now()
        },
      },
      uploadVisible: false,
      fileList: [],
      selectArr: [],
      successFileList: [],
      isFail: false,
      faccept: ['.jpg', '.jpeg', '.png', '.bmp', '.zip'],
      fCount: 0,
      currentRow: {},
      filesLoading: false,
      nonDicomfilesList: [],
      previewImgVisible: false,
      imageLoading: false,
      fileUrl: '',
      type: '',
      uploadVideoVisible: false,
      trialId: this.$route.query.trialId,
      moment,
      BodyPart: {},
      studyMonitorId: null,
      relationInfo: {},
    }
  },
  async mounted() {
    console.log(this.data)
    this.BodyPart.Bodypart = await this.$getBodyPart(this.$route.query.trialId)
    this.getNoneDicomList()
    this.trialBodyPartTypes = this.bodyParts ? this.bodyParts.split('|') : []
    this.trialModalitys = this.modalities ? this.modalities.split('|') : []
    this.OSSclient.close()
  },
  watch: {
    isFail() {
      if (this.isFail) {
        this.$confirm(
          this.$t('trials:visit:crcUpload:nomDicomFiles:failUpload'),
          {
            type: 'warning',
            distinguishCancelAndClose: true,
            confirmButtonText: this.$t('common:button:confirm'),
            cancelButtonText: this.$t('common:button:cancel'),
          }
        )
          .then(() => {
            this.beginUpload()
          })
          .catch((err) => {
            this.btnLoading = false
            console.log(err)
          })
      }
    },
    btnLoading() {
      store.dispatch('trials/setUnLock', this.btnLoading)
    },
  },
  beforeDestroy() {
    store.dispatch('trials/setUnLock', false)
    this.OSSclient.close()
  },
  computed: {
    isEN() {
      return this.$i18n.locale !== 'zh'
    },
  },
  methods: {
    // 初始化非Dicom列表数据
    getNoneDicomList() {
      this.loading = true
      getNoneDicomStudyList(this.subjectVisitId)
        .then((res) => {
          this.relationInfo = res.OtherInfo
          this.faccept = []
          this.relationInfo.ImageFormatList.forEach((item) => {
            this.faccept.push(`.${item}`)
          })
          this.nonDicomStudyList = res.Result.map((v) => {
            if (v.VideoObjectName) {
              v.FileCount += 1
            }
            return v
          })
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 打开新增弹框，并初始化数据
    handleAdd() {
      this.title = this.$t('trials:uploadNonDicoms:dialogTitle:add')
      this.form.Id = ''
      this.form.CodeView = ''
      this.form.BodyPart = ''
      this.form.Modality = ''
      this.form.StudyName = ''
      this.form.ImageDate = ''
      this.form.BodyParts = []
      this.dialogVisible = true
    },
    // 打开比编辑弹框，并初始化数据
    handleEdit(row) {
      this.title = this.$t('trials:uploadNonDicoms:dialogTitle:edit')
      const { CodeView, Id, BodyPart, Modality, ImageDate, StudyName } = {
        ...row,
      }
      this.form.CodeView = CodeView
      this.form.Id = Id
      this.form.BodyPart = BodyPart
      this.form.Modality = Modality
      this.form.StudyName = StudyName
      this.form.ImageDate = ImageDate
      this.form.BodyParts = this.form.BodyPart.split(', ')
      this.dialogVisible = true
    },
    // 保存非Dicom检查信息
    handleSave() {
      this.$refs.editForm.validate((valid) => {
        if (!valid) return
        this.btnLoading = true
        this.form.BodyPart = this.form.BodyParts.join(', ')
        this.form.TrialId = this.trialId
        this.form.TrialSiteId = this.data.TrialSiteId
        this.form.SubjectId = this.data.SubjectId
        this.form.SubjectVisitId = this.subjectVisitId
        addOrUpdateNoneDicomStudy(this.form)
          .then((res) => {
            this.btnLoading = false
            this.$refs.editForm.resetFields()
            this.getNoneDicomList()
            // 刷新父组件列表
            this.$emit('getList')
            this.$message.success(this.$t('common:message:savedSuccessfully'))

            this.dialogVisible = false
          })
          .catch(() => {
            this.btnLoading = false
          })
      })
    },
    // 根据id删除某个非Dicom检查信息
    handleDelete(row) {
      var message = ''
      if (row.FileCount > 0) {
        message = this.$t('trials:uploadNonDicoms:message:deleteStudyAndFiles')
      } else {
        message = this.$t('trials:uploadNonDicoms:message:delete')
      }
      this.$confirm(message, {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.loading = true
          deleteNoneDicomStudy(this.trialId, this.subjectVisitId, row.Id)
            .then((res) => {
              this.loading = false
              if (res.IsSuccess) {
                // 刷新父组件列表
                this.$emit('getList')
                this.nonDicomStudyList.splice(
                  this.nonDicomStudyList.findIndex(
                    (item) => item.Id === row.Id
                  ),
                  1
                )

                this.$message.success(
                  this.$t('trials:uploadNonDicoms:message:deletedSuccessfully')
                )
              }
            })
            .catch(() => {
              this.loading = false
            })
        })
        .catch(() => { })
    },
    // 打开上传文件弹窗
    handleUpload(row) {
      this.fileList = []
      this.uploadVisible = true
      this.fCount = 0
      this.currentRow = { ...row }
    },
    handleLookVideo(row) {
      this.currentRow = { ...row }
      this.lookVideoVisible = true
    },
    handleUploadVideo(row) {
      this.uploadVideoVisible = true
      this.currentRow = { ...row }
    },
    hadnleDeleteVideo(row) {
      this.$confirm(this.$t('trials:uploadNonDicoms:message:delete'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        this.filesLoading = true
        this.loading = true
        var params = Object.assign({}, row)
        params.VideoName = ''
        params.VideoObjectName = ''
        params.VideoUrl = ''
        params.UploadVideoTime = ''
        addOrUpdateNoneDicomStudy(params)
          .then((res) => {
            this.filesLoading = false
            this.loading = false
            this.nonDicomfilesList.pop()
            this.$emit('getList')
            this.$message.success(
              this.$t('trials:uploadNonDicoms:message:deletedSuccessfully')
            )
            this.getNoneDicomList()
          })
          .catch(() => {
            this.filesLoading = false
            this.loading = false
          })
      })
    },
    uploadOver(isSuccess, res, fileName) {
      if (isSuccess) {
        var params = Object.assign({}, this.currentRow)
        params.VideoName = fileName
        params.VideoObjectName = res.name
        params.VideoUrl = res.url
        params.UploadVideoTime = this.parseTime(new Date())
        addOrUpdateNoneDicomStudy(params)
          .then((res) => {
            this.getNoneDicomList()
            // 刷新父组件列表
            this.uploadVideoVisible = false
            this.$emit('getList')
            this.$message.success(this.$t('components:uploadvideo:message:xf1'))
          })
          .catch(() => {
            this.uploadVideoVisible = false
          })
      }
    },
    // 扫描待上传文件
    beginScanFiles(e) {
      var files = [...e.target.files]
      var sameFiles = []
      files.forEach((file) => {
        var extendName = file.name
          .substring(file.name.lastIndexOf('.'))
          .toLocaleLowerCase()
        if (
          this.faccept.indexOf(extendName) !== -1 &&
          this.fileList.findIndex((v) => v.name === file.name) > -1
        ) {
          sameFiles.push(file.name)
        }
      })
      var scope = this
      if (sameFiles.length > 0) {
        const h = this.$createElement
        var msg = this.$t(
          'trials:uploadNonDicoms:message:exsitSameFile'
        ).replace('xxx', sameFiles.join(', '))
        this.$msgbox({
          message: h('div', { style: 'maxHeight:300px;overflow: auto;' }, [
            h('p', null, msg),
            h(
              'p',
              null,
              this.$t('trials:uploadNonDicoms:message:isContinueUpload')
            ),
          ]),
          type: 'warning',
          showCancelButton: true,
        })
          .then(() => {
            scope.pendingUploadQuene(files)
          })
          .catch(() => {
            scope.resetUploadForm()
          })
      } else {
        scope.pendingUploadQuene(files)
      }
    },
    pendingUploadQuene(files) {
      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) {
          files[i].id = `${files[i].lastModified}${files[i].name}`
          let obj = {
            name: files[i].name,
            size: files[i].size,
            type: extendName.split('.')[1],
            status: 0,
            file: files[i],
            id: `${files[i].lastModified}${files[i].name
              }${new Date().getTime()}${i + 1}`,
            fileType: files[i].type,
            uploadFileSize: 0,
          }
          this.fileList.push(obj)
          this.$refs.filesTable.toggleRowSelection(obj, true)
        }
      }
      this.resetUploadForm()
    },
    resetUploadForm() {
      this.$nextTick(() => {
        this.$refs.uploadForm.reset()
      })
    },
    handlePreviewImg(row) {
      if (!!~row.FileType.indexOf('pdf')) {
        return this.$preview({
          path: row.Path || row.fullPath,
          type: 'pdf',
          title: row.FileName,
        })
      }
      // this.imgUrl = row.FullFilePath
      // this.previewImgVisible = true
      // this.imageLoading = true
      this.$refs[row.FullFilePath].$viewer.show()
    },
    beginScanFolder(e) {
      var files = e.target.files
      this.fCount += files.Count
      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) {
          files[i].id = `${files[i].lastModified}${files[i].name}`
          this.fileList.push(files[i])
        }
      }
    },
    handleRemoveFile(row) {
      this.$confirm(this.$t('trials:uploadNonDicoms:message:delete'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.fileList.splice(
            this.fileList.findIndex((item) => item.id === row.id),
            1
          )
          let flag = this.successFileList.some((item) => item.id === row.id)
          if (flag) {
            this.successFileList.splice(
              this.successFileList.findIndex((item) => item.id === row.id),
              1
            )
          }
        })
        .catch(() => { })
    },
    // 获取待上传文件信息
    handleSelectionChange(selection) {
      this.selectArr = selection
    },
    // 开始上传文件
    async beginUpload() {
      this.btnLoading = true
      this.isFail = false
      const fileMaxSize = 1024 * 1024 * 1024 * 2 // 1G
      var currentFilesSize = 0
      this.selectArr.forEach((item) => {
        currentFilesSize += item.size
      })
      if (currentFilesSize / fileMaxSize > 1) {
        // 'Upload file size cannot exceed 1G'
        this.$alert(this.$t('trials:uploadNonDicoms:message:uploadSize'))
        this.btnLoading = false
      } else {
        this.selectArr.forEach((item) => (item.status = 0))
        let num = this.selectArr.length > 6 ? 6 : this.selectArr.length
        let funArr = []
        let res = await preArchiveStudy({
          subjectVisitId: this.subjectVisitId,
          isDicom: false,
          FileCount: this.selectArr.length,
        })
        if (res.IsSuccess) {
          this.studyMonitorId = res.Result
          for (let i = 0; i < num; i++) {
            funArr.push(this.handleUploadTask(this.selectArr, i))
          }
          if (funArr.length > 0) {
            let res = await Promise.all(funArr)
          }
        } else {
          this.isFail = true
        }
      }
    },
    // 并发上传
    async handleUploadTask(arr, index) {
      if (!this.uploadVisible) return
      let file = this.fileList.filter((item) => item.id === arr[index].id)[0]
      file.status = 1
      let path = `/${this.trialId}/Image/${this.data.SubjectId}/${this.data.Id
        }/${this.$guid()}${file.name
          .substring(file.name.lastIndexOf('.'))
          .toLocaleLowerCase()}`
      file.curPath = path
      const fileData = await this.fileToBlob(file.file)
      let res = await this.fileToOss(path, fileData, file)
      if (res) {
        file.status = 2
        this.successFileList.push({
          fileName: file.name,
          filePath: this.$getObjectName(res.url),
          fileFize: file.size,
          fileType: file.fileType,
        })
        let flag = arr.every((item) => item.status === 2)
        if (flag) {
          let RecordPath = await this.uploadRecord(arr)
          return this.submitFile(this.successFileList, RecordPath)
        }
      } else {
        file.status = 3
      }
      let flag = arr.every((item) => item.status > 1)
      if (flag) {
        let failFileList = arr.filter((item) => item.status === 3)
        if (failFileList && failFileList.length > 0) {
          let RecordPath = await this.uploadRecord(arr)
          this.$refs.filesTable.clearSelection()
          failFileList.forEach((row) => {
            row.uploadFileSize = 0
            this.$refs.filesTable.toggleRowSelection(row)
          })
          this.isFail = true
          this.submitFile(this.successFileList, RecordPath, true)
          return false
        }
      }
      let ind = arr.findIndex((item) => item.status === 0)
      if (ind >= 0) {
        return this.handleUploadTask(arr, ind)
      } else {
        return false
      }
    },
    // file上传到oss
    async fileToOss(path, file, item) {
      try {
        let res = await this.OSSclient.multipartUpload(
          {
            path,
            file,
            speed: true,
          },
          (percentage, checkpoint, lastPer) => {
            item.uploadFileSize += checkpoint.size * (percentage - lastPer)
            if (item.uploadFileSize > file.fileSize) {
              item.uploadFileSize = file.fileSize > 0 ? file.fileSize : 1
            }
          }
        )
        if (res) {
          return res
        } else {
          return false
        }
      } catch (err) {
        console.log(err)
        return false
      }
    },
    // 非Dicom文件上传归档
    submitFile(uploadedFileList, RecordPath, isReLoad = false) {
      if (!this.uploadVisible) return
      this.btnLoading = true
      var params = {
        trialId: this.trialId,
        subjectVisitId: this.subjectVisitId,
        noneDicomStudyId: this.currentRow.Id,
        studyMonitorId: this.studyMonitorId,
        uploadedFileList: uploadedFileList,
      }
      if (RecordPath) {
        params.RecordPath = RecordPath.path
        params.FailedFileCount = RecordPath.Record.Failed.length
      }
      uploadNoneDicomFile(params)
        .then((res) => {
          if (!isReLoad) {
            this.resetFileDiaolg()
          }
          this.getNoneDicomList()
          // 刷新父组件列表
          this.$emit('getList')
          this.$message.success(
            this.$t('trials:uploadNonDicoms:message:uploadedSuccessfully')
          )
        })
        .catch(() => {
          this.btnLoading = false
        })
    },
    // 上传提交记录
    uploadRecord(arr) {
      return new Promise(async (resolve) => {
        try {
          let Record = {
            Failed: [],
            Existed: [],
            Uploaded: [],
            FileCount: arr.length,
          }
          arr.forEach((item) => {
            let file = this.fileList.find((data) => data.id === item.id)
            if (file.status === 2) {
              Record.Uploaded.push(file.curPath)
            }
            if (file.status === 3) {
              Record.Failed.push(file.curPath)
            }
          })
          let text = JSON.stringify(Record)
          let logJsonBlob = this.generateTxtFile(text)
          let logJsonObjectName = `/${this.trialId}/Image/${this.data.SubjectId}/${this.data.Id}/${this.studyMonitorId}.txt`
          let logRes
          try {
            logRes = await this.OSSclient.put(logJsonObjectName, logJsonBlob)
            if (logRes && logRes.url) {
              resolve({ path: this.$getObjectName(logRes.url), Record })
            } else {
              resolve(false)
            }
          } catch (e) {
            resolve(false)
          }
        } catch (err) {
          console.log(err)
          resolve(false)
        }
      })
    },
    generateTxtFile(text) {
      let blob = new Blob(['\ufeff', text], { type: 'text/plain' })
      return blob
    },
    resetFileDiaolg() {
      this.btnLoading = false
      this.uploadVisible = false
      this.selectArr = []
      this.successFileList = []
      this.OSSclient.close()
    },
    handleGetFilesList(row) {
      this.filesLoading = true
      getNoneDicomStudyFileList(row.Id)
        .then((res) => {
          this.nonDicomfilesList = res.Result
          if (row.VideoName) {
            this.nonDicomfilesList.push({
              FileName: row.VideoName,
              type: 'MP4',
            })
          }
          this.filesLoading = false
        })
        .catch(() => {
          this.filesLoading = false
        })
    },
    // 根据id删除某个文件
    handleDeleteFile(id) {
      this.$confirm(this.$t('trials:uploadNonDicoms:message:delete'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.filesLoading = true
          this.loading = true
          deleteNoneDicomStudyFile(this.trialId, this.subjectVisitId, id)
            .then((res) => {
              this.filesLoading = false
              this.loading = false
              if (res.IsSuccess) {
                // 刷新父组件列表
                this.$emit('getList')
                this.nonDicomfilesList.splice(
                  this.nonDicomfilesList.findIndex((item) => item.Id === id),
                  1
                )
                this.$message.success(
                  this.$t('trials:uploadNonDicoms:message:deletedSuccessfully')
                )
                this.getNoneDicomList()
              }
            })
            .catch(() => {
              this.filesLoading = false
              this.loading = false
            })
        })
        .catch(() => { })
    },
    // 预览
    handlePreview(row) {
      window.open(row.FullFilePath, '_blank')
    },
    // 预览访视下所有的非DICOM文件
    handlePreviewAllVisitFiles() {
      // 预览所有检查下非Dicom文件
      let trialId = this.$route.query.trialId
      var token = getToken()
      const routeData = this.$router.resolve({
        path: `/showNoneDicoms?trialId=${trialId}&subjectVisitId=${this.subjectVisitId}&TokenKey=${token}`,
      })
      window.open(routeData.href, '_blank')
    },
    handlePreviewAllFiles(row) {
      this.currentRow = { ...row }
      let trialId = this.$route.query.trialId
      var token = getToken()
      const routeData = this.$router.resolve({
        path: `/showNoneDicoms?trialId=${trialId}&subjectVisitId=${this.subjectVisitId}&studyId=${row.Id}&TokenKey=${token}`,
      })
      window.open(routeData.href, '_blank')
    },
    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(' | ')
    },
    // 设置已删除序列行样式
    tableRowClassName({ row, rowIndex }) {
      if (row.IsDeleted) {
        return 'delete-row'
      } else {
        return ''
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.upload {
  display: inline-block;
  height: 30px;
  width: 90px;
  padding: 2px 10px;
  line-height: 23px;
  position: relative;
  text-decoration: none;
  border-radius: 3px;
  overflow: hidden;
  text-align: center;
  background: #428bca;
  border-color: #428bca;
  color: #fff;

  .select-file {
    height: 30px;
    width: 90px;
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 0;
    opacity: 0;
    font-size: 0;
  }

  .btn-select {
    //给显示在页面上的按钮写样式
    width: 90px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
    border-radius: 24px;
    overflow: hidden;
    position: absolute;
    top: 0;
    left: 0;
    pointer-events: none; //pointer-events:none用来控制该标签的点击穿透事件
  }
}

.non-dicom-wrapper {
  ::v-deep .delete-row {
    text-decoration-line: line-through;
    color: #c0c4cc;
  }
}
</style>
<style>
.imgTable .delete-row {
  text-decoration-line: line-through;
  color: #c0c4cc;
}
</style>
