<template>
  <box-content>
    <div class="title">
      {{ TITLE }}
    </div>
    <!-- 搜索框 -->
    <div class="search" style="position: relative">
      <el-form :inline="true" class="base-search-form">
        <!--阅片人-->
        <el-form-item :label="$t('trials:trialDocument:entryRecord:search:viewer')">
          <el-input v-model="searchData.Code" style="width: 100px" placeholder="" clearable />
        </el-form-item>
        <!--审核人-->
        <el-form-item :label="$t('trials:trialDocument:entryRecord:search:auditor')">
          <el-input v-model="searchData.OptUserName" style="width: 100px" placeholder="" clearable />
        </el-form-item>
        <!--审核人角色-->
        <el-form-item :label="$t('trials:trialDocument:entryRecord:search:auditorRole')">
          <el-select v-model="searchData.UserTypeEnum" style="width: 100px" placeholder="" clearable>
            <el-option v-for="item in $d.UserType" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:trialDocument:entryRecord:search:confirmTime')">
          <el-date-picker v-model="timeList" @change="changeTimeList" value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']" type="datetimerange">
          </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.stop="openUpload">
            {{ $t('trials:trialDocument:entryRecord:title:uploadFile') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" v-adaptive="{ bottomOffset: 75 }" :data="list" stripe height="100"
      style="width: 100%">
      <el-table-column type="index" />
      <!--姓名-->
      <el-table-column prop="BlindName" :label="$t('trials:trialDocument:entryRecord:table:name')" show-overflow-tooltip
        sortable="custom">
        <template slot-scope="scope">
          <span>{{ isEN ? scope.row.BlindName : scope.row.BlindNameCN }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="Code" :label="$t('trials:trialDocument:entryRecord:table:userName')" show-overflow-tooltip
        sortable="custom" />
      <el-table-column prop="Speciality" :label="$t('trials:trialDocument:entryRecord:table:status')"
        show-overflow-tooltip sortable="custom">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.DoctorTrialState === 10" type="primary">{{
            $fd('DoctorTrialState', scope.row.DoctorTrialState)
          }}</el-tag>
          <el-tag v-if="scope.row.DoctorTrialState === 9" type="warning">{{
            $fd('DoctorTrialState', scope.row.DoctorTrialState)
          }}</el-tag>
          <el-tag v-if="scope.row.DoctorTrialState === 8" type="danger">{{
            $fd('DoctorTrialState', scope.row.DoctorTrialState)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="AuditUserName" :label="$t('trials:trialDocument:entryRecord:table:auditor')"
        show-overflow-tooltip sortable="custom" />
      <el-table-column prop="AuditTypeEnum" :label="$t('trials:trialDocument:entryRecord:table:auditorRole')"
        show-overflow-tooltip sortable="custom">
        <template slot-scope="scope">
          <span>{{ $fd('UserType', scope.row.AuditTypeEnum) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="AuditTimeStr" :label="$t('trials:trialDocument:entryRecord:table:auditorTime')"
        show-overflow-tooltip sortable="custom" />
      <el-table-column prop="OptUserName" :label="$t('trials:trialDocument:entryRecord:table:Opter')"
        show-overflow-tooltip sortable="custom" />
      <el-table-column prop="UserTypeEnum" :label="$t('trials:trialDocument:entryRecord:table:OptRole')"
        show-overflow-tooltip sortable="custom">
        <template slot-scope="scope">
          <span>{{ $fd('UserType', scope.row.UserTypeEnum) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="OptTimeStr" :label="$t('trials:trialDocument:entryRecord:table:submmitTime')"
        show-overflow-tooltip sortable="custom" />
      <el-table-column :label="$t('common:action:action')" width="100">
        <template slot-scope="scope">
          <el-button icon="el-icon-view" :title="$t('common:button:view')" circle @click.stop="preview(scope.row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
      @pagination="getList" />
    <el-dialog :visible.sync="preview_visible" fullscreen>
      <div style="height: 100%; overflow: auto">
        <preview :isEN="isEN" :isAll="isAll" :reviewerId.sync="reviewerId" v-if="preview_visible" />
      </div>
    </el-dialog>
    <!-- <upload-files
      :config="config"
      :faccept="faccept"
      :uploadPath="uploadPath"
      :limitLength="limitLength"
      v-if="config.visible"
      @close="close"
      @uplaodFile="uplaodFile"
    /> -->
    <base-model :config="upload_config">
      <div slot="dialog-body">
        <div class="file_title">
          {{ $t('trials:trialDocument:entryRecord:title:uploadFile') }}
        </div>
        <div class="file" v-if="file.FileName">
          <div class="name">{{ file.FileName }}</div>
          <i v-if="hasDownLoad && (isManage || isInspect)" class="el-icon-download"
            :title="$t('common:button:download')" @click.stop="downLoad(file)" />
          <i v-if="hasDel && isManage && !viewStatus" class="el-icon-delete" :title="$t('common:button:delete')"
            @click.stop="handleRemoveFile" />
        </div>
        <div class="btnBox">
          <!-- <el-button
            type="primary"
            v-if="hasEdit && isManage && !viewStatus"
            @click.stop="openFile(false)"
          >
            {{ $t('trials:trialDocument:entryRecord:button:uploadFile') }}
          </el-button> -->
          <el-upload v-if="hasEdit && isManage && !viewStatus" class="upload-demo" action
            :before-upload="(param) => beforeUpload(param, '.zip')" :show-file-list="false"
            :http-request="handleUploadFile" :limit="1" accept=".zip">
            <el-button size="small" type="primary" :disabled="!!file.FileName">
              {{ $t('trials:trialDocument:entryRecord:button:uploadFile') }}
            </el-button>
          </el-upload>
        </div>
      </div>
    </base-model>
  </box-content>
</template>
<script>
import { getConfirmationReviewerList } from '@/api/trials'
import {
  uploadTrialFileTypeFile,
  getTrialFileTypeFile,
  deleteTrialTypeFile,
} from '@/api/dictionary'
import Pagination from '@/components/Pagination'
import BoxContent from '@/components/BoxContent'
import preview from '@/views/reviewers/curriculumVitae/preview.vue'
import baseModel from '@/components/BaseModel'
import { mapGetters } from 'vuex'
// import uploadFiles from '../../uploadFiles.vue'
import { downLoadFile } from '@/utils/stream.js'
const searchDataDefault = () => {
  return {
    Code: null,
    UserTypeEnum: null,
    OptUserName: null,
    OptStartTime: null,
    OptEndTime: null,
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: 'BlindName',
  }
}
export default {
  name: 'entryRecord',
  components: {
    BoxContent,
    Pagination,
    preview,
    //  uploadFiles,
    baseModel,
  },
  props: {
    ArchiveTypeEnum: {
      type: Number,
      default: 0,
    },
    rowData: {
      type: Object,
      default: () => {
        return {}
      },
    },
    viewStatus: {
      type: Boolean,
      default: false,
    },
    Id: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      reviewerId: null,
      isAll: false,
      preview_visible: false,
      timeList: [],
      config: {
        visible: false,
        showClose: true,
        width: '800px',
        title: '',
        appendToBody: false,
        isFolder: false,
      },
      upload_config: {
        visible: false,
        showClose: true,
        width: '800px',
        title: '',
        appendToBody: false,
        isFolder: false,
      },
      faccept: ['.zip'],
      limitLength: 1,
      uploadPath: null,
      file: {},
    }
  },
  methods: {
    handleRemoveFile() {
      this.$confirm(
        this.$t('trials:trialDocument:entryRecord:message:deleteMes'),
        {
          type: 'warning',
          distinguishCancelAndClose: true,
        }
      )
        .then(() => {
          deleteTrialTypeFile({
            TrialFileTypeId: this.file.TrialFileTypeId,
          }).then((res) => {
            if (res.IsSuccess) {
              this.getFile()
              this.$message({
                message: this.$t('common:message:deletedSuccessfully'),
                type: 'success',
              })
            }
          })
        })
        .catch((action) => { })
    },
    async handleUploadFile(param) {
      try {
        console.log(param)
        let trialId = this.$route.query.trialId
        let extendName = param.file.name
          .substring(param.file.name.lastIndexOf('.'))
          .toLocaleLowerCase()
        if (!trialId)
          return this.$alert(
            this.$t('trials:trialDocument:entryRecord:msg:noTrialId')
          ).catch()
        this.loading = true
        var file = await this.fileToBlob(param.file)
        let typeArr = ['', 'Report', 'Doc', 'Record', 'Reviewer', 'Template']
        let types = typeArr[this.ArchiveTypeEnum]
        // let fileNameNoType = param.file.name
        //   .substring(0, param.file.name.lastIndexOf('.'))
        //   .toLocaleLowerCase()
        const res = await this.OSSclient.put(
          `/${trialId}/Document/${types}/${this.$guid()}${extendName}`,
          file
        )
        this.file = {
          FileName: param.file.name,
          FilePath: this.$getObjectName(res.url),
          FileSize: param.file.size,
          FileFormat: extendName,
        }
        this.loading = false
        this.uplaodFile([this.file])
      } catch (err) {
        console.log(err)
      }
    },
    beforeUpload(param, accept) {
      if (this.file && !!this.file.FileName) {
        this.$alert(
          this.$t('trials:trialDocument:entryRecord:msg:hasFile')
        ).catch()
        return
      }
      let extendName = param.name
        .substring(param.name.lastIndexOf('.'))
        .toLocaleLowerCase()
      if (accept !== extendName) {
        this.$alert(
          this.$t('trials:trialDocument:entryRecord:msg:typeErr')
        ).catch()
        return
      }
    },
    openUpload() {
      this.upload_config.title = `${this.$t(
        'trials:trialDocument:entryRecord:title:uploadFile'
      )}
        -
    ${this.isEN ? this.rowData.Name : this.rowData.NameCN}`
      this.upload_config.visible = true
    },
    // 下载
    async downLoad(row) {
      try {
        return await downLoadFile(
          this.OSSclientConfig.basePath + row.FilePath,
          row.FileName
        )
      } catch (err) {
        console.log(err)
      }
    },
    // 获取上传文件
    async getFile() {
      try {
        if (!this.Id) return false
        let data = {
          TrialFileTypeId: this.Id,
        }
        let res = await getTrialFileTypeFile(data)
        if (res.IsSuccess) {
          this.file = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    async uplaodFile(list) {
      console.log(list, 'list')
      try {
        let data = {
          TrialFileTypeId: this.Id,
          FileRecord: list[0],
        }
        let res = await uploadTrialFileTypeFile(data)
        if (res.IsSuccess) {
          this.getFile()
        }
      } catch (err) {
        console.log(err)
      }
    },
    openFile(isFolder = false) {
      this.config.title = this.$t(
        'trials:trialDocument:entryRecord:form:title:uploadFile'
      )
      this.config.visible = true
      this.config.isFolder = isFolder
    },
    async getList() {
      try {
        this.searchData.TrialId = this.$route.query.trialId
        this.loading = true
        let res = await getConfirmationReviewerList(this.searchData)
        this.loading = false
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.timeList = []
      this.getList()
    },
    // 排序
    handleSortByColumn(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 预览
    preview(row) {
      this.reviewerId = row.Id
      this.isAll = false
      this.preview_visible = true
    },
    changeTimeList() {
      if (this.timeList) {
        this.searchData.OptStartTime = this.timeList[0]
        this.searchData.OptEndTime = this.timeList[1]
      } else {
        this.searchData.OptStartTime = null
        this.searchData.OptEndTime = null
      }
    },
    close() {
      this.config.visible = false
    },
  },
  created() {
    let typeArr = ['', 'Report', 'Doc', 'Record', 'Reviewer', 'Template']
    let types = typeArr[this.ArchiveTypeEnum]
    this.uploadPath = `/${this.$route.query.trialId}/Document/${types}`
  },
  watch: {
    Id: {
      handler() {
        this.rowBtnStatus = 'edit'
        this.getList()
        this.getFile()
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(['hospitalList']),
    isEN() {
      return this.$i18n.locale !== 'zh'
    },
    isInspect() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:inspect',
      ])
    },
    isManage() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:manage',
      ])
    },
    hasAdd() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:add',
      ])
    },
    hasEdit() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:edit',
      ])
    },
    hasDel() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:del',
      ])
    },
    hasDownLoad() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:downLoad',
      ])
    },
    hasAccredit() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:accredit',
      ])
    },
    TITLE() {
      return `${this.$fd('ArchiveType', this.ArchiveTypeEnum)} — ${this.isEN ? this.rowData.Name : this.rowData.NameCN
        }`
    },
  },
}
</script>
<style lang="scss" scoped>
.title {
  line-height: 40px;
  font-weight: bold;
  margin-bottom: 10px;
}

.fileName {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  /* 文本不换行 */
  overflow: hidden;
  /* 超出部分隐藏 */
  text-overflow: ellipsis;
}

.fileBtnBox {
  display: inline-block;
  width: 50px;

  i {
    cursor: pointer;
    color: #409eff;
    margin-right: 3px;

    &:last-child {
      margin: 0;
    }
  }
}

.topForm {
  .el-form-item {
    margin-right: 30px;
  }
}

.file_title {
  line-height: 40px;
  font-weight: bold;
}

.file {
  width: 100%;
  display: flex;
  margin-bottom: 10px;

  .name {
    max-width: 90%;
    white-space: nowrap;
    /* 文本不会换行，会在同一行内继续，直到遇到<br>标签为止 */
    text-overflow: ellipsis;
    /* 当文本溢出包含它的容器时，显示省略号(...)来表示被截断的文本 */
    overflow: hidden;
    /* 隐藏溢出容器的文本 */
  }

  i {
    cursor: pointer;
    margin: 3px;
    color: #409eff;
  }

  .disable {
    cursor: not-allowed;
    color: #909399;
  }
}

.btnBox {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>