import Vue from 'vue'
import axios from 'axios'
import md5 from 'js-md5'
// import {eventBus} from './eventBus'
// import VueCoreVideoPlayer from 'vue-core-video-players'
import 'viewerjs/dist/viewer.css'
import VueViewer from 'v-viewer'
// import VueCoreVideoPlayer from 'vue-core-video-player'
Vue.prototype.$EventBus = new Vue()
// Vue.use(VueCoreVideoPlayer)
Vue.use(VueViewer)
//域名管理对象
Vue.prototype.domainManager = function () {
  let domainUrl = '';
  domainUrl = "http://192.168.2.214:8082";
  domainUrl = "http://127.0.0.1";
  let domainNameUrl = this.GetDomain();
  domainNameUrl="http://tmb2b.oytour.com/"
  if (domainNameUrl.indexOf('testerp.oytour') !== -1) {
    domainUrl = "http://testapi.oytour.com";
  } else if (domainNameUrl.indexOf('oytour') !== -1) {
    domainUrl = "http://reborn.oytour.com";
    domainUrl = 'http://192.168.10.11:8083'
  }
  var obj = {
    //主地址
    DomainUrl: domainUrl,
    //常用提交数据URL
    PostUrl: domainUrl + "/api/common/post",
    javaUrl: 'http://efficient.oytour.com'

  };
  return obj;
}
//获取当前域名
Vue.prototype.GetDomain=function()
{
    var domainNameUrl =window.location.hostname;
    domainNameUrl="t.oytour.com";
    return domainNameUrl;
}
Vue.prototype.groupBy = function (array, f){
  const groups = {};
  array.forEach((item) => {
      const group = JSON.stringify(f(item));
      groups[group] = groups[group] || [];
      groups[group].push(item);
  });
  return Object.keys(groups).map((group) => {
      return {
        key:group.replace(/\"/g,""),
        data:groups[group]
      };
  });
}
Vue.prototype.moneyFormat = function(num, decimal = 2, split = ',') {
  function thousandFormat (num){
    const len = num.length
    return len <= 3 ? num : thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3)
  }
  if (isFinite(num)) { // num是数字
    if (num === 0) { // 为0
      return num.toFixed(decimal)
    } else { // 非0
      var res = ''
      var dotIndex = String(num).indexOf('.')
      if (dotIndex === -1) { // 整数
        res = thousandFormat(String(num)) + (decimal>0?'.':'') + '0'.repeat(decimal)
      } else {
        decimal = decimal==0?2:decimal
        const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal)) // 四舍五入，然后固定保留2位小数
        const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1) // 截取小数位
        res = thousandFormat(numStr.slice(0, dotIndex)) + decimals
      }
      return res
    }
  } else {
    return '--'
  }
}
//HTTP提交数据
Vue.prototype.apipost = function (cmd, msg, successCall, faildCall) {
  if (msg == null || msg == "") {
    msg = {}
  }
  var timestamp = (new Date()).valueOf();
  var apiurl = this.domainManager().PostUrl;
  var token = "";
  var key = "";
  var tempLanguage = 0;
  var GroupId = 0;
  if (this.getLocalStorage() != null) {
    token = this.getLocalStorage().token;
    key = this.getLocalStorage().SecretKey;
  }
  if (localStorage.groupinfo && localStorage.groupinfo != 'undefined') {
    var groupJson = JSON.parse(localStorage.groupinfo);
    GroupId = groupJson.GroupId;
  }
  var encodeMsg = encodeURIComponent(JSON.stringify(msg)).toLowerCase();
  var md5Str = md5(`cmd=${cmd}&msg=${encodeMsg}&timestamp=${timestamp}&token=${token}&key=${key}`);

  var postData = {
    msg: msg,
    cmd: cmd,
    timestamp: timestamp,
    token: token,
    sign: md5Str,
    languageId: tempLanguage,
    GroupId: GroupId
  }
  this.$axios.post(apiurl, postData, {
      headers: {
        'Content-Type': 'application/json',
        'Referer-Viitto': this.$route.path
      }
    })
    .then(res => {
      successCall(res);
    }, faildCall)
}

Vue.prototype.apiJavaPost = function (cmd, msg, successCall, faildCall) {
    if (msg == null || msg == "") {
      msg = {}
    }
    var apiurl = this.domainManager().javaUrl + cmd;
    var timestamp = (new Date()).valueOf();
    this.apiurl = apiurl;
    var token = "";
    var key = "";
    var GroupId = 0;
    if (this.getLocalStorage() != null) {
      token = this.getLocalStorage().token;
      key = this.getLocalStorage().secretKey;
    }
    if (localStorage.groupinfo && localStorage.groupinfo != 'undefined') {
      var groupJson = JSON.parse(localStorage.groupinfo);
      GroupId = groupJson.GroupId;
    }
    var encodeMsg = encodeURIComponent(JSON.stringify(msg)).toLowerCase();
    var md5Str = md5(`msg=${encodeMsg}&timestamp=${timestamp}&token=${token}&key=${key}`);

    var postData = {
      "msg": msg,
      "timestamp": timestamp,
      "token": token,
      "sign": md5Str,
      "GroupId": GroupId
    }
    this.$axios.post(apiurl, postData, {
        headers: {
          'Content-Type': 'application/json',
          'Referer-Viitto': this.$route.path
        }
      })
      .then(res => {
         successCall(res)
      }, faildCall)
  },


  //获取缓存
  Vue.prototype.getLocalStorage = function () {
    try {
      var localStorageData = window.localStorage["b2bUser"];
      if (localStorageData !== undefined && localStorageData != 'undefined') {
        return JSON.parse(localStorageData);
      } else {
        return null;
      }
    } catch (error) {
      return null;
    }

  }

//向外跳转
Vue.prototype.OpenNewUrl = function (URL) {
  if (URL && URL != '') {
    if (URL.indexOf("https") != -1) {
      var str = 'http://' + URL.substring(8);
      window.open(str, '_blank');
    } else if (URL.indexOf("http") != -1) {
      var str = 'http://' + URL.substring(7);
      window.open(str, '_blank');
    } else {
      window.open("http://" + URL, '_blank');
    }
  }
}

//公用跳转
Vue.prototype.CommonJump = function (path, obj) {
  this.$router.push({
    path: path,
    query: obj
  });
}

Vue.prototype.createCalendar = function (dateStr) {
  var days = [];
  var date;
  if (dateStr) {
    date = new Date(dateStr);
  } else {
    var now = new Date();
    date = new Date(this.formatDate(now.getFullYear(), now.getMonth() + 1, 1));
  }
  var currentDay = date.getDate();
  var currentYear = date.getFullYear();
  var currentMonth = date.getMonth() + 1;
  var currentWeek = date.getDay(); // 1...6,0

  var str = this.formatDate(
    currentYear,
    currentMonth,
    currentDay
  );

  days.length = 0;
  // 当月第一天是周日，放在第一行第1个位置，前面0个
  //初始化第一周
  for (var i = currentWeek; i >= 0; i--) {
    var d = new Date(str);
    d.setDate(d.getDate() - i);
    var dayobject = {};
    dayobject.day = d;
    days.push(dayobject); //将日期放入data 中的days数组 供页面渲染使用
  }

  //其他周
  var temp = 35;
  if (
    currentWeek +
    new Date(currentYear, currentMonth, 0).getDate() > 35
  ) {
    temp = 41;
  }
  for (var i = 1; i < temp - currentWeek; i++) {
    var d = new Date(str);
    d.setDate(d.getDate() + i);
    var dayobject = {};
    dayobject.day = d;
    days.push(dayobject);
  }
  return {
    DayArray: days,
    CurrentDay: currentDay,
    CurrentMonth: currentMonth,
    CurrentYear: currentYear,
    CurrentWeek: currentWeek
  };
}
//格式化日期
Vue.prototype.formatDate = function (year, month, day) {
  var y = year;
  var m = month;
  if (m < 10) m = "0" + m;
  var d = day;
  if (d < 10) d = "0" + d;
  return y + "-" + m + "-" + d;
}

//格式化日期二
Vue.prototype.formatDate2 = function (dateStr) {
  var date = new Date(dateStr);
  return {
    CYear: date.getFullYear(),
    CMonth: (date.getMonth() + 1),
    CDay: date.getDate(),
  }
}

//添加月份
Vue.prototype.AddMonth = function (dateStr, month) {
  var v = new Date(dateStr);
  if (v) {
    var t = new Date(v.getFullYear(), v.getMonth(), v.getDate(), v.getHours(), v.getMinutes(), v.getSeconds(), v.getMilliseconds());
    t.setMonth(v.getMonth() + month);
    if (t.getDate() != v.getDate()) {
      t.setDate(0);
    }
    return t;
  }
}

//获取URL中参数
Vue.prototype.getUrlKey = function (name, url) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
}
Vue.prototype.GetHtml = function (str) {
  if (str && str != "") {
    return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>')
      .replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&apos;/g, "'");
  }
  return str;
}
