import html2canvas from 'html2canvas'
import {
  getToken,
  getUserId
} from '@/utils/auth'
import Vue from 'vue'
import request from '@/utils/request';
(function() {
  let tools = {
    setImage(callback) {
      if (window.plus) {
        var ws = plus.webview.currentWebview()
        var bitmap = new plus.nativeObj.Bitmap('test');
        // 将webview内容绘制到Bitmap对象中
        ws.draw(bitmap, function() {
          callback(bitmap.toBase64Data());
        }, function(e) {
          console.log('截屏绘制图片失败：' + JSON.stringify(e));
        });
      } else {
        html2canvas(document.body, {
          useCORS: true
        }).then(function(canvas) {
          var extra_canvas = document.createElement("canvas");
          var w = canvas.width
          var h = canvas.height
          extra_canvas.setAttribute('width', 320);
          extra_canvas.setAttribute('height', (320 * h / w));
          var ctx = extra_canvas.getContext('2d');
          ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, 320, (320 * h / w));
          var dataURL = extra_canvas.toDataURL();
          callback(dataURL)
        });
      }
    },
    getBlob(canvas) { //获取blob对象
      var data = canvas.toDataURL("image/jpeg", 0.1);
      var dataurl = data
      return dataurl
    }
  }

  document.body.addEventListener('click', function(e) {
    tools.setImage(function(image) {
      var error_msg = ""
      var user_token = getToken()
      var user_id = getUserId()
      let _canvas = document.body;
      var timestamp = (new Date()).valueOf() / 1000;
      var w = parseInt(window.getComputedStyle(_canvas).width);
      var h = parseInt(window.getComputedStyle(_canvas).height);
      request('post','/api/error/push', {
        event_time: timestamp,
        sw: w,
        sh: h,
        error_msg: error_msg,
        image: image,
        user_token: user_token,
        user_id: user_id,
        click_left: e.clientX,
        click_top: e.clientY,
        url: window.location.href
      }).then((res) => {

      })
    })
  }, false)


  const errorHandler = (error, vm, info) => {
    tools.setImage(function(image) {
      var error_msg = ""
      error_msg += "vm: " + vm.$vnode.tag + "\n"
      error_msg += "URL: " + location.href + "\n"
      error_msg += "Error: " + error.name + ':' + error.message + "" + info

      var timestamp = (new Date()).valueOf() / 1000;
      var user_token = getToken()
      var user_id = getUserId()
      let _canvas = document.body;
      var w = parseInt(window.getComputedStyle(_canvas).width);
      var h = parseInt(window.getComputedStyle(_canvas).height);

      request('post','/api/error/push', {
        event_time: timestamp,
        sw: w,
        sh: h,
        error_msg: error_msg,
        image: image,
        user_token: user_token,
        user_id: user_id,
        url: window.location.href
      }).then((res) => {})
    })
  }
  Vue.config.warnHandler = errorHandler
  Vue.config.errorHandler = errorHandler;
})(window)
