/* global Zving UE $ baidu FormData Blob atob Image */
/**
 * @description 粘贴包含图片的Word数据
 * @author wangzhaohui
 */
UE.plugins['zuploadlocalimage'] = function () {
  var me = this
  // var clipData
  var confirmDialog
  var Dialog = baidu.editor.ui.Dialog
  // var Message = baidu.editor.ui.Message

  var localServerUrl = 'http://127.0.0.1:10707/'
  var contextPath = Zving.CONTEXTPATH.endsWith('/') ? Zving.CONTEXTPATH : Zving.CONTEXTPATH + '/'
  var uploadProgressDialog
  function uploadLocalImage (evt, data) {
    var htmlData = data ? data.html : me.getContent()
    if (!/<img[^>]+?src=['"]?file:[^>]+?['"]|<v:imagedata[^>]+?src=['"]?file:[^>]+?['"]/img.test(htmlData)) {
      return
    }
    var installPluginDialog = new Dialog({
      editor: me,
      name: 'installplugindialog',
      cssRules: 'width:400px;height:100px;padding: 2em;',
      content: '检测到您粘贴的内容含有本地图片，上传本地图片需要安装插件，请<a href="assets/ZvingCovertHelper.zip" style="text-decoration:underline;color:blue;">下载浏览器插件</a>并安装。',
      title: ''
    })

    $.ajax({
      url: localServerUrl,
      crossDomain: true, // 允许跨域
      xhrFields: {
        withCredentials: true // 允许携带证书
      }
    }).then(function (res) {
      if (!res || !res.status) {
        installPluginDialog.open()
        return
      }
      if (!confirmDialog || confirmDialog.hidden === true || confirmDialog.isDestroyed === true) {
        confirmDialog = new Dialog({
          editor: me,
          title: '',
          name: 'uploadlocalimageconfirm',
          cssRules: 'width:400px;height:100px;padding: 2em;',
          icon: 'icon_query',
          content: '检测到您粘贴的内容含有本地图片，是否上传本地图片？',
          buttons: [
            {
              className: 'edui-cancelbutton',
              label: '取消',
              editor: me,
              onclick: function () {
                confirmDialog.close()
              }
            },
            {
              className: 'edui-okbutton edui-button-upload-local-image',
              label: '自动上传图片',
              editor: me,
              onclick: function () {
                replaceImagesList = getLocalImagesInEditor(data)
                var filesLength = 0
                for (var k in replaceImagesList) {
                  filesLength++
                }
                confirmDialog.close()
                if (filesLength > 2) {
                  uploadProgressDialog = new Dialog({
                    editor: me,
                    name: 'uploadlocalimagetips',
                    cssRules: 'width:200px;height:100px;padding:2em;',
                    content: '图片上传中，请稍候...',
                    title: ''
                  })
                  uploadProgressDialog.open()
                }
                setTimeout(function () {
                  for (var k in replaceImagesList) {
                    uploadFileLocalServer(replaceImagesList[k].localPath, replaceImagesList[k].oldTag, k)
                  }
                }, 1)
              }
            }
          ]
        })
      }
      confirmDialog.open()
    }, function (res) {
      installPluginDialog.open()
    })
  }
  var replaceImagesList = {}
  function getLocalImagesInEditor (data) {
    var htmlData = data ? data.html : me.getContent()
    // console.log('getLocalImagesInEditor ',htmlData)
    var localImagesList = {}
    var reImgTag = /<img[^>]+?src=['"]?file:(.+?)['"]?[^>]+?>|<v:imagedata[^>]+?src=['"]?file:([^>]+?)['"]?[^>]+?>/img
    var rePath = /\ssrc=(['"]?)file:\/\/\/(.+?)(\1)(\s[\/\w]|\/?>)/i
    var reWidth = /\swidth=(['"]?)(.+?)(\1)(\s[\/\w]|\/?>)/i
    var reHeight = /\sheight=(['"]?)(.+?)(\1)(\s[\/\w]|\/?>)/i
    var res = htmlData.match(reImgTag)
    if (res) {
      for (var i = 0; i < res.length; i++) {
        var oldTag = res[i]
        var matchPath = rePath.exec(oldTag)
        var matchW = reWidth.exec(oldTag)
        var matchH = reHeight.exec(oldTag)
        if (matchPath && matchPath[2]) {
          var isrc = matchPath[2]
          var imgFilePath = isrc.replace(/\//g, '\\')
          var key = imgFilePath.replace(/\W/g, '_')
          if (localImagesList[key] === undefined) { // 用一个列表来存要被替换的Tag字符串
            localImagesList[key] = {}
            localImagesList[key].oldTag = oldTag
            localImagesList[key].localPath = imgFilePath
            localImagesList[key].localFileName = imgFilePath.substring(imgFilePath.lastIndexOf('\\') + 1)
            // 上传完图片宽高可能改变，由图片本身宽度来呈现
            if (matchW && matchW[2]) {
              localImagesList[key].width = matchW[2]
            }
            if (matchH && matchH[2]) {
              localImagesList[key].height = matchH[2]
            }
          }
        }
      }
    }
    return localImagesList
  }
  function replaceImgTags (replaceList, clipData) {
    var htmlData = clipData ? clipData.html : me.getContent()
    if (!htmlData || htmlData.indexOf('file://') === -1) {
      return
    }
    for (var k in replaceList) {
      var opt = replaceList[k]
      // console.log(opt.oldTag,opt.newTag);
      if (opt.uploaded === false) {
        continue
      }
      while (htmlData.indexOf(opt.oldTag) !== -1) {
        htmlData = htmlData.replace(opt.oldTag, '<p align="center">' + opt.newTag + '</p>')
      }
    }
    // console.log('replaceImgTags ',htmlData);
    if (clipData) {
      clipData.html = htmlData
    } else {
      me.setContent(htmlData)
    }
  }

  function uploadFileLocalServer (localFile, oldTag, id) {
    // 专题截图采取本地服务提供的接口
    var url = localServerUrl + 'localimage'
    var img = new Image()
    img.setAttribute('crossOrigin', 'anonymous')
    img.onload = function () {
      uploadImage(img, id)
    }
    img.onerror = function () {
      console.error('读取本地图片出错，可能本地服务没有正确安装')
    }
    img.src = url + '?filePath=' + encodeURIComponent(localFile)
  }

  function replaceImgLocalServer (id, data) {
    if (!data.resourceID) {
      console.error('上传图片 ' + replaceImagesList[id].localFileName + ' 到服务器失败', data)
      return
    }
    var imgTag = ''
    var options = replaceImagesList[id]
    var previewPrefix = data.previewPrefix
    if (data.sPath.indexOf('/preview/') !== -1) {
      previewPrefix = data.sPath.substring(0, data.sPath.indexOf('/preview/')) + data.previewPrefix.substring(data.previewPrefix.indexOf('/preview/'))
    }
    if (data.path) {
      imgTag = '<a href="' + previewPrefix + data.path + '" target="_blank">'
      imgTag += '<img src="' + previewPrefix + data.path + '" imagerela="' + data.resourceID + '"'

      imgTag += ' border="0"></a>'
    } else {
      imgTag = '<img src="' + previewPrefix + data.path + '" imagerela="' + data.resourceID + '"'
      imgTag += ' border="0">'
    }
    options.uploaded = true
    options.newTag = imgTag
    isAllImagesUploadedLocalServer()
  }
  function isAllImagesUploadedLocalServer () {
    for (var k in replaceImagesList) {
      var opt = replaceImagesList[k]
      if (opt.uploaded === undefined) {
        return
      }
    }
    uploadProgressDialog && uploadProgressDialog.close()
    replaceImgTags(replaceImagesList)
  }
  function dataURIToBlob (dataURI) {
    var array = []
    var binary = atob(dataURI.split(',')[1])
    var i = 0
    while (i < binary.length) {
      array.push(binary.charCodeAt(i++))
    }
    return new Blob([new Uint8Array(array)], {
      type: 'image/png'
    })
  }

  function uploadImage (srcImg, id) {
    var blob, buffer, ctx, formData, height, image, img, maxHeight, maxWidth, ratio, width
    img = srcImg
    maxWidth = 3840
    maxHeight = 2160
    ratio = 0
    width = img.width
    height = img.height
    if (width > maxWidth) {
      ratio = maxWidth / width
      height = height * ratio
      width = width * ratio
    }
    if (height > maxHeight) {
      ratio = maxHeight / height
      width = width * ratio
      height = height * ratio
    }
    buffer = document.createElement('canvas')
    buffer.setAttribute('width', width)
    buffer.setAttribute('height', height)
    ctx = buffer.getContext('2d')
    ctx.drawImage(img, 0, 0, width, height)
    image = buffer.toDataURL('image/png')
    blob = dataURIToBlob(image)
    formData = new FormData()
    formData.append('file', blob, 'inword_' + Date.now() + '.png')
    var uploadActionUrl = contextPath + 'ui/catalogresources/' + me.options.catalogID + '/upload?' + 'siteID=' + me.options.siteID

    $.ajax({
      url: uploadActionUrl,
      type: 'POST',
      data: formData,
      contentType: false,
      processData: false,
      crossDomain: true,
      xhrFields: {
        withCredentials: true
      },
      error: function (res) {
        console.error('上传图片到服务器失败！')
      },
      success: function (resp) {
        var res = resp.data || resp
        // console.log('图片上传完成 ', res)
        replaceImgLocalServer(id, res)
      }
    })
  }

  me.addListener('afterpaste', function (evt) {
    uploadLocalImage()
  })
}
