import { fileUpload, getSignature } from '@/api/system'
import { Message, Loading } from 'element-ui'
import md5 from 'blueimp-md5'
/**
 * 以分隔符截取字符串，并返回最后一个截取段
 */
const splitStrLast = function(str, split) {
  const fileNameArr = str.split(split)
  const last = fileNameArr[fileNameArr.length - 1]
  return last
}
const fetchUpload = function(file, callback) {
  const loading = Loading.service({
    lock: true,
    text: '视频上传中',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
    customClass: 'tinymce-el-loading'
  })
  const fileName = file.name
  const key = 'upload/cms-admin/' + md5(fileName + new Date().getTime()) + fileName.substr(fileName.lastIndexOf('.'))
  getSignature()
    .then(response => {
      const { accessid, policy, signature, host } = response
      const data = { key, OSSAccessKeyId: accessid, policy, signature, success_action_status: '200' }
      const fileUrl = `${host}/${key}`
      const formData = new window.FormData()
      formData.append('key', data.key)
      formData.append('OSSAccessKeyId', data.OSSAccessKeyId)
      formData.append('policy', data.policy)
      formData.append('signature', data.signature)
      formData.append('success_action_status', '200')
      formData.append('file', file)
      fileUpload(formData).then(res => {
        loading.close()
        callback(fileUrl, { title: file.name })
      }).catch(err => {
        loading.close()
        Message({ message: err.message || '上传上传出错了', type: 'error', customClass: 'tinymce-el-message' })
      })
    })
    .catch(err => {
      console(err)
      loading.close()
    })
}
/**
 * 视频上传
 * @param {function} callback 上传结束回调
 * @param {string} value
 * @param {*} meta
 */
export function mediaUpload(callback, value, meta) {
  if (meta.filetype === 'media') {
    const input = document.createElement('input') // 创建一个隐藏的input
    input.setAttribute('type', 'file')
    input.setAttribute('accept', '.mp4')
    input.onchange = function() {
      const file = this.files[0]
      let errorMsg = ''
      if (file && file.name) {
        const suffix = splitStrLast(file.name, '.')
        if (['mp4'].includes(suffix)) {
          if (file.size > 1024 * 1024 * 1024) {
            errorMsg = '视频文件大小不能超过 1GB！'
          }
        } else {
          errorMsg = '只支持mp4格式的视频文件'
        }
      } else {
        errorMsg = '请选取视频文件'
      }
      if (errorMsg) {
        Message({ message: errorMsg, type: 'error', customClass: 'tinymce-el-message' })
      } else {
        fetchUpload(file, callback)
      }
    }
    // 触发点击
    input.click()
  }
}
/**
 * 添加视频回调
 * @param {function} data 视频数据
 * @param {string} resolve 回调函数
 */
export function mediaResolver(data, resolve) {
  try {
    const videoUri = encodeURI(data.url)
    const embedHtml = `
      <p>
         <span
          data-mce-selected="1"
          data-mce-object="video"
          data-mce-p-width="100%"
          data-mce-p-height="100%"
          data-mce-p-controls="controls"
          data-mce-p-controlslist="nodownload"
          data-mce-p-allowfullscreen="true"
          data-mce-p-src=${videoUri} >
          <video src=${videoUri} width="100%" height="100%" controls="controls" controlslist="nodownload">
          </video>
        </span>
      </p>
      <p style="text-align: left;"></p>
      `
    resolve({ html: embedHtml })
  } catch (e) {
    resolve({ html: '' })
  }
}
