<template>
  <div class="UploadFile-container">
    <template>
      <transition-group class="el-upload-list el-upload-list--picture-card" style="flex-wrap: wrap; display: flex" tag="ul" name="el-list">
        <li class="el-upload-list__item is-success" v-for="(file, index) in fileImages" :key="index">
          <el-image :src="getImgUrl(file.url)" class="el-upload-list__item-thumbnail" :preview-src-list="getImgList(fileImages)" :z-index="10000" :ref="'image' + index"> </el-image>
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(index)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(index)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </li>
      </transition-group>
    </template>
    <!--    <template v-if="mobileFileList.length">-->
    <!--      <transition-group class="el-upload-list el-upload-list&#45;&#45;picture-card" tag="ul" name="el-list">-->
    <!--        <li class="el-upload-list__item is-success" v-for="(file, index) in mobileFileList" :key="index">-->
    <!--          <el-image :src="getImgUrl(file.url)" class="el-upload-list__item-thumbnail" :preview-src-list="getImgList(fileList)" :z-index="10000" :ref="'image' + index"> </el-image>-->
    <!--          <span class="el-upload-list__item-actions">-->
    <!--            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(index)">-->
    <!--              <i class="el-icon-zoom-in"></i>-->
    <!--            </span>-->
    <!--            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleMobileRemove(index)">-->
    <!--              <i class="el-icon-delete"></i>-->
    <!--            </span>-->
    <!--          </span>-->
    <!--        </li>-->
    <!--      </transition-group>-->
    <!--    </template>-->
    <el-upload
      :action="define.comUploadUrl"
      :headers="uploadHeaders"
      :on-success="handleSuccess"
      :on-error="handleError"
      :multiple="limit !== 1"
      :show-file-list="false"
      accept="image/*"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :disabled="disabled"
      list-type="picture-card"
      :limit="limit"
      class="upload-btn"
    >
      <i class="el-icon-plus"></i>
      <span @click.stop="scanClick" v-if="scanCode">
        <el-popover v-model="isScan" placement="bottom" @hide="scanHidden" title="微信扫一扫上传" width="128" trigger="click" append-to-body>
          <amis-sdk
            :amis-json="{
              type: 'qr-code',
              codeSize: 128,
              value: url
            }"
          />
          <el-button slot="reference" type="text" style="position: absolute; right: 15px; top: -5px; font-size: 18px; width: 25px">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="rgba(24,144,255,1)">
              <path d="M15 3H21V8H19V5H15V3ZM9 3V5H5V8H3V3H9ZM15 21V19H19V16H21V21H15ZM9 21H3V16H5V19H9V21ZM3 11H21V13H3V11Z"></path></svg
          ></el-button>
        </el-popover>
      </span>

      <!--      <el-button @click.stop="scanClick" v-if="scanCode" type="text" class="fa" style="position: absolute; right: 15px; top: -5px; font-size: 18px; width: 25px">-->
      <!--       -->
      <!--      </el-button>-->

      <div slot="tip" class="el-upload__tip" v-show="showTip">只能上传不超过{{ fileSize }}{{ sizeUnit }}的{{ accept }}图片</div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import AmisSdk from '@/components/AmisSdk.vue'
import { comUrl } from '@/utils/define'
import { delBySerialNumber, getBySerialNumber, getFileById } from '@/api/common'

const units = {
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 1024 * 1024
}
export default {
  name: 'UploadImg',
  components: { AmisSdk },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'annexpic'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    showTip: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 0
    },
    accept: {
      type: String,
      default: 'image/*'
    },
    sizeUnit: {
      type: String,
      default: 'MB'
    },
    fileSize: {
      default: 2
    },
    scanCode: {
      default: false
    }
  },
  data() {
    return {
      url: '',
      uuid: '',
      fileList: [],
      uploadHeaders: { Authorization: 'bearer ' + getToken() },
      isScan: false,
      mobileFileList: [],
      fileImages: []
    }
  },
  mounted() {
    // 判断字符串类型
    this.uuid = g.guid(8)
    this.url = comUrl + '/work/uploadFile.html?uid=' + 'uid' + '&uuid=' + this.uuid + '&limit=' + this.limit
    this.fileList = this.value
      .filter((o) => !o.url && !o.type)
      .map((v) => {
        return {
          type: 'new',
          url: v
        }
      })
  },
  computed: {
    allFileList() {
      return [...this.fileList, ...this.mobileFileList]
    }
  },
  watch: {
    allFileList: {
      handler(val) {
        console.log(val)
        if (val.length > 0) {
          // getFileById(val.map((o) => o.url)).then((res) => {
          //   const list = Object.values(res.data.data).map((o) => {
          //     return {
          //       name: o.fileName,
          //       fileId: o.id,
          //       url: o.filePath
          //     }
          //   })
          //
          // })
          this.fileImages = val.map((o) => {
            return {
              name: o.url,
              fileId: o.url,
              url: 'api/file/getFileInputStreamById/' + o.url
            }
          })
        }
      }
    },
    value: {
      handler(val) {
        // console.log(val)
        // this.fileList = val
        //   .filter((o) => !o.url && !o.type)
        //   .map((v) => {
        //     return {
        //       url: v
        //     }
        //   })
        // try {
        //   const toObj = JSON.parse(val)
        //   if (Array.isArray(toObj) && toObj[0].url) {
        //     this.fileList = toObj
        //   }
        //   console.log(toObj)
        // } catch {
        //   if (Array.isArray(val) && val[0] && val[0].url) {
        //     this.fileList = val
        //   }
        // }
      }
    }
  },
  methods: {
    beforeUpload(file) {
      const unitNum = units[this.sizeUnit]
      if (!this.fileSize) return true
      let isRightSize = file.size / unitNum < this.fileSize
      if (!isRightSize) {
        this.$message.error(`文件大小超过${this.fileSize}${this.sizeUnit}`)
      }
      return isRightSize
    },
    handleError(res, file, fileList) {
      this.$message({ message: res, type: 'warning', duration: 5000 })
    },
    handleSuccess(res, file, fileList) {
      if (res.code == 200) {
        this.fileList.push({
          url: res.data.id,
          type: 'new'
        })
        this.$emit('input', this.fileList)
      } else {
        this.$message({ message: res.msg, type: 'error', duration: 5000 })
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多可以上传${this.limit}张图片`)
    },
    handlePictureCardPreview(index) {
      this.$refs['image' + index][0].clickHandler()
    },
    handleRemove(index) {
      const url = this.allFileList[index]
      this.fileList.splice(index, 1)
      this.fileImages.splice(index, 1)
      this.$emit('input', this.fileList)
      // delBySerialNumber(url.url, url.url).then((res) => {})
    },
    handleMobileRemove(index) {
      const url = this.mobileFileList[index].url
      this.mobileFileList.splice(index, 1)
      this.$emit('input', this.fileList)
      delBySerialNumber(this.uuid, url).then((res) => {})
    },
    getImgUrl(url) {
      let ImgUrl
      if (!g.isLeftLike(url, 'http://')) {
        if (process.env.NODE_ENV === 'development') {
          ImgUrl = this.define.comUrl + '/'
          return ImgUrl + url
        } else {
          ImgUrl = document.location.origin + '/'
          return ImgUrl + url
        }
      } else {
        return url
      }
    },
    getImgList(list) {
      return list.map((o) => {
        let ImgUrl
        if (!g.isLeftLike(o.url, 'http://')) {
          if (process.env.NODE_ENV === 'development') {
            ImgUrl = this.define.comUrl + '/'
            return ImgUrl + o.url
          } else {
            ImgUrl = document.location.origin + '/'
            return ImgUrl + o.url
          }
        } else {
          return o.url
        }
      })
    },
    scanHidden() {
      if (this.interval) {
        clearInterval(this.interval)
      }
    },
    // 扫一扫弹出二维码
    scanClick() {
      this.isScan = true
      // 定时运行getMobileFileList
      this.interval = setInterval(() => {
        this.getMobileFileList()
      }, 3000)
    },
    getMobileFileList() {
      getBySerialNumber(this.uuid).then((res) => {
        if (res.data.data.length) {
          this.mobileFileList = res.data.data.map((o) => {
            return {
              url: +o.id,
              type: 'new'
            }
          })
          if (this.fileList.length < 1) {
            this.fileList = this.mobileFileList
            this.$emit('input', this.fileList)
          } else {
            this.$emit('input', g.removeRepeatAttr([...this.fileList, ...this.mobileFileList], 'url'))
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}
:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.upload-btn {
  display: inline-block;
}
</style>
