import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './registerServiceWorker'
import './plugins/element.js'
import ElementUI from 'element-ui'
import plug from './plugins/index'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
import echarts from 'echarts'
import VueLazyload from 'vue-lazyload'
import htmlToPdf from './assets/utils/htmlToPdf'
import commonUtils from './assets/utils/commonUtils'
import languageUtils from './assets/utils/languageUtils' //引入语言转换帮助类
import moment from 'moment'
import co from 'co'
import MsgBus from './plugins/event-bus'
import {
  location
} from "./assets/utils/getLocation"
import 'xe-utils'
import vueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import pinyin from 'pinyin'
Vue.prototype.pinyin = pinyin
// 使用Vue.use()方法就会调用工具方法中的install方法
Vue.use(htmlToPdf)
Vue.use(VueLazyload)
Vue.use(vueQuillEditor)

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(plug)
Vue.http = Vue.prototype.$http = axios
Vue.commonUtils = Vue.prototype.$commonUtils = commonUtils
Vue.languageUtils = Vue.prototype.$languageUtils = languageUtils
Vue.prototype.MsgBus = MsgBus
Vue.prototype.$echarts = echarts
String.prototype.IsPicture = function () {
  //判断是否是图片 - strFilter必须是小写列举
  var strFilter = ".jpeg|.gif|.jpg|.png|.bmp|.pic|"
  if (this.indexOf(".") > -1) {
    var p = this.lastIndexOf(".");
    var strPostfix = this.substring(p, this.length) + '|';
    strPostfix = strPostfix.toLowerCase();
    if (strFilter.indexOf(strPostfix) > -1) {
      return true;
    }
  }
  return false;
}
router.beforeEach((to, from, next) => {
  let msg = {
    path: from.path,
    query: from.query
  }
  sessionStorage.setItem("FromPath", JSON.stringify(msg));
  if (to.meta.title) {
    if (localStorage.g && localStorage.g != 'undefined') {
      if (JSON.parse(localStorage.g).i != 2)
        document.title = to.meta.title.split('-')[0] + '-' + JSON.parse(localStorage.g).n
      else
        document.title = to.meta.title
    } else {
      document.title = to.meta.title
    }
  }
  next()
})

Vue.prototype.getLocalStorage = function () {
  var localStorageData = window.localStorage["userInfo"];
  if (localStorageData != undefined) {
    return JSON.parse(localStorageData);
  } else {
    return null;
  }
}

Vue.prototype.getNowDate = function () {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
    " " + date.getHours() + seperator2 + date.getMinutes() +
    seperator2 + date.getSeconds();
  return currentdate;
}
Vue.prototype.DateDiff = function (sDate1, sDate2) {
  var aDate, oDate1, oDate2, iDays
  aDate = sDate1.split("-")
  oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
  aDate = sDate2.split("-")
  oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数  
  return iDays
}

//价钱格式化，三位数逗号分隔，保留两位小数
Vue.prototype.moneyFormat = function (value) {
  if (!value) {
    return 0.00
  }
  let nStr = Number(value).toFixed(2)
  nStr += '';
  let x = nStr.split('.');
  let x1 = x[0];
  let x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
},

  // 注册
  Vue.filter('priceFormat', function (value) {
    if (value == null) {
      return 0.00;
    }
    let nStr = value.toFixed(2)
    nStr += '';
    let x = nStr.split('.');
    let x1 = x[0];
    let x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  })

// 不要小数点
Vue.filter('NoDesnum', function (value) {
  if (value == null) {
    return 0.00;
  } else if (value < 1) {
    return value;
  } else {
    let nStr = Number(value).toFixed(0)
    nStr += '';
    let x = nStr.split('.');
    let x1 = x[0];
    let x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  }

})
// 时间格式YYYY-MM-DD
Vue.filter("YMD", function (date) {
  return moment(date).format("YYYY-MM-DD");
})

Vue.filter("MD", function (date) {
  return moment(date).format("MM月DD日");
})

Vue.filter("YMDHMS", function (date) {
  return moment(date).format("YYYY-MM-DD HH:mm:ss");
})

Vue.prototype.random_string = function (len) {
  len = len || 32;
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  var maxPos = chars.length;
  var pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
},

  //上传文件到文件服务器
  Vue.prototype.UploadSelfFileT = function (path, files, successCall) {
    if (files && files.length > 0) {
      let nameList = new Array()
      for (let index = 0; index < files.length; index++) {
        nameList.push(this.random_string());
      }
      let that = this;
      co(function* () {
        for (let index = 0; index < files.length; index++) {
          let fileName = nameList[index]
          fileName = path + fileName + "." + files[index].name.split('.').pop()
          var formData = new FormData();
          var uploadUrl = that.domainManager().UploadUrl + "/Upload?filePath=" + path;
          formData.append("myfile", files[index]);
          that.$http.post(uploadUrl, formData, {})
            .then(res => {
              successCall(res);
            })
        }
      }).catch(function (err) {
        console.log("上传文件出错" + err);
      });
    }
  }



/**
 * 上传到当前Api站点
 * @param params 上传需要携带信息
 * @param fileObj 上传文件信息
 * @param successCall 回调函数
 */
Vue.prototype.UploadLocalSystem = function (params, fileObj, successCall) {
  let that = this;
  let url = that.domainManager().PostUrl + "/api/Upload/Index";
  let formData = new FormData()
  if (params) {
    formData.append("params", JSON.stringify(params));
  }
  formData.append('myfile', fileObj);
  co(function* () {
    that.$http.post(url, formData, {})
      .then(res => {
        successCall(res);
      })
  }).catch(function (err) {
    console.log("上传文件出错" + err);
  });
}

// 导入引流汇总
Vue.prototype.UploadFlowStat = function (params, fileObj, successCall) {
  let that = this;
  let url = that.domainManager().PostUrl + "/api/Upload/UploadFlowStat";
  let formData = new FormData()
  if (params) {
    formData.append("params", JSON.stringify(params));
  }
  formData.append('myfile', fileObj);
  co(function* () {
    that.$http.post(url, formData, {})
      .then(res => {
        successCall(res);
      })
  }).catch(function (err) {
    console.log("上传文件出错" + err);
  });
}

//新页面打开页面
Vue.prototype.OpenNewUrl = function (path, queryObj) {
  var newUrl = this.$router.resolve({
    path: path,
    query: queryObj
  });
  window.open(newUrl.href, '_blank');
}

//验证只能输入2位小数
Vue.prototype.checkPrice = function (item, filed) {
  var value = "";
  if (typeof item[filed] == "string") {
    value = item[filed];
  } else {
    value = item[filed].toString();
  }
  value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
  value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
  value = value
    .replace(".", "$#$")
    .replace(/\./g, "")
    .replace("$#$", ".");
  value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
  if (value.indexOf(".") < 0 && value != "") {
    //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
    value = parseFloat(value);
  }
  item[filed] = value;
}

//验证只能输入整数
Vue.prototype.checkInteger = function (item, filed) {
  var value = "";
  if (typeof item[filed] == "string") {
    value = item[filed];
  } else {
    value = item[filed].toString();
  }
  value = value.replace(this.$commonUtils.Regex.isInteger, "");
  item[filed] = value;
}

Vue.prototype.formatDate = function (date, fmt, type) { //type : 类型 0:时间为秒  1:时间为毫秒
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "M+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "h+": date.getHours().toString(),           // 时
    "m+": date.getMinutes().toString(),         // 分
    "s+": date.getSeconds().toString()          // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    };
  };
  return fmt;
}

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')