<template>
  <div>
    <!-- 原文上传 -->
    <el-dialog class="fileUpload-dialog" :title="uploadTitle" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="uploadVisible">
      <div class="setting-dialog">
        <div class="upload-container">
          <i v-if="uploadType !== 1 && fileList.length === 0" class="iconfont icon-tianjiawenjian upload-icon" />
          <div v-for="item in fileList" :key="item.name" class="file-list">
            <i class="iconfont icon-xiaowenjian" />
            {{ item.name }}
            <i class="el-icon-close" @click="deleteFile(item)" />
          </div>
          <div v-if="uploadType !== 1" class="upload-input">
            <input ref="fileInput" :key="key" type="file" :multiple="isMultiple" :accept="uploadType === 2 ? '.zip' :''" @change="handleFileChange">
            <div class="upload-zip"><i class="iconfont icon-shangchuan2" />点击上传</div>
          </div>
          <BigUpload v-else-if="uploadType === 1" :selected-category="selectedCategory" :arc-id="arcId" />
          <div v-if="uploadType === 2" class="el-upload__tip">上传限制文件类型：zip</div>

        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="uploadVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 上传详情 -->
    <el-dialog class="collectUpload-dialog" :title="detailUploadTitle" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="uploadDetialVisible">
      <div class="setting-dialog">
        <div class="upload-detail">
          <el-table :data="uploadDetailData" style="width: 100%">
            <el-table-column prop="number" label="编号" width="120" />
            <el-table-column prop="operator" label="操作人" width="120" />
            <el-table-column prop="operationType" label="操作类型" width="120" />
            <el-table-column prop="file" label="文件" width="160" />
            <el-table-column prop="createDate" label="操作时间" width="200" />
            <el-table-column prop="conclusion" label="结论" width="200">
              <template slot-scope="scope">
                <div>成功 {{ scope.row.successNumber }} 条; 失败 {{ scope.row.failNumber }} 条</div>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :current-page="page.page"
            :total="page.total"
            :page-size="page.size"
            :pager-count="5"
            layout="total, prev, pager, next, sizes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentPage"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { FetchAddArchivesFile } from '@/api/collect/collect'
import { getCurrentTime } from '@/utils/index'
import { upload, archivesUpload } from '@/utils/upload'
import { mapGetters } from 'vuex'
export default {
  name: 'UploadOriginal',
  components: { },
  props: {
    selectedCategory: {
      type: Object,
      default: function() {
        return {}
      }
    },
    arcId: {
      type: String,
      default: function() {
        return ''
      }
    }
  },
  data() {
    return {
      uploadVisible: false,
      uploadTitle: '普通上传',
      detailUploadTitle: '上传详情',
      key: 0,
      file: null, // 附件 change
      fileNames: '', // 附件 - name
      formatType: '', // 附件 - type
      postfix: '', // 附件 - 文件后缀
      fileSize: '', // 附件 - 大小
      filePath: [], // 附件 - path
      px: '', // 附件 - 分辨率
      nowDate: '', // 当前时间
      fileList: [],
      uploadType: 0,
      // 上传详情
      uploadDetialVisible: false,
      uploadDetailData: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ]),
    isMultiple() {
      return this.uploadType === 0
    }
  },
  created() {

  },
  mounted() {
  },
  methods: {
    handleFileChange(e) {
      const files = e.target.files
      this.file = files[0]
      this.key++
      const maxMessage = '上传文件大小不能超过 10MB，可使用大文件上传!'
      const maxSize = 10 * 1024 * 1024
      if (this.file && this.file.size > maxSize) {
        this.$message.warning(maxMessage)
        this.fileList = []
        e.target.value = ''
        return false
      }
      if (this.fileList.length !== 0) {
        const existingFile = this.fileList.some(file => file.name === this.file.name)
        if (existingFile) {
          this.$message.warning('文件已存在')
          return false
        }
      }
      for (let i = 0; i < files.length; i++) {
        if (this.uploadType === 2) {
          this.fileList = []
          this.fileList.push(files[i])
        } else {
          this.fileList.push(files[i])
        }
      }
    },
    handleUploadConfirm() {
      if (this.fileList.length === 0) {
        this.$message.info('请先选择相关文件！')
        return false
      }
      if (this.uploadType === 2) {
        // 原文目录上传
        upload(this.baseApi + '/api/collect/catalogUpload',
          this.fileList[0]
        ).then(res => {
          if (res.data.code === 200) {
            this.$message.success('成功追加' + res.data.data + '附件')
            this.$emit('close-dialog')
            this.uploadVisible = false
          } else {
            this.$message.error('上传附件失败!')
          }
        })
      } else {
        this.uplaodToList(this.fileList)
      }
    },
    uplaodToList(files) {
      // 原文上传
      this.nowDate = getCurrentTime()
      const promiseArray = files.map(async(item, index) => {
        const json = {}
        if (item.type.substring(0, item.type.indexOf('/')) === 'image') {
          const fileBase64 = await this.getBase64(item)
          const imgRes = await this.getImgPx(fileBase64)
          item.px = imgRes.width + 'px*' + imgRes.height + 'px'
        } else {
          item.px = ''
        }
        json.file_name = item.name
        json.file_size = item.size
        json.file_type = item.name.substring(item.name.lastIndexOf('.') + 1, item.name.length)
        // json.file_path = this.filePath[index].path
        json.file_path = ''
        json.sequence = null
        json.archive_id = this.arcId
        json.file_dpi = item.px
        json.file_thumbnail = ''
        json.create_time = this.nowDate
        json.id = null
        return json
      })
      Promise.all(promiseArray)
        .then((arrayUpload) => {
          // 上传附件
          archivesUpload(this.baseApi + '/api/collect/uploadFiles',
            files,
            this.selectedCategory.id,
            this.arcId,
            JSON.stringify(arrayUpload)
          ).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.data)
              this.$emit('close-dialog')
              this.uploadVisible = false
            } else {
              this.$message.error('上传附件失败!')
            }
          })
        })
        .catch((error) => {
          console.error(error)
        })
    },
    // 附件旁边的X
    deleteFile(file) {
      const index = this.fileList.indexOf(file)
      this.fileList.splice(index, 1)
      if (this.fileList.length !== 0) {
        archivesUpload(this.baseApi + '/api/collect/uploadFiles', this.fileList, this.selectedCategory.id).then(res => {
          if (res.data.code === 200) {
            this.filePath = res.data.data
          }
        })
      } else {
        this.$message.info('已清空所有要上传的附件!')
      }
    },
    // 将上传的图片转为base64
    getBase64(file) {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      return new Promise((resolve) => {
        reader.onload = () => {
          resolve(reader.result)
        }
      })
    },
    // 获取图片的分辨率
    getImgPx(img) {
      const image = new Image()
      image.src = img
      return new Promise((resolve) => {
        image.onload = () => {
          const width = image.width
          const height = image.height
          resolve({ width, height })
        }
      })
    },
    handleSizeChange(size) {
      this.page.size = size
      this.page.page = 1
    },
    handleCurrentPage(val) {
      this.page.page = val
    }
  }
}
</script>

<style lang='scss' scoped>

.upload-container{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 496px;
  min-height: 178px;
  padding: 12px;
  border-radius: 3px;
  background: #EDEFF3;
  border: 1px dashed #BCC2C7;
  .upload-icon{
    font-size: 32px;
    color: #1F55EB;
  }
  .el-upload__tip{
    font-size: 12px;
    color: #A6ADB6;
  }
  .file-list{
    font-size: 12px;
    line-height: 24px;
    color: #545B65;
  }
}

.upload-input{
  position: relative;
  margin-top: 16px;
  width: 104px;
  height: 32px;
  & input{
    position: absolute;
    left: 0;
    top: 0;
    height: 32px;
    opacity: 0;
  }
}
.upload-zip{
  width: 104px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  color: #fff;
  text-align: center;
  border-radius: 3px;
  background: #1F55EB;
  & i{
    font-size: 13px;
  }
}

.collectUpload-dialog{
  ::v-deep .el-dialog{
    width: 970px;
  }
}

</style>
