<template>
  <base-model :config="config">
    <div slot="dialog-body">
      <!-- 多文件上传 -->
      <form id="inputForm" ref="uploadForm">
        <el-divider content-position="left">{{
          $t('trials:trialDocument:label:fileType').replace(
            'xxx',
            faccept.join('/')
          )
        }}</el-divider>
        <div class="form-group">
          <div
            class="upload"
            style="margin-right: 10px"
            :disabled="limitLength"
            v-if="!limitLength"
          >
            <input
              multiple="multiple"
              webkitdirectory=""
              directory
              accept="*/*"
              type="file"
              name="uploadFolder"
              class="select-file"
              title=""
              @change="beginScanFiles($event)"
              v-if="
                !loading &&
                (!limitLength ||
                  (fileList.length < limitLength && limitLength > 1))
              "
            />
            <div class="btn-select">
              {{ $t('trials:trialDocument: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="!loading && (!limitLength || fileList.length < limitLength)"
            />
            <div class="btn-select">
              {{ $t('trials:trialDocument: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 && !loading"
        />
        <el-table-column type="index" width="50" />
        <!-- 文件名称 -->
        <el-table-column
          prop="name"
          :label="$t('trials:trialDocument:table:fileName')"
          min-width="100"
        />
        <!-- 文件大小 -->
        <el-table-column
          prop="size"
          :label="$t('trials:trialDocument:table:fileSize')"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.size && scope.row.size > 0
                ? `${(scope.row.size / 1024 / 1024).toFixed(2)}MB`
                : ''
            }}</span>
          </template>
        </el-table-column>
        <!-- 文件类型 -->
        <el-table-column
          prop="type"
          :label="$t('trials:trialDocument:table:fileType')"
        />
        <!-- 上传状态 -->
        <el-table-column
          prop="status"
          :label="$t('trials:trialDocument: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:trialDocument:table:failedFileCount')"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-progress
              color="#409eff"
              :percentage="
                ((scope.row.uploadFileSize * 100) / scope.row.size).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="loading"
              :title="$t('trials:trialDocument:action:delete')"
              @click="handleRemoveFile(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="dialog-footer">
      <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="loading"
          @click="beginUpload"
        >
          {{ $t('trials:trialDocument:action:upload') }}
        </el-button>
      </div>
    </div>
  </base-model>
</template>
<script>
import baseModel from '@/components/BaseModel'
import { deepClone } from '@/utils/index.js'
import store from '@/store'
export default {
  name: 'uploadFiles',
  props: {
    config: {
      required: true,
      default: () => {
        return {
          visible: false,
        }
      },
    },
    faccept: {
      type: Array,
      default: () => {
        return []
      },
    },
    uploadPath: {
      type: String,
      default: '',
    },
    limitLength: {
      type: Number,
      default: 0,
    },
  },
  components: {
    'base-model': baseModel,
  },
  data() {
    return {
      loading: false,
      fileList: [],
      selectArr: [],
      isFail: false,
      successFileList: [],
      fileInput: null,
    }
  },
  methods: {
    // 获取待上传文件信息
    handleSelectionChange(selection) {
      this.selectArr = selection
    },
    // 扫描待上传文件
    beginScanFiles(e) {
      if (this.fileInput) {
        this.fileInput = null
      }
      var files = [...e.target.files]
      if (this.limitLength && this.fileList.length >= this.limitLength)
        return this.$message.warning(
          this.$t('trials:trialDocument:message:limitLength')
        )
      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:trialDocument: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:trialDocument: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()
      })
    },
    handleRemoveFile(row) {
      this.$confirm(this.$t('trials:trialDocument: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(() => {})
    },
    // 开始上传文件
    async beginUpload() {
      this.loading = 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:trialDocument:message:uploadSize'))
        this.loading = false
      } else {
        this.selectArr.forEach((item) => (item.status = 0))
        let num = this.selectArr.length > 6 ? 6 : this.selectArr.length
        let funArr = []
        for (let i = 0; i < num; i++) {
          funArr.push(this.handleUploadTask(this.selectArr, i))
        }
        if (funArr.length > 0) {
          let res = await Promise.all(funArr)
        }
      }
    },
    // 并发上传
    async handleUploadTask(arr, index) {
      if (!this.config.visible) return
      let file = this.fileList.filter((item) => item.id === arr[index].id)[0]
      file.status = 1
      let fileType = file.name
        .substring(file.name.lastIndexOf('.'))
        .toLocaleLowerCase()
      // let fileName = file.name
      //   .substring(0, file.name.lastIndexOf('.'))
      //   .toLocaleLowerCase()
      let path = `${this.uploadPath}/${this.$guid()}${fileType}`
      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),
          FileSize: file.size,
          FileFormat: fileType,
        })
        let flag = arr.every((item) => item.status === 2)
        if (flag) {
          return this.submitFile(this.successFileList)
        }
      } 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) {
          this.$refs.filesTable.clearSelection()
          failFileList.forEach((row) => {
            row.uploadFileSize = 0
            this.$refs.filesTable.toggleRowSelection(row)
          })
          this.isFail = true
          this.submitFile(this.successFileList, 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
            }
          }
        )
        if (res) {
          return res
        } else {
          return false
        }
      } catch (err) {
        console.log(err)
        return false
      }
    },
    submitFile(list, isReLoad = false) {
      if (!this.config.visible) return
      if (!isReLoad) {
        this.reset()
      }
      let arr = deepClone(list)
      this.$emit('uplaodFile', arr)
    },
    reset() {
      this.loading = false
      this.selectArr = []
      this.successFileList = []
      this.OSSclient.close()
      this.$emit('close')
    },
    openFile(isFolder = false) {
      this.fileInput = document.createElement('input')
      this.fileInput.type = 'file'
      this.fileInput.addEventListener('change', this.beginScanFiles)
      if (isFolder) {
        this.fileInput.accept = '*/*'
        //webkitdirectory directory
        this.fileInput.webkitdirectory = 'webkitdirectory'
        this.fileInput.directory = 'directory'
      } else {
        this.fileInput.accept = this.faccept.join(',')
      }
      console.log(this.fileInput)
      this.fileInput.click()
    },
  },
  watch: {
    isFail() {
      if (this.isFail) {
        this.$confirm(this.$t('trials:trialDocument:failUpload'), {
          type: 'warning',
          distinguishCancelAndClose: true,
          confirmButtonText: this.$t('common:button:confirm'),
          cancelButtonText: this.$t('common:button:cancel'),
        })
          .then(() => {
            this.beginUpload()
          })
          .catch((err) => {
            this.loading = false
            console.log(err)
          })
      }
    },
    loading() {
      store.dispatch('trials/setUnLock', this.loading)
    },
  },
  mounted() {
    this.openFile(this.config.isFolder)
  },
  beforeDestroy() {
    store.dispatch('trials/setUnLock', false)
    this.OSSclient.close()
  },
}
</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用来控制该标签的点击穿透事件
  }
}
</style>