import { fileUpload } from '@/api/system'
import { Message } from 'element-ui'
/**
 * 以分隔符截取字符串，并返回最后一个截取段
 */
const splitStrLast = function(str, split) {
  const fileNameArr = str.split(split)
  const last = fileNameArr[fileNameArr.length - 1]
  return last
}
/**
 * 视频上传
 * @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]
      if (file && file.name) {
        const suffix = splitStrLast(file.name, '.')
        if (['mp4'].includes(suffix)) {
          const formData = new window.FormData()
          formData.append('file', file)
          formData.append('type', 'file')
          fileUpload(formData).then(res => {
            if (res.code === 0 && res.data && res.data[0]) {
              const [first] = res.data
              callback(first.full_path, { title: first.title })
            } else {
              Message({ message: res.message || '上传上传出错了', type: 'error', customClass: 'tinymce-el-message' })
            }
          })
        } else {
          Message({ message: '只支持mp4格式的视频文件', type: 'error', customClass: 'tinymce-el-message' })
        }
      } else {
        Message({ message: '请选取视频文件', type: 'error', customClass: 'tinymce-$message' })
      }
    }
    // 触发点击
    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: '' })
  }
}
