<template>
  <div id="mef-m-authentication-apply">
    <div class="apply-upload-item fr noMb">
      <div class="photo-upload item-03" :class="{uploaded: userWorkPhoto}" @click="photoUpload('userWorkPhoto')">
        <img :src="userWorkPhoto" onerror="this.src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII='" class="fit-cover-img" />
        <span v-if="userWorkPhoto" class="delete-icon" @click.stop="clearPhotoUrl('userWorkPhoto')"></span>
      </div>
    </div>
  </div>
</template>

<script>
/* function getQiniuToken() {
  return Promise.resolve({'uptoken': 'xxx'});
} */

// c39eAF6CRLXTPcOp7YZWN47QG-R8GMdJwBtBQ1Eb:vQEKW6kSJvaMFOD6G0Fj1toohjE=:eyJzY29wZSI6ImFpeXVleGluZzoiLCJkZWFkbGluZSI6MTY0NzU3NjY4N30=

/* c39eAF6CRLXTPcOp7YZWN47QG-R8GMdJwBtBQ1Eb:MZKUih1U9m0jKz57RwADJw02a9U=:eyJwZXJzaXN0ZW50UGlwZWxpbmUiOiJhaXl4bGliX3ZpZGVvLXBpcGUiLCJzY29wZSI6ImFpeXVleGluZyIsInBlcnNpc3RlbnRPcHMiOiJhdnRodW1iL20zdTgvbm9Eb21haW4vMS9zZWd0aW1lLzE1L3ZiLzQ0MGsvaGxzS2V5L2Z0em4xOWFpeXhsaWIyMDEvaGxzS2V5VXJsL2h0dHBzOi8vcWluaXUuYWl5eGxpYi5jb20vYWl4eWxpYndvcmQua2V5fHNhdmVhcy8iLCJkZWFkbGluZSI6MTY0NzU3NjcxOX0=*/
import { getQiniuToken } from '@/api/material/material'
export default {
  name: 'Upload',
  data() {
    return {
      userWorkPhoto: ''
    }
  },
  mounted() {

  },
  methods: {
    clearPhotoUrl(urlName) {
      this[urlName] = ''
    },
    photoUpload(type) {
      const ipt = document.createElement('input')
      ipt.setAttribute('type', 'file')
      ipt.setAttribute('accept', 'image/*')
      ipt.style.width = 0
      ipt.style.height = 0
      ipt.addEventListener('change', async() => {
        const [file] = ipt.files
        const base64Img = await this.fileToBase64(file)
        const url = await this.uploadBase64(base64Img)
        this.userWorkPhoto = url
        document.body.removeChild(ipt)
      })
      document.body.appendChild(ipt)
      ipt.click()
    },
    uploadBase64(base64Img) {
      return new Promise((resolve) => {
        getQiniuToken()
          .then(res => {
            const key = 'qiniu.aiyxlib.com' + this.uuid() + '.jpg'
            const pic = base64Img.split(',')[1]
            // const url = 'https://upload.qiniup.com/' + window.btoa(key) // 非华东空间需要根据注意事项 1 修改上传域名
            const url = 'https://upload.qiniup.com/' // 非华东空间需要根据注意事项 1 修改上传域名
            const xhr = new XMLHttpRequest()
            xhr.onreadystatechange = () => {
              if (xhr.readyState == 4) {
                resolve(
                  'qiniu.aiyxlib.com' + JSON.parse(xhr.responseText).key
                )
              }
            }
            xhr.open('POST', url, true)
            xhr.setRequestHeader('Content-Type', 'application/octet-stream')
            xhr.setRequestHeader('Authorization', 'UpToken ' + res.data)
            xhr.send(pic)
            // 获取到凭证之后再将文件上传到七牛云空间
          })
          .catch(console.error)
      })
    },
    fileToBase64(file) {
      return new Promise((resolve) => {
        const reader = new FileReader()
        // 传入一个参数对象即可得到基于该参数对象的文本内容
        reader.readAsDataURL(file)
        reader.onload = function(e) {
          // target.result 该属性表示目标对象的DataURL
          resolve(e.target.result)
        }
      })
    },
    uuid(len, radix) {
      const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
      const uuid = []
      let i
      radix = radix || chars.length
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
      } else {
        let r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = ''
        uuid[14] = '4'
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random() * 16
            uuid[i] = chars[i == 19 ? r & 0x3 | 0x8 : r]
          }
        }
      }
      return uuid.join('')
    }
  }
}
</script>
<style lang="scss" scoped>
  #mef-m-authentication-apply{
    .apply-upload-item{
      width: 132px;
      margin-bottom: 30px;
      text-align: center;
      &.noMb{
        margin-bottom: 0;
      }
      .photo-upload {
        width: 132px;
        height: 96px;
        position: relative;
        margin-bottom: 10px;
        &.item-03{
          // background: top / 100% url(~@/assets/images/authentication/upload_workCard.png)
          // no-repeat;
        }
        &.uploaded{
          background: none;
        }
        img{
          width: 85px;
          height: 85px;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%,-50%);
        }
        .delete-icon{
          width: 16px;
          height: 16px;
          // background: top / 100% url(~@/assets/images/common/icon-del.png)
          //   no-repeat;
          border-radius: 0;
          top: -8px;
          right: -8px;
          position: absolute;
          i {
            display: none;
          }
        }
      }
      .apply-name{
        font-size: 14px;
        font-weight: bold;
        padding-top: 10px;
        text-align: center;
      }
    }
  }
</style>
