<template>
  <div>
    <a-upload
      name="avatar"
      list-type="picture-card"
      :file-list="fileList"
      :show-upload-list="{showPreviewIcon:false,showRemoveIcon:true}"
      class="avatar-uploader"
      action="#"
      :before-upload="beforeUpload"
      :remove="handleRemove"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < limit">
        <div class="ant-upload-text" />
      </div>
    </a-upload>

    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage">
    </a-modal>
  </div>
</template>

<script>
import OSS from 'ali-oss'
import { getOssAuth } from '@/api/upload.js'
import { message } from 'ant-design-vue'
import { defineComponent, reactive, onMounted, watch, toRefs } from 'vue'
export default defineComponent({
  name: 'UploadOss',
  props: {
    limit: {
      type: Number,
      default: 1
    },
    defaultList: {
      type: String,
      default: ''
    }
  },
  emits: ['uploadSuccess'],
  setup(props, { emit }) {
    const data = reactive({
      ...props,
      client: null,
      fileList: [],
      uploadFile: [],
      previewImage: '',
      previewVisible: false
    })
    onMounted(() => {
      if (props.defaultList) {
        const list = props.defaultList.split(',')
        const fileList = list.map((item) => {
          const objectName = item.split('/').slice(3).join('/')
          const obj = {
            name: objectName,
            uid: objectName,
            type: 'image/png',
            url: item,
            objectName: objectName
          }
          return obj
        })
        data.fileList = fileList
        emit('uploadSuccess', 'upload')
      } else {
        data.fileList = []
      }
      data.uploadFile = []
      data.previewImage = ''
      data.previewVisible = false
    })

    watch(() => props.defaultList, (newValue, oldValue) => {
      if (newValue.length) {
        const list = newValue.split(',')
        const fileList = list.map((item) => {
          const objectName = item.split('/').slice(3).join('/')
          const obj = {
            name: objectName,
            uid: objectName,
            type: 'image/png',
            url: item,
            objectName: objectName
          }
          return obj
        })
        data.fileList = fileList
        emit('uploadSuccess', 'upload')
      } else {
        data.fileList = []
      }
    })

    function beforeUpload(file) {
      if (!file.type.match('image.*')) {
        message.error('请选择正确的图片类型')
      } else {
        data.uploadFile.push(file)
        // const client = new OSS({
        //   region: 'oss-cn-shanghai',
        //   secure: true,
        //   accessKeyId: 'LTAI5tSJ62TLMUb4SZuf285A',
        //   accessKeySecret: 'MWYynm30filZ7x0HqSHlU3pdLVNeI7',
        //   bucket: 'ta-tech-image'
        // })
        // client.put(`imagedir/${file.name}`, file)
        //   .then((res) => {
        //     const imageUrl = client.signatureUrl(`imagedir/${file.name}`)
        //     const length = data.fileList.length
        //     data.fileList[length - 1].url = imageUrl
        //     emit('uploadSuccess', data.fileList)
        //   })
        //   .catch((err) => {
        //     const length = data.fileList.length
        //     data.fileList.splice(length - 1, 1)
        //     message.error('上传图片失败，请重新选择上传！')
        //     console.log(err)
        //   })
      }
      /* 中断a-upload的文件上传 */
      return false
    }

    function startUpload() {
      return new Promise((resolve, reject) => {
        const uploads = []
        const uloadList = data.uploadFile.filter((item) => {
          const index = data.fileList.findIndex(list => list.uid === item.uid)
          const result = index === -1 ? false : !data.fileList[index].url
          return result
        })
        if (!uloadList.length) {
          const objectList = data.fileList.map((item) => item.objectName || 'error')
          resolve(objectList)
        } else {
          getOssAuth()
            .then(res => {
              data.client = new OSS({
                region: 'oss-cn-shanghai',
                secure: true,
                accessKeyId: res.accessKeyId,
                accessKeySecret: res.accessKeySecret,
                stsToken: res.securityToken,
                bucket: 'ta-tech-image'
              })
              uloadList.forEach(item => {
                uploads.push(uploadOss(item))
              })
              Promise.all(uploads)
                .then((res) => {
                  const objectList = data.fileList.map((item) => item.objectName || 'error')
                  resolve(objectList)
                })
                .catch((error) => {
                  resolve(error)
                })
            })
        }
      })
    }

    function uploadOss(file) {
      return new Promise((resolve, reject) => {
        const randomString = Math.random().toString(36).slice(2)
        const suffix = /\.[^\.]+/.exec(file.name)
        const timestamp = new Date().getTime()
        const objectName = `imagedir/${randomString}_${timestamp}${suffix}`
        data.client.put(objectName, file)
          .then((res) => {
            const index = data.fileList.findIndex(list => list.uid === file.uid)
            data.fileList[index].url = res.url
            data.fileList[index].objectName = objectName
            resolve(objectName)
          })
          .catch((err) => {
            resolve('error')
            console.log(err)
          })
      })
    }

    /**
     * @description: 文件发生变化时
     * @param {Array} fileList
     * @return {*}
     */
    function handleChange({ fileList }) {
      data.fileList = fileList.filter((item) => {
        return item.type.match('image.*')
      })
      const status = data.fileList.length ? 'ready' : ''
      emit('uploadSuccess', status)
    }

    /**
     * @description: 文件删除时的回调
     * @param {Object} file
     * @return {*}
     */
    function handleRemove(file) {
      const index = data.fileList.findIndex((item) => {
        return item.uid === file.uid
      })
      data.uploadFile.splice(index, 1)
    }

    /**
     * @description: 关闭预览图
     * @param {Object} file
     * @return {*}
     */
    function handlePreview(file) {
      data.previewImage = file.url || file.thumbUrl
      data.previewVisible = true
    }

    /**
     * @description: 关闭图片预览框
     */
    function handleCancel() {
      data.previewVisible = false
    }

    return {
      ...toRefs(data),
      beforeUpload,
      handlePreview,
      handleChange,
      handleRemove,
      handleCancel,
      startUpload,
      uploadOss
    }
  }
})
</script>

<style lang="less" scoped>
.ant-upload-picture-card-wrapper{
  min-height: 122px;
  padding: 10px 0 0 10px;
}
.ant-upload-text {
  // width: 100px;
  // height: 100px;
  // cursor: pointer;
  // border: 1px solid #e1e1e1;
  // margin: 10px 0 0 10px;
  position: relative;
}
.ant-upload-text::before {
  content: '';
  position: absolute;
  left: 50%;
  top: 50%;
  width: 30px;
  transform:translate(-50%, -50%);
  border-top: 2px solid #e1e1e1;
}

.ant-upload-text::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 50%;
  height: 30px;
  transform: translate(-50%,-50%);
  border-left: 2px solid #e1e1e1;
}
</style>
