<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true" class="base-search-form">
        <!-- 患者ID/患者姓名 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
          <el-input v-model="searchData.PatientIdStr" style="width: 100px" clearable />
        </el-form-item>
        <el-form-item :label="$t('trials:uploadDicomList:table:patientName')">
          <el-input v-model="searchData.PatientName" style="width: 100px" clearable />
        </el-form-item>
        <!-- Called AE -->
        <el-form-item class="my_multiple" :label="$t('trials:inspection:search:CalledAE')">
          <el-select v-model="searchData.CalledAEList" clearable multiple style="width: 140px">
            <el-option v-for="(item, index) of calledAeList" :key="index" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- Calling AE -->
        <el-form-item class="my_multiple" :label="$t('trials:inspection:search:CallingAE')">
          <el-select v-model="searchData.callingAE" clearable style="width: 140px">
            <el-option v-for="(item, index) of callingAeList" :key="index" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 研究名称 -->
        <el-form-item :label="$t('trials:trials-list:table:researchName')">
          <el-input v-model="searchData.ExperimentName" style="width: 100px" clearable />
        </el-form-item>
        <!-- 课题组 -->
        <el-form-item :label="$t('trials:trials-myinfo:form:StudyHospitalGroupList')">
          <el-select v-model="searchData.HospitalGroupIdList" clearable multiple style="width: 140px">
            <el-option v-for="(item) of hospitalGroupList" :key="item.Id" :label="item.Name" :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 最新接收时间 -->
        <el-form-item :label="$t('trials:inspection:table:latestReceiveTime')">
          <el-date-picker v-model="dateValue" type="datetimerange" range-separator="-"
            :start-placeholder="$t('trials:uploadClinicalData:table:beginDate')"
            :end-placeholder="$t('trials:uploadClinicalData:table:endDate')" :default-time="['00:00:00', '23:59:59']"
            clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <!-- 查询 -->
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">
            {{ $t('common:button:search') }}
          </el-button>
          <!-- 重置 -->
          <el-button type="primary" icon="el-icon-refresh-left" @click="handleReset">
            {{ $t('common:button:reset') }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <!-- 推送记录 -->
          <el-button type="primary" @click="handleOpenDialog({}, 'push')">
            {{ $t('common:button:push') }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <!-- pacs拉取 -->
          <el-button type="primary" @click="handleOpenDialog({}, 'pull')"
            v-hasPermi="['trials:trialsInspection:pullPACS']">
            {{ $t('common:button:pull') }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <!-- 查看所有检查 -->
          <el-button type="primary" @click="handleOpenDialog({}, 'study', true)">
            {{ $t('common:button:viewAllStudy') }}
          </el-button>
        </el-form-item>
        <el-form-item v-if="hasPermi(['trials:trialsInspection:downloadImage'])">
          <!-- 下载影像 -->
          <el-button type="primary" @click="getDownloadPatientStudyInfo(multipleSelection)"
            :disabled="multipleSelection.length <= 0">
            {{ $t('trials:inspection:button:downloadImage') }}
          </el-button>
        </el-form-item>
        <el-form-item v-if="hasPermi(['trials:trialsInspection:downloadImage'])">
          <!-- 下载记录 -->
          <el-button type="primary" @click="() => RecordVisible = true">
            {{ $t('trials:inspection:button:downloadRecord') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>

    <!-- 检查列表 -->
    <template slot="main-container">
      <el-table ref="inspectionList" v-loading="loading" v-adaptive="{ bottomOffset: 60 }" :data="list" stripe
        height="100" @sort-change="handleSortByColumn" @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'LatestPushTime', order: 'descending' }">
        <el-table-column type="selection" width="55" v-if="hasPermi(['trials:trialsInspection:downloadImage'])" />
        <el-table-column type="index" width="40" v-else />
        <!--患者ID-->
        <el-table-column prop="PatientIdStr" :label="$t('trials:uploadDicomList:table:pId')" show-overflow-tooltip
          min-width="120" sortable="custom"></el-table-column>
        <!--患者姓名-->
        <el-table-column prop="PatientName" :label="$t('trials:uploadDicomList:table:patientName')"
          show-overflow-tooltip min-width="120" sortable="custom"></el-table-column>
        <!--出生日期-->
        <el-table-column prop="PatientBirthDate" :label="$t('trials:inspection:table:birthdate')" show-overflow-tooltip
          min-width="120" sortable="custom"></el-table-column>
        <!--性别-->
        <el-table-column prop="PatientSex" :label="$t('trials:trials-myinfo:form:gender')" show-overflow-tooltip
          min-width="100" sortable="custom">
          <template slot-scope="scope">
            <span>{{ $fd('Sex', scope.row.PatientSex) }}</span>
          </template>
        </el-table-column>
        <!--Called AE-->
        <el-table-column prop="CalledAEList" :label="$t('trials:inspection:table:CalledAE')" show-overflow-tooltip
          min-width="120">
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.CalledAEList" :key="`CalledAEList${index}`">{{
              index === scope.row.CalledAEList.length - 1 ? item : `${item}, `
            }}</span>
          </template>
        </el-table-column>
        <!--Calling AE-->
        <el-table-column prop="CallingAEList" :label="$t('trials:inspection:table:CallingAE')" show-overflow-tooltip
          min-width="120">
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.CallingAEList" :key="`CallingAEList${index}`">{{
              index === scope.row.CallingAEList.length - 1
                ? item
                : `${item}, `
            }}</span>
          </template>
        </el-table-column>
        <!-- 研究名称 -->
        <el-table-column prop="TrialList" :label="$t('trials:trials-list:table:researchName')" show-overflow-tooltip
          min-width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="handleOpenDialog(scope.row, 'research')"
              v-for="(item, index) in scope.row.TrialList" :key="`TrialList${index}`">
              <span>{{
                index === scope.row.TrialList.length - 1
                  ? `${item.ExperimentName}（${item.VisitCount}）`
                  : `${item.ExperimentName}（${item.VisitCount}），`
              }}</span>
            </el-button>
            <!-- <span v-else>{{ scope.row.VisitName }}</span> -->
          </template>
        </el-table-column>
        <!--课题组-->
        <el-table-column prop="ViewHospitalGroupList" :label="$t('trials:trials-myinfo:form:StudyHospitalGroupList')"
          show-overflow-tooltip min-width="100">
          <template slot-scope="scope">
            <span>{{
              scope.row.ViewHospitalGroupList && scope.row.ViewHospitalGroupList.length > 0 ?
                scope.row.ViewHospitalGroupList.join(', ') : '' }}</span>
          </template>
        </el-table-column>
        <!-- 检查数 -->
        <el-table-column prop="StudyCount" :label="$t('trials:studyList:table:count')" show-overflow-tooltip
          min-width="100" sortable="custom">
          <template slot-scope="scope">
            <el-button v-if="scope.row.StudyCount >= 1" type="text" @click="handleOpenDialog(scope.row, 'study')">
              <span>{{ scope.row.StudyCount }}</span>
            </el-button>
            <span v-else>{{ scope.row.StudyCount }}</span>
          </template>
        </el-table-column>
        <!--最新接收时间-->
        <el-table-column prop="LatestPushTime" :label="$t('trials:inspection:table:latestReceiveTime')"
          show-overflow-tooltip min-width="180" sortable="custom"></el-table-column>
        <!--操作-->
        <el-table-column :label="$t('common:action:action')" min-width="140" fixed="right">
          <template slot-scope="scope">
            <el-button circle icon="el-icon-view" :title="$t('trials:trialsInspection:button:view')"
              @click.stop="handleOpenDialog(scope.row, 'study')" />
            <el-button circle v-hasPermi="['trials:trialsInspection:addTrials']" icon="el-icon-plus"
              :title="$t('trials:inspection:button:addTrials')" @click.stop="handleOpenDialog(scope.row, 'add')" />
            <!-- 下载影像 -->
            <el-button v-hasPermi="['trials:trialsInspection:downloadImage']" circle icon="el-icon-download"
              @click="getDownloadPatientStudyInfo([scope.row])" :title="$t('trials:inspection:button:downloadImage')" />
            <!-- <el-button
              circle
              icon="el-icon-delete"
              v-hasPermi="['trials:trialsInspection:delPatient']"
              :title="$t('trials:inspection:button:delete')"
              @click.stop="deletePatientStudyAllData(scope.row)"
            /> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
        @pagination="getList" />
    </template>

    <!--研究项目列表-->
    <researchTrialsList v-if="researchTrialsVisible" :visible.sync="researchTrialsVisible" :Patient="selectPatient"
      @getList="getList" @handleOpenDialog="handleOpenDialog" />
    <!--可加入项目列表-->
    <addTrialsList v-if="addTrialsVisible" :visible.sync="addTrialsVisible" :Patient="selectPatient" @getList="getList"
      @handleOpenDialog="handleOpenDialog" />
    <!--查看检查列表-->
    <viewStudyList v-if="studyTrialsVisible" :visible.sync="studyTrialsVisible" :Patient="selectPatient"
      :isAll="studyAll" :calledAeList="calledAeList" :callingAeList="callingAeList"
      :hospitalGroupList="hospitalGroupList" @getList="getList"
      @getDownloadPatientStudyInfo="getDownloadPatientStudyInfo" />
    <!--推送记录列表-->
    <pushRecordList v-if="pushTrialsVisible" :visible.sync="pushTrialsVisible" :calledAeList="calledAeList"
      :callingAeList="callingAeList" />
    <!--pacs拉取列表-->
    <pullImage v-if="pullTrialsVisible" :visible.sync="pullTrialsVisible" :calledAeList="calledAeList"
      :callingAeList="callingAeList" @getList="getList" />
    <el-dialog title="" :visible.sync="RecordVisible" :fullscreen="true">
      <downloadRecord :isSystem="true" v-if="RecordVisible" />
    </el-dialog>
    <el-dialog :title="$t('dialog:title:downLoadProgress')" :visible.sync="downloadVisible" width="35%"
      :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleClose">
      <div v-if="downloadType == 'downLoad' || downloadType == 'start'">
        <span style="margin-bottom: 5px;">{{ $t('dialog:sattus:downLoading') }}</span>
        <span>{{ speed }}</span>
        <el-progress :percentage="percentage * 1" v-if="downloadVisible"></el-progress>
      </div>
      <div v-else>
        <span>{{ $t('dialog:sattus:ziping') }}</span>
      </div>
    </el-dialog>
  </BaseContainer>
</template>
<script>
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import researchTrialsList from './components/research-trials-list'
import addTrialsList from './components/add-trials-list'
import viewStudyList from './components/view-study-list'
import pushRecordList from './components/push-record-list'
import pullImage from './components/pullImage/index.vue'
import { getPatientList, deletePatientStudyAllData, getDownloadPatientStudyInfo, PatientStudyBatchDownload } from '@/api/inspection.js'
import { getDicomCalledAEList, getDicomCallingAEList } from '@/api/dicomAE.js'
import downloadRecord from "@/views/trials/trials-panel/trial-summary/download-record"
import { getToken } from '@/utils/auth'
import * as signalR from '@microsoft/signalr'
import {
  downloadImageSuccess,
} from '@/api/trials.js'
import { getHospitalGroupList } from '@/api/admin.js'
import { downLoadFile } from '@/utils/stream.js'
const defaultSearchData = () => {
  return {
    PatientIdStr: null,
    PatientName: null,
    CalledAEList: [],
    callingAE: null,
    ExperimentName: null,
    HospitalGroupIdList: [],
    Asc: false,
    BeginPushTime: null,
    EndPushTime: null,
    SortField: 'LatestPushTime',
    PageIndex: 1,
    PageSize: 20,
  }
}
export default {
  name: 'inspection',
  components: {
    BaseContainer,
    Pagination,
    researchTrialsList,
    addTrialsList,
    viewStudyList,
    pushRecordList,
    pullImage,
    downloadRecord
  },
  data() {
    return {
      // 查询
      searchData: defaultSearchData(),
      calledAeList: [],
      callingAeList: [],
      dateValue: [],
      // 检查列表
      total: 0,
      loading: false,
      list: [],
      multipleSelection: [],
      downloadId: null,
      RecordVisible: false,
      // 选中的患者
      selectPatient: {},
      // 研究项目列表
      researchTrialsVisible: false,
      // 可加入项目列表
      addTrialsVisible: false,
      // 查看检查列表
      studyTrialsVisible: false,
      // 推送记录列表
      pushTrialsVisible: false,
      // pacs拉取列表
      pullTrialsVisible: false,
      hospitalGroupList: [],
      studyAll: false,

      downloadVisible: false,
      downloadType: '',
      percentage: 0,
      downLoadImageCount: 0,
      speed: '0KB/s'
    }
  },
  created() {
    this.getDicomCalledAEList()
    this.getDicomCallingAEList()
    this.getList()
    this.getHospitalGroupList()
  },
  methods: {
    handleClose(done) {
      this.downLoadType = 'start'
      this.percentage = 0
      this.downLoadImageCount = 0
      this.downloadVisible = false
      this.speed = '0KB/s'
      this.downloadId = null
      done()
    },
    generate() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },
    async getDownloadPatientStudyInfo(arr) {
      try {
        let data = {
          PatientIdList: [],
          ScpStudyIdList: []
        }
        this.downloadId = this.generate()
        data.CurrentNoticeId = this.downloadId
        arr.forEach(item => {
          data.PatientIdList.push(item.PatientId)
          if (item.SCPStudyId) {
            data.ScpStudyIdList.push(item.SCPStudyId)
          }
        })
        let params = null
        data.PatientIdList.forEach(item => {
          if (!params) {
            params = `PatientIdList=${item}`
          } else {
            params += `&PatientIdList=${item}`
          }
        })
        data.ScpStudyIdList.forEach(item => {
          if (!params) {
            params = `ScpStudyIdList=${item}`
          } else { 
            params += `&ScpStudyIdList=${item}`
          }
        })
        if (!params) {
          params = `CurrentNoticeId=${this.downloadId}`
        } else {
          params += `&CurrentNoticeId=${this.downloadId}`
        }
        if (params) {
          params += `&access_token=${getToken()}`
          let url = `/api/download/GetPatientStudyBatchDownload?${params}`
          // let url = `http://106.14.89.110:30021/download/DownloadBigFileBatch?fileName=Test_HIR_New_log.ldf`
          let a = document.createElement('a')
          a.href = url
          a.click()
          a = null
        }

      } catch (err) {
        console.log(err)
      }
    },
    formatSize(size, fixed = 2) {
      if (isNaN(parseFloat(size))) return ''
      let kbSize = size / 1024
      if (kbSize <= 1024) {
        return `${kbSize.toFixed(fixed)}KB`
      }
      let mbSize = kbSize / 1024
      return `${mbSize.toFixed(fixed)}MB`
    },
    // 打包下载
    async downloadImage(data, OtherInfo) {
      try {
        let { files, name } = this.formatDownloadFile(data)
        let res = await downLoadFile(files, name, 'zip', async (data) => {
          let { type } = data
          this.downloadType = type
          if (type === 'start') {
            this.downloadVisible = true
          }
          if (type === 'downLoad') {
            this.downLoadImageCount++
            if (this.downLoadImageCount >= OtherInfo.ImageCount) {
              this.downLoadImageCount = OtherInfo.ImageCount
              this.percentage = 100
            } else {
              this.percentage = (((this.downLoadImageCount / OtherInfo.ImageCount).toFixed(2)) * 100).toFixed(0)
            }

          }
          if (type === 'downLoaded') {
          }
          if (type === 'error') {
            let confirm = await this.$confirm(this.$t('trials:imageSummary:confirm:downloadError'))
            this.downLoadType = 'start'
            this.percentage = 0
            this.downLoadImageCount = 0
            this.downloadVisible = false
          }
          if (type === 'zipEnd') {
            this.downLoadType = 'start'
            this.percentage = 0
            this.downLoadImageCount = 0
            this.downloadVisible = false
            if (this.downloadId) {
              this.downloadImageSuccess()
            }
          }
        })


      } catch (err) {
        console.log(err)
      }
    },
    // 格式化下载文件路径
    formatDownloadFile(data) {
      let files = [],
        name = `Image_${Date.now()}.zip`
      data.forEach(patient => {
        if (Array.isArray(patient.StudyList) && patient.StudyList.length > 0) {
          patient.StudyList.forEach((study) => {
            let arr = []
            study.ModalityList.forEach(item => {
              if (!arr.includes(item)) {
                arr.push(item)
              }
            })
            let str = arr.join('_')
            if (study.StudyDIRPath && !study.dirHas) {
              study.dirHas = true
              let obj = {
                name: `${study.PatientId}/${study.StudyTime}_${str}/DICOMDIR`,
                url: this.OSSclientConfig.basePath + study.StudyDIRPath,
              }
              files.push(obj)
            }
            if (Array.isArray(study.SeriesList) && study.SeriesList.length > 0) {
              study.SeriesList.forEach((series) => {
                if (
                  Array.isArray(series.InstanceList) &&
                  series.InstanceList.length > 0
                ) {
                  series.InstanceList.forEach((instance) => {
                    let fileName = instance.FileName || instance.Path.split('/').pop()
                    let obj = {
                      name: `${study.PatientId}/${study.StudyTime}_${str}/IMAGE/${fileName}`,
                      url: this.OSSclientConfig.basePath + instance.Path,
                    }
                    files.push(obj)
                  })
                }
              })
            }
          })
        }
      })
      return { files, name }
    },
    // 影像下载成功确认
    async downloadImageSuccess() {
      try {
        let params = {
          TrialImageDownloadId: this.downloadId,
        }
        await downloadImageSuccess(params)
      } catch (err) {
        console.log(err)
      }
    },
    // 获取calledAE列表
    async getDicomCalledAEList() {
      try {
        let res = await getDicomCalledAEList()
        if (res.IsSuccess) {
          this.calledAeList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async getHospitalGroupList() {
      try {
        let res = await getHospitalGroupList({})
        if (res.IsSuccess) {
          this.hospitalGroupList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 清除数据
    async deletePatientStudyAllData(item) {
      try {
        let confirm = await this.$confirm(
          this.$t('trials:inspection:message:remove'),
          {
            type: 'warning',
            distinguishCancelAndClose: true,
            confirmButtonText: this.$t('common:button:confirm'),
            cancelButtonText: this.$t('common:button:cancel'),
          }
        )
        if (confirm !== 'confirm') return
        let params = {
          PatientId: item.PatientId,
        }
        let res = await deletePatientStudyAllData(params)
        if (res.IsSuccess) {
          this.getList()
          this.$message.success(this.$t('common:message:removedSuccessfully'))
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取callingAE列表
    async getDicomCallingAEList() {
      try {
        let res = await getDicomCallingAEList()
        if (res.IsSuccess) {
          this.callingAeList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取列表数据
    async getList() {
      let data = {}
      Object.keys(this.searchData).forEach((key) => {
        data[key] = this.searchData[key]
      })
      if (this.dateValue && this.dateValue[0] && this.dateValue[1]) {
        data.BeginPushTime = this.$moment(this.dateValue[0]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        data.EndPushTime = this.$moment(this.dateValue[1]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      } else {
        data.BeginPushTime = null
        data.EndPushTime = null
      }
      try {
        this.loading = true
        let res = await getPatientList(data)
        this.loading = false
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = defaultSearchData()
      this.$refs.inspectionList.clearSort()
      this.dateValue = []
      this.getList()
    },
    // 表格排序
    handleSortByColumn(sort) {
      this.searchData.SortField = sort.prop
      if (sort.order === 'ascending') this.searchData.Asc = true
      if (sort.order === 'descending') this.searchData.Asc = false
      if (!sort.order) this.searchData.SortField = null
      this.getList()
    },
    // 打开弹框
    handleOpenDialog(item, key, isAll = false) {
      if (key === 'study') {
        this[`${key}All`] = isAll
      }
      this[`${key}TrialsVisible`] = true
      this.selectPatient = item
    },
    async onUploadProgress(id, num, type = 'start') {
      if (id !== this.downloadId) return false
      this.downloadType = type
      if (type === 'start') {
        this.downloadVisible = true
      }
      if (type === 'downLoad') {
        this.percentage = num
        // if (this.downLoadImageCount >= OtherInfo.ImageCount) {
        //   this.downLoadImageCount = OtherInfo.ImageCount
        //   this.percentage = 100
        // } else {
        //   this.percentage = (((this.downLoadImageCount / OtherInfo.ImageCount).toFixed(2)) * 100).toFixed(0)
        // }

      }
      if (num >= 100) {
        this.downLoadType = 'start'
        this.percentage = 0
        this.downLoadImageCount = 0
        this.downloadVisible = false
        this.speed = '0KB/s'
      }
      // if (type === 'downLoaded') {
      // }
      // if (type === 'error') {
      //   let confirm = await this.$confirm(this.$t('trials:imageSummary:confirm:downloadError'))
      //   this.downLoadType = 'start'
      //   this.percentage = 0
      //   this.downLoadImageCount = 0
      //   this.downloadVisible = false
      // }
    }
  },
  mounted() {
    this.$EventBus.$on("reload", (data) => {
      window.location.reload()
    });
    let connection = new signalR.HubConnectionBuilder()
      .withUrl("/DownloadHub", { accessTokenFactory: () => getToken() })
      .configureLogging(signalR.LogLevel.Information)
      .withAutomaticReconnect()
      .build()
    connection.start()
    connection.on("ReceivProgressAsync", (id, obj) => {
      console.log(obj)
      this.speed = obj.speed
      this.onUploadProgress(id, obj.sizePercent, 'downLoad')
    });
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-progress {
  display: flex;
  align-items: center;
}
</style>