<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true">
        <!-- 受试者编号 -->
        <el-form-item :label="$t('trials:uploadMonitor:table:subjectId')">
          <el-input v-model="searchData.SubjectCode" clearable style="width: 140px" />
        </el-form-item>
        <!-- 患者编号 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
          <el-input v-model="searchData.PatientIdStr" clearable style="width: 140px" />
        </el-form-item>
        <!-- 患者姓名 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:patientName')">
          <el-input v-model="searchData.PatientName" clearable style="width: 140px" />
        </el-form-item>
        <!-- 患者性别 -->
        <el-form-item :label="$t('trials:subject:table:gender')">
          <el-select v-model="searchData.SubjectSex" clearable filterable style="width: 150px">
            <el-option v-for="item of $d.Sex" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 访视名称 -->
        <el-form-item :label="$t('trials:uploadMonitor:table:visitName')">
          <el-input v-model="searchData.VisitName" clearable style="width: 140px" />
        </el-form-item>
        <!--拍片日期-->
        <el-form-item :label="$t('trials:trials-panel:table:ScanDate')">
          <el-date-picker v-model="dateValue" type="datetimerange" range-separator="-"
            :start-placeholder="$t('trials:uploadClinicalData:table:beginDate')"
            :end-placeholder="$t('trials:uploadClinicalData:table:endDate')" clearable
            :default-time="['00:00:00', '23:59:59']">
          </el-date-picker>
        </el-form-item>
        <!--状态-->
        <el-form-item :label="$t('trials:trials-list:table:status')">
          <el-select v-model="searchData.SubmitState" clearable filterable style="width: 150px">
            <el-option v-for="item of $d.SubmitState" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </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-button type="primary" @click="getDownloadSubjectVisitStudyInfo(multipleSelection)"
            :disabled="multipleSelection.length <= 0" v-hasPermi="['trials:trials-panel:hirVisit:download']">
            {{ $t('trials:inspection:button:downloadImage') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>

    <!-- 访视列表:default-sort="{ prop: 'SubmitTime', order: 'descending' }" -->
    <template slot="main-container">
      <el-table ref="visitList" v-loading="loading" v-adaptive="{ bottomOffset: 60 }" :data="list" stripe height="100"
        @sort-change="handleSortByColumn" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" v-if="hasPermi(['trials:trials-panel:hirVisit:download'])" />
        <el-table-column min-width="20">
          <template slot-scope="scope">
            <i v-if="
              Number(scope.row.SubmitState) === 1 &&
              scope.row.VisitLatestStudyTime
            " class="el-icon-warning-outline" :title="$t('trials:hirVisit:tipMessage:tipOne')" style="color: red"></i>
          </template>
        </el-table-column>
        <!-- 受试者编号 -->
        <el-table-column prop="SubjectCode" :label="$t('trials:uploadMonitor:table:subjectId')" show-overflow-tooltip
          sortable="custom" min-width="120" />
        <!-- 患者编号 -->
        <el-table-column prop="PatientList.PatientIdStr" :label="$t('trials:uploadDicomList:table:pId')"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.PatientList" :key="`${index}${item.PatientId}`">
              {{
                index === scope.row.PatientList.length - 1
                  ? item.PatientIdStr
                  : `${item.PatientIdStr}, `
              }}
            </span>
          </template>
        </el-table-column>
        <!-- 患者姓名 -->
        <el-table-column prop="SubjectShortName" :label="$t('trials:researchStaff:table:Name')" show-overflow-tooltip
          sortable="custom" min-width="100" />
        <!-- 性别 -->
        <el-table-column prop="SubjectSex" :label="$t('trials:subject:table:gender')" show-overflow-tooltip
          sortable="custom">
          <template slot-scope="scope">
            <span>{{ $fd('Sex', scope.row.SubjectSex) }}</span>
          </template>
        </el-table-column>
        <!-- 访视名称 -->
        <el-table-column prop="VisitName" :label="$t('trials:uploadMonitor:table:visitName')" show-overflow-tooltip
          sortable="custom" min-width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="handleOpenStudyDialog(scope.row)">
              <span>{{ scope.row.VisitName }}</span>
            </el-button>
          </template>
        </el-table-column>
        <!-- 最早拍片日期 -->
        <el-table-column prop="VisitEarliestStudyTime" :label="$t('trials:trials-panel:table:EarliestScanDate')"
          show-overflow-tooltip sortable="custom" min-width="140" />
        <!-- 最晚拍片日期 -->
        <el-table-column prop="VisitLatestStudyTime" :label="$t('trials:linkedRP:table:latestScanDate')"
          show-overflow-tooltip sortable="custom" min-width="120" />
        <!-- 状态 -->
        <el-table-column prop="SubmitState" :label="$t('trials:trials-list:table:status')" show-overflow-tooltip
          sortable="custom">
          <template slot-scope="scope">
            <el-tag :type="Number(scope.row.SubmitState) === 0
              ? 'warning'
              : Number(scope.row.SubmitState) === 1
                ? 'danger'
                : ''
              ">{{ $fd('SubmitState', Number(scope.row.SubmitState)) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 打包状态 -->
        <!-- <el-table-column
          prop="PackState"
          :label="$t('trials:hirVisit:table:PackState')"
          show-overflow-tooltip
          min-width="100"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.SubmitState > 1"
              :type="
                Number(scope.row.PackState) === 0
                  ? 'danger'
                  : Number(scope.row.PackState) === 1
                  ? 'warning'
                  : 'success'
              "
              >{{ $fd("PackState", Number(scope.row.PackState)) }}</el-tag
            >
          </template>
        </el-table-column> -->
        <!-- 提交时间 -->
        <el-table-column prop="SubmitTime" :label="$t('trials:crcUpload:table:submitTime')" show-overflow-tooltip
          min-width="100" sortable="custom" />
        <!--操作-->
        <el-table-column :label="$t('common:action:action')" min-width="200" fixed="right" v-if="
          hasPermi([
            'trials:trials-panel:hirVisit:edit',
            'trials:trials-panel:hirVisit:submit',
            'trials:trials-panel:hirVisit:remove',
            'trials:trials-panel:hirVisit:download',
          ])
        ">
          <template slot-scope="scope">
            <!--修改检查-->
            <el-button circle icon="el-icon-edit-outline" v-hasPermi="['trials:trials-panel:hirVisit:edit']"
              :title="$t('trials:hirVisit:button:editStudy')" :disabled="Number(scope.row.SubmitState) > 1"
              @click.stop="editStudy(scope.row)" />
            <!--提交-->
            <el-button circle icon="el-icon-position" v-hasPermi="['trials:trials-panel:hirVisit:submit']" :disabled="Number(scope.row.SubmitState) != 1 ||
              !scope.row.VisitLatestStudyTime
              " :title="$t('common:button:submit')" @click.stop="submit(scope.row)" />
            <!--删除-->
            <el-button circle icon="el-icon-delete" v-hasPermi="['trials:trials-panel:hirVisit:remove']"
              @click.stop="remove(scope.row)" :disabled="Number(scope.row.SubmitState) > 1"
              :title="$t('common:button:delete')" />
            <!--下载报告-->
            <el-button v-hasPermi="['trials:trials-panel:hirVisit:download']" circle :loading="downloading"
              icon="el-icon-download" :disabled="Number(scope.row.SubmitState) !== 2"
              :title="$t('trials:reading:button:download')" @click="getDownloadSubjectVisitStudyInfo([scope.row])" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
        @pagination="getList" />
    </template>
    <!--修改检查-->
    <editStudyList :visible.sync="editStudyVisible" :data="editStudyData" v-if="editStudyVisible" @getList="getList" />
    <!--访视详情-->
    <visitInfo v-if="visitVisible" :visible.sync="visitVisible" :rowData="rowData" />
    <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"></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 editStudyList from './components/edit-study-list.vue'
import visitInfo from './components/visit-info.vue'
import { deleteSubjectVisit } from '@/api/trials'
import { getPatientSubejctVisitList } from '@/api/trials/visit.js'
import { submitVisitStudyBinding } from '@/api/inspection.js'
import { downLoadFile } from '@/utils/stream.js'
import { getToken } from '@/utils/auth'
import * as signalR from '@microsoft/signalr'
import {
  getDownloadSubjectVisitStudyInfo,
  VisitImageDownload,
  downloadImageSuccess,
} from '@/api/trials.js'
const defaultSearchData = () => {
  return {
    subjectCode: null,
    subjectShortName: null,
    subjectSex: null,
    pageIndex: 1,
    pageSize: 20,
    asc: true,
    sortField: '',
    SubmitState: null,
    PatientName: null,
    PatientIdStr: null,
    PatientSex: null,
    BeginStudyTime: null,
    EndStudyTime: null,
    VisitName: null,
  }
}
export default {
  name: 'hirVisit',
  components: {
    BaseContainer,
    Pagination,
    editStudyList,
    visitInfo,
  },
  data() {
    return {
      // 查询
      searchData: defaultSearchData(),
      visitOptions: [],
      dateValue: [],
      // 列表
      list: [],
      loading: false,
      total: 0,
      // 修改检查
      editStudyVisible: false,
      editStudyData: {},
      // 访视详情
      visitVisible: false,
      rowData: {},

      // 下载相关
      downloading: false,
      downloadId: null,
      downloadVisible: false,
      downloadType: '',
      percentage: 0,
      downLoadImageCount: 0,
      speed: '0KB/s',
      multipleSelection: []
    }
  },
  created() {
    if (zzSessionStorage.getItem('SubjectCode')) {
      this.searchData.SubjectCode = zzSessionStorage.getItem('SubjectCode')
      zzSessionStorage.removeItem('SubjectCode')
    }
    this.getList()
  },
  mounted() {
    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')
    });
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    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 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 (num >= 100) {
        this.downLoadType = 'start'
        this.percentage = 0
        this.downLoadImageCount = 0
        this.downloadVisible = false
        this.speed = '0KB/s'
      }
    },
    // 查询
    handleSearch() {
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = defaultSearchData()
      this.$refs.visitList.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()
    },
    // 获取列表
    async getList() {
      let data = {}
      Object.keys(this.searchData).forEach((key) => {
        data[key] = this.searchData[key]
      })
      data.TrialId = this.$route.query.trialId
      if (this.dateValue && this.dateValue[0] && this.dateValue[1]) {
        data.BeginStudyTime = this.$moment(this.dateValue[0]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        data.EndStudyTime = this.$moment(this.dateValue[1]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      } else {
        data.BeginStudyTime = null
        data.EndStudyTime = null
      }
      try {
        this.loading = true
        let res = await getPatientSubejctVisitList(data)
        this.loading = false
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 获取某个访视下的检查信息
    handleOpenStudyDialog(row) {
      this.visitVisible = true
      this.rowData = { ...row }
    },
    // 修改检查
    editStudy(item) {
      this.editStudyData = item
      this.editStudyVisible = true
    },
    // 提交
    async submit(item) {
      let confirm = await this.$confirm(
        this.$t('trials:adjustRecord:message:confirm'),
        {
          type: 'warning',
          distinguishCancelAndClose: true,
          confirmButtonText: this.$t('common:button:confirm'),
          cancelButtonText: this.$t('recompose:button:cancel'),
        }
      )
      if (confirm !== 'confirm') return
      let data = {
        TrialId: this.$route.query.trialId,
        SubjectVisitIdList: [item.SubjectVisitId],
        SubjectId: item.SubjectId,
      }
      try {
        this.loading = true
        let res = await submitVisitStudyBinding(data)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(
            this.$t('trials:crcUpload:message:submittedSuccessfully')
          )
          this.getList()
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 删除
    async remove(row) {
      try {
        let confirm = await this.$confirm(
          this.$t('trials:crcUpload:message:deleteVisit'),
          {
            type: 'warning',
            distinguishCancelAndClose: true,
          }
        )
        if (confirm !== 'confirm') return
        let res = await deleteSubjectVisit(
          this.$route.query.trialId,
          row.SubjectVisitId
        )
        if (res.IsSuccess) {
          this.getList()
          this.$message.success(
            this.$t('trials:crcUpload:message:deleteVisitSuccessfully')
          )
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取下载文件信息
    async getDownloadSubjectVisitStudyInfo(arr) {
      if (this.downloading) return
      try {
        let data = {
          // SubjectVisitId: row.SourceSubjectVisitId,
          SubjectVisitIdList: arr.map(item => item.SubjectVisitId),
          TrialId: this.$route.query.trialId,
        }
        this.downloadId = this.generate()
        data.CurrentNoticeId = this.downloadId
        this.onUploadProgress(this.downloadId)
        // this.downloading = true
        await VisitImageDownload(data)
        // this.downloading = false
        // if (res.IsSuccess) {
        //   this.downloadId = res.OtherInfo
        //   this.downloadImage(res.Result)
        // }
      } catch (err) {
        this.downloading = false
        console.log(err)
      }
    },
    // 打包下载
    async downloadImage(data) {
      try {
        let { files, name } = this.formatDownloadFile(data)
        let res = await downLoadFile(files, name, 'zip')

        if (res && this.downloadId) {
          this.downloadImageSuccess()
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化下载文件路径
    formatDownloadFile(data) {
      let files = [],
        name = `${data.SubjectCode}_${data.VisitName}_ImageStudy.zip`
      if (Array.isArray(data.StudyList) && data.StudyList.length > 0) {
        data.StudyList.forEach((study) => {
          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.Path.split('/').pop()
                  let obj = {
                    name: `${data.SubjectCode}_${data.VisitName}/${study.StudyCode
                      }_${study.StudyTime.split(' ')[0]}_${series.Modality
                      }/${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)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-progress {
  display: flex;
  align-items: center;
}
</style>
