通用方法 - davy-gan/web GitHub Wiki

//是否在壳里
var isApp = yxt.client === 'yxtapp' ? true : false,
  version = yxt.version;
window.jQuery = window.$;
//是否在壳里
var isOldApp = window.y_bridge_public.isY;
var oldVersion = window.y_bridge_public.version;
//用于调试知识打开的机构
var testOrgId = 'b1df5d73-b5fc-414e-8997-5e55f758926c';
// 文码code
var keycode = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv"
  + "wxyz0123456789+/" + "=";
function encodeContent (input) {
  var output = "";
  var chr1, chr2, chr3 = "";
  var enc1, enc2, enc3, enc4 = "";
  var i = 0;
  input = _utf8_encode(input);
  do {
    chr1 = input.charCodeAt(i++);
    chr2 = input.charCodeAt(i++);
    chr3 = input.charCodeAt(i++);
    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
      enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
      enc4 = 64;
    }
    output = output + keycode.charAt(enc1) + keycode.charAt(enc2)
      + keycode.charAt(enc3) + keycode.charAt(enc4);
    chr1 = chr2 = chr3 = "";
    enc1 = enc2 = enc3 = enc4 = "";
  } while (i < input.length);

  return output;
}
// private method for UTF-8 encoding
var _utf8_encode = function (string) {
  string = string.replace(/\r\n/g,"\n");
  var utftext = "";
  for (var n = 0; n < string.length; n++) {
    var c = string.charCodeAt(n);
    if (c < 128) {
      utftext += String.fromCharCode(c);
    } else if((c > 127) && (c < 2048)) {
      utftext += String.fromCharCode((c >> 6) | 192);
      utftext += String.fromCharCode((c & 63) | 128);
    } else {
      utftext += String.fromCharCode((c >> 12) | 224);
      utftext += String.fromCharCode(((c >> 6) & 63) | 128);
      utftext += String.fromCharCode((c & 63) | 128);
    }

  }
  return utftext;
}

// 组装成分页参数,mode为true表示正序asc,false表示倒序desc
function PagingCriteria (pageIndex, pageSize, sort, mode) {
  pageIndex = pageIndex ? pageIndex : 1
  pageSize = pageSize ? pageSize : 10
  var paging = {}
  paging.limit = pageSize
  paging.offset = (pageIndex - 1) * pageSize
  return paging
}

var browser = {
  versions: function () {
    var u = navigator.userAgent, app = navigator.appVersion;
    return {//移动终端浏览器版本信息
      trident: u.indexOf('Trident') > -1, //IE内核
      presto: u.indexOf('Presto') > -1, //opera内核
      webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
      iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1, //是否iPad
      webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
      weixin: u.toLowerCase().match(/MicroMessenger/i) == "micromessenger",
      ios9: u.toLowerCase().match(/os [9]_\d[_\d]* like Mac OS X/i),
      qq: u.toLowerCase().indexOf('qqbrowser') > -1 || u.toLowerCase().indexOf('qq') > -1,//qq壳
      isUcBrowser: u.toLowerCase().indexOf('ucbrowser') > -1 || u.toLowerCase().indexOf('ucweb') > -1 || u.toLowerCase().indexOf('ubrowser') > -1, //uc
      safari: u.indexOf("Safari") > -1 || u.toLowerCase().indexOf("safari") > -1, //safari浏览器
      ding: u.indexOf("DingTalk") > -1 || u.toLowerCase().indexOf("dingtalk") > -1,
      fxiaoke: u.indexOf("FSBrowser") > -1 || u.toLowerCase().indexOf("fsbrowser") > -1
    };
  }(),
  language: function () {
    var userAgents = navigator.userAgent.split(" "), language = userAgents[userAgents.indexOf("language")] || "";
    return (language.split("/")[1] || navigator.language).toLowerCase();
  }
};
//是否在微信中
var isWeixin = browser.versions.weixin, isDing = browser.versions.ding, isFxiaoke = browser.versions.fxiaoke;
var source = '506';
//如果套壳了,才显示
if (isApp) {
  //ios
  if (browser.versions.ios) {
    source = '502';
  }
  //android
  else if (browser.versions.android) {
    source = '503';
  }
}
else if (isWeixin) {
  source = '504';
}


//设置cookie
function setCookie (cname, cvalue) {
  document.cookie = cname + "=" + cvalue + ";";
}
//获取cookie
function getCookie (cname) {
  var result = null;
  var myCookie = "" + document.cookie + ";";
  var searchName = "" + cname + "=";
  var startOfCookie = myCookie.indexOf(searchName);
  var endOfCookie;
  if (startOfCookie != -1) {
    startOfCookie += searchName.length;
    endOfCookie = myCookie.indexOf(";", startOfCookie);
    result = (myCookie.substring(startOfCookie, endOfCookie));
  }
  return result;
}
//清除cookie
function clearCookie (name) {
  setCookie(name, "");
}

//取缓存value
function getLocalStorage (key) {
  var value;
  try {
    localStorage.setItem("TestKey", "123");
    value = localStorage.getItem(key);
  }
  catch (e) {
    value = getCookie(key);
  }

  return value;
}
//设置缓存值
function setLocalStorage (key, value) {
  try {
    localStorage.setItem(key, value);
  }
  catch (e) {
    setCookie(key, value);
  }
}

function removeLocalStorage (key) {
  try {
    localStorage.removeItem(key);
  }
  catch (e) {
    clearCookie(key, "");
  }
}

function getSessionStorage (key) {
  var value;
  try {
    sessionStorage.setItem("TestKey", "123");
    value = sessionStorage.getItem(key);
  }
  catch (e) {
    value = getCookie(key);
  }

  return value;
}

function setSessionStorage (key, value) {
  try {
    sessionStorage.setItem(key, value);
  }
  catch (e) {
    setCookie(key, value);
  }
}

function removeSessionStorage (key) {
  try {
    sessionStorage.removeItem(key);
  }
  catch (e) {
    clearCookie(key, "");
  }
}
/**
 * 清除cookie
 * 创建人:肖刚
 * 创建时间:2015年10月30日
 */
function clearCookieForKey () {
  clearCookie("isClickMy");
  clearCookie("userId");
  clearCookie("orgId");
  clearCookie("email");
  clearCookie("mobile");
  clearCookie("headPictureUrl");
  clearCookie("isEmailValidated");
  clearCookie("isMobileValidated");
  clearCookie("token");
  clearCookie("isClickMy");
  clearCookie("toolbar");
  clearCookie("apps");
  clearCookie("clientKey");
  clearCookie("deviceId");
  //clearCookie("returnUrl");
  clearCookie("toolbarnew");
  clearMallCookieForKey();
}

function clearMallCookieForKey () {
  clearCookie("dd_order");
  clearCookie("mall_orgaccountid");
  clearCookie("mall_accountid");
  clearCookie("mall_admin");
  clearCookie("mall_fullname");
  clearCookie("mall_userid");
  clearCookie("mall_orgid");
  clearCookie("mall_sunperadmin");
  clearCookie("mall_rolelist");
  clearCookie("huihui_hostid");
  clearCookie("huihui_capacity");
  clearCookie("huihui_said");
  clearCookie("huihui_ismaxcapacity");
  clearCookie("isInlay");
}

function clearlocalStorageForKey () {
  localStorage.removeItem("userId");
  localStorage.removeItem("orgName");
  localStorage.removeItem("websitepicurl");
  localStorage.removeItem("email");
  localStorage.removeItem("mobile");
  localStorage.removeItem("headPictureUrl");
  localStorage.removeItem("isEmailValidated");
  localStorage.removeItem("isMobileValidated");
  localStorage.removeItem("token");
  localStorage.removeItem("toolbar");
  localStorage.removeItem("apps");
  localStorage.removeItem("isClickMy");
  localStorage.removeItem("clientKey");
  localStorage.removeItem("deviceId");
  localStorage.removeItem("schemeversion");
  localStorage.removeItem("newIndex");
  localStorage.removeItem("toolbarnew");
  sessionStorage.clear();
  localStorage.removeItem("sex");
  localStorage.removeItem("ouId");
  localStorage.removeItem("ouName");
  localStorage.removeItem("positionId");
  localStorage.removeItem("positionName");
  localStorage.removeItem("searchKnowledgeKeywords");
  localStorage.removeItem("oldhuazhuad");
  localStorage.removeItem("examSource");
  localStorage.removeItem("communitySearch");
  clearlocalStorageMallForKey();
  var storage = window.localStorage;
  var len = storage.length;
  for (var i=len; i  >=  0; i--){
    var key = storage.key(i);
    if (key && key.indexOf('CACHEDATA') > -1) {
      localStorage.removeItem(key)
    }
  }
}

function clearlocalStorageMallForKey () {
  localStorage.removeItem("dd_order");
  localStorage.removeItem("mall_orgaccountid");
  localStorage.removeItem("mall_accountid");
  localStorage.removeItem("mall_admin");
  localStorage.removeItem("mall_fullname");
  localStorage.removeItem("mall_userid");
  localStorage.removeItem("mall_orgid");
  localStorage.removeItem("mall_sunperadmin");
  localStorage.removeItem("mall_rolelist");
  localStorage.removeItem("huihui_hostid");
  localStorage.removeItem("huihui_capacity");
  localStorage.removeItem("huihui_said");
  localStorage.removeItem("huihui_ismaxcapacity");
}

// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d H:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};

function getMinusTime (time) {
  var timeObj = {};
  timeObj.years = Math.floor(time / (365 * 24 * 60 * 60 * 1000));

  var leave1 = time % (365 * 24 * 60 * 60 * 1000);
  timeObj.months = Math.floor(leave1 / (30 * 24 * 60 * 60 * 1000));

  var leave2 = leave1 % (30 * 24 * 60 * 60 * 1000);
  timeObj.days = Math.floor(leave2 / (24 * 60 * 60 * 1000));

  var leave3 = leave2 % (24 * 60 * 60 * 1000);
  timeObj.hours = Math.floor(leave3 / (60 * 60 * 1000));

  var leave4 = leave3 % (3600 * 1000);
  timeObj.minutes = Math.floor(leave4 / (60 * 1000));

  var leave5 = leave4 % (60 * 1000);
  timeObj.seconds = Math.round(leave5 / 1000);
  return timeObj;
}

//使当前及其子元素失去焦点
function blur (elem) {
  $(elem).blur().find("input,textarea").blur();
}

//将时间格式化成YYYY/MM/dd HH:mm:ss
function DateFormat (time) {
  return (time || "").replace(/\.\d+/, "").replace(/-/g, "/");
}


//JS生成GUID函数,类似.net中的NewID();
function NewGuid () {
  return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function S4 () {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function setLoginInfo (data) {
  setLocalStorage("userName", data.fullName);
  setLocalStorage("userId", data.userId);
  setLocalStorage("orgId", data.orgId);
  setLocalStorage("orgName", data.webSiteName);
  setLocalStorage("websitepicurl", data.logoUrl);
  setLocalStorage("orgCode", data.orgCode);
  setLocalStorage("email", data.email);
  setLocalStorage("mobile", data.mobile);
  setLocalStorage("headPictureUrl", data.headPictureUrl);
  setLocalStorage("isEmailValidated", data.isEmailValidated);
  setLocalStorage("isMobileValidated", data.isMobileValidated);
  setLocalStorage("token", data.token);
  setLocalStorage("loginUserName", data.userName);
  setLocalStorage("domainName", data.domainName);
  data.clientKey ? setLocalStorage("clientKey", data.clientKey) : null;
  data.deviceId ? setLocalStorage("deviceId", data.deviceId) : null;
  setLocalStorage("sex", data.sex);
  setLocalStorage("ouId", data.ouId);
  setLocalStorage("ouName", data.ouName);
  setLocalStorage("positionId", data.positionId);
  setLocalStorage("positionName", data.positionName);
}
//用于IOS输入法切换时插入的特殊字符
function input_iosRevise (str) {
  return str ? str.replace(/\u2006/g, '') : "";
}

/*
 函数:格式化日期
 参数:formatStr-格式化字符串
 d:将日显示为不带前导零的数字,如1
 dd:将日显示为带前导零的数字,如01
 ddd:将日显示为缩写形式,如Sun
 dddd:将日显示为全名,如Sunday
 M:将月份显示为不带前导零的数字,如一月显示为1
 MM:将月份显示为带前导零的数字,如01
 MMM:将月份显示为缩写形式,如Jan
 MMMM:将月份显示为完整月份名,如January
 yy:以两位数字格式显示年份
 yyyy:以四位数字格式显示年份
 h:使用12小时制将小时显示为不带前导零的数字,注意||的用法
 hh:使用12小时制将小时显示为带前导零的数字
 H:使用24小时制将小时显示为不带前导零的数字
 HH:使用24小时制将小时显示为带前导零的数字
 m:将分钟显示为不带前导零的数字
 mm:将分钟显示为带前导零的数字
 s:将秒显示为不带前导零的数字
 ss:将秒显示为带前导零的数字
 l:将毫秒显示为不带前导零的数字
 ll:将毫秒显示为带前导零的数字
 tt:显示am/pm
 TT:显示AM/PM
 返回:格式化后的日期
 */
Date.prototype.formatDate = function (formatStr) {
  var date = this;

  /*
   函数:填充0字符
   参数:value-需要填充的字符串, length-总长度
   返回:填充后的字符串
   */
  var zeroize = function (value, length) {
    if (!length) {
      length = 2;
    }
    value = new String(value);
    for (var i = 0, zeros = ''; i < (length - value.length); i++) {
      zeros += '0';
    }
    return zeros + value;
  };

  return formatStr.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|[lLZ])\b/g, function ($0) {
    switch ($0) {
      case 'd':
        return date.getDate();
      case 'dd':
        return zeroize(date.getDate());
      case 'ddd':
        return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][date.getDay()];
      case 'dddd':
        return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
      case 'M':
        return date.getMonth() + 1;
      case 'MM':
        return zeroize(date.getMonth() + 1);
      case 'MMM':
        return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()];
      case 'MMMM':
        return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][date.getMonth()];
      case 'yy':
        return new String(date.getFullYear()).substr(2);
      case 'yyyy':
        return date.getFullYear();
      case 'h':
        return date.getHours() % 12 || 12;
      case 'hh':
        return zeroize(date.getHours() % 12 || 12);
      case 'H':
        return date.getHours();
      case 'HH':
        return zeroize(date.getHours());
      case 'm':
        return date.getMinutes();
      case 'mm':
        return zeroize(date.getMinutes());
      case 's':
        return date.getSeconds();
      case 'ss':
        return zeroize(date.getSeconds());
      case 'l':
        return date.getMilliseconds();
      case 'll':
        return zeroize(date.getMilliseconds());
      case 'tt':
        return date.getHours() < 12 ? 'am' : 'pm';
      case 'TT':
        return date.getHours() < 12 ? 'AM' : 'PM';
    }
  });
}

// 说明:两个时间相减
// 参数:JS的Date类型,或者 string 类型,格式为:yyyy-MM-dd HH:mm:ss
// 返回: date1-date2的秒数
var substractDate = function (date1, date2) {
  var type1 = typeof date1;
  var type2 = typeof date2;
  if (type1 == 'string') {
    date1 = new Date(date1);
  }
  if (type2 == 'string') {
    date2 = new Date(date2);
  }
  return (date1 - date2) / 1000;
}

//相隔天数
function getDays (strDateStart, strDateEnd) {
  var strDateS = new Date(strDateStart.formatDate("yyyy-MM-dd"));
  var strDateE = new Date(strDateEnd.formatDate("yyyy-MM-dd"));
  iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24)//把相差的毫秒数转换为天数
  return iDays;
}

//几秒前,几分钟前
function GetDateStringForDate (date, type, Lang) {
  var formatDateString = "";
  var limit = substractDate(new Date, date);
  var secondNum = 60; //60秒
  var minutesNum = 3600; //60分钟
  var hourNum = 86400;  //24小时

  if (limit < secondNum) {
    var info = "";
    if (Lang == "en")//英文
    {
      info = "Seconds ago";
    }
    else if (Lang == "ha")//繁体
    {
      info = "秒鐘前";
    }
    else//其他全为中文
    {
      info = "秒钟前";
    }
    var li = Math.round(limit);
    if (li <= 0) {
      li = 1;
    }
    formatDateString = Math.round(limit) + info;
  }
  else if (limit < minutesNum) {
    var info = "";
    if (Lang == "en")//英文
    {
      info = "minutes ago";
    }
    else if (Lang == "ha")//繁体
    {
      info = "分鐘前";
    }
    else//其他全为中文
    {
      info = "分钟前";
    }
    formatDateString = Math.round(limit / secondNum) + info;
  }
  else if (limit < hourNum) {
    var info = "";
    if (Lang == "en")//英文
    {
      info = "hour ago";
    }
    else if (Lang == "ha")//繁体
    {
      info = "小時前";
    }
    else//其他全为中文
    {
      info = "小时前";
    }
    formatDateString = Math.round(limit / minutesNum) + info;
  }
  else {
    var dbNum = getDays(new Date, date);
    if (dbNum == 1) {
      if (Lang == "en")//英文
      {
        formatDateString = "Yday " + getDateString(date, 4, Lang);
      }
      else if (Lang == "ha")//繁体
      {
        formatDateString = "昨天 " + getDateString(date, 4, Lang);
      }
      else//其他全为中文
      {
        formatDateString = "昨天 " + getDateString(date, 4, Lang);
      }
    }
    else if (dbNum == 2) {
      if (Lang == "en")//英文
      {
        formatDateString = "DBY " + getDateString(date, 4, Lang);
      }
      else if (Lang == "ha")//繁体
      {
        formatDateString = "前天 " + getDateString(date, 4, Lang);
      }
      else//其他全为中文
      {
        formatDateString = "前天 " + getDateString(date, 4, Lang);
      }
    }
    else {
      formatDateString = getDateString(date, type, Lang);
    }

  }
  return formatDateString;
}

//获取时间格式(国际化)
//date 时间,type:0短格式(年月日);1长格式(年月日时分);2是否启用几秒前长格式(年月日时分);3是否启用几秒前短格式(年月日),lang语言
function getDateString (date, type, lang) {
  if (date == null || date == "" || typeof (date) == "undefined")
    return "-";
  var type1 = typeof date;
  if (type1 == 'string') {
    date = new Date(date.replace(/-/g, "/").replace(/\.[0-9]*$/g, ''));
  }
  var formatDateString = "";
  if (lang.toLowerCase().indexOf("en") > -1)//英文
  {
    switch (type) {
      case 0:
        formatDateString = date.formatDate("MMM dd,yyyy");
        break;
      case 1:
        formatDateString = date.formatDate("MMM dd,yyyy hh:mm TT");
        break;
      case 2:
        formatDateString = GetDateStringForDate(date, 1, lang);
        break;
      case 3:
        formatDateString = GetDateStringForDate(date, 0, lang);
        break;
      case 4:
        formatDateString = date.formatDate("hh:mm TT");
        break;
    }
  }
  else if (lang.toLowerCase().indexOf("ha") > -1)//繁体
  {
    switch (type) {
      case 0:
        formatDateString = date.formatDate("yyyy-MM-dd");
        break;
      case 1:
        formatDateString = date.formatDate("yyyy-MM-dd HH:mm");
        break;
      case 2:
        formatDateString = GetDateStringForDate(date, 1, lang);
        break;
      case 3:
        formatDateString = GetDateStringForDate(date, 0, lang);
        break;
      case 4:
        formatDateString = date.formatDate("HH:mm");
        break;
    }
  }
  else//其他全为中文
  {
    switch (type) {
      case 0:
        formatDateString = date.formatDate("yyyy-MM-dd");
        break;
      case 1:
        formatDateString = date.formatDate("yyyy-MM-dd HH:mm");
        break;
      case 2:
        formatDateString = GetDateStringForDate(date, 1, lang);
        break;
      case 3:
        formatDateString = GetDateStringForDate(date, 0, lang);
        break;
      case 4:
        formatDateString = date.formatDate("HH:mm");
        break;
    }
  }
  return formatDateString;
}

function floorNumber (number) {
  return Math.floor(number) ? Math.floor(number) : 0
}

function parseFloatNumber (number) {
  return parseFloat(number) ? parseFloat(number) : 0
}

function isLogin () {
  if (localStorage.userId && localStorage.token && localStorage.orgId) {
    return true
  } else {
    clearlocalStorageForKey()
    return false
  }
}

function showKng () {
  var isInlay = !!window.localStorage.getItem('isInlay')
  //isApp = window.y_bridge_public.isY,
  var isWeChat = browser.versions.weixin
  if (isInlay || isApp || isWeChat || isDing || isFxiaoke) {
    return true
  }
  return false
}

// 通用方法名称空间
var util_methods = {};

(function ($) {
  util_methods = {

    getWeek: function (date) {

      if (!(date instanceof Date)) {
        date = new Date(date);
      }

      var weekArr = [],
        year = date.getFullYear(),
        month = date.getMonth(),
        day = date.getDate(),
        week = date.getDay(),
        temp, index = (week + 6) % 7;
      for (i = 0; i < index; i++) {
        temp = new Date(year, month, day + i - index);

        weekArr[i] = temp.getFullYear() + "/" + ( "0" + (temp.getMonth() + 1)).substr(-2, 2) + "/" + ("0" + temp.getDate()).substr(-2, 2);
      }

      weekArr[index] = year + "/" + ( "0" + (month + 1)).substr(-2, 2) + "/" + ("0" + day).substr(-2, 2);

      for (i = index + 1; i < 7; i++) {
        temp = new Date(year, month, day + i - index);
        weekArr[i] = temp.getFullYear() + "/" + ( "0" + (temp.getMonth() + 1)).substr(-2, 2) + "/" + ("0" + temp.getDate()).substr(-2, 2);
      }
      return weekArr;
    },

   
    getCurrentWeek: function () {
      var d = new Date();

      return this.getWeek(d);
    },

    getPrevWeek: function (d) {
      var date = d;
      if (!(d instanceof Date)) {
        date = new Date(d);
      }

      date = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 7);


      return this.getWeek(date);
    },

    getNextWeek: function (d) {
      var date = d;
      if (!(d instanceof Date)) {
        date = new Date(d);
      }

      date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7);

      return this.getWeek(date);
    },

    getCurrentDayInfo: function () {
      var date = new Date();
      this.year = date.getFullYear();
      this.month = date.getMonth() + 1;
      this.date = date.getDate();
      this.day = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"][date.getDay()];
      this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      var currentTime = ( "0" + (this.month)).substr(-2, 2) + "月" + ("0" + this.date).substr(-2, 2) + "日 " + this.day;

      return currentTime;
    }

  };
})(jQuery);

// 换肤
function changeTheme(url) {
  var head = document.getElementsByTagName('head')[0];
  var link = document.createElement('link');
  link.type='text/css';
  link.rel = 'stylesheet';
  link.href = url;
  head.appendChild(link);
}

/**
 * 返回指定主站的界面
 * @return {stringg} 主站地址
 */
function goMainStationUrl (page) {
  if (!page) {
    page = 'login'
  }
  var origin = window.location.origin
  return origin + '/#/' + page
}
import Vue from 'vue'
import { locales } from '@/configs/locales'
import { config } from '@/configs/consts'
export const isNullOrEmpty = (s) => {
  if (s === null || s === '') {
    return true
  } else {
    return false
  }
}

export const isString = (str) => {
  if (typeof str === 'string') {
    return true
  } else {
    return false
  }
}

// 分页
export const PagingCriteria = (pageIndex, pageSize, sort, mode) => {
  let paging = {}
  paging.limit = pageSize
  paging.offset = (pageIndex - 1) * pageSize
  if (!isNullOrEmpty(sort)) {
    paging.orderby = sort
  }
  if (!isNullOrEmpty(mode)) {
    paging.direction = mode
  }
  return paging
}
export const setLanguage = type => {
  let lang
  if (type === 1) { // 简体中文
    lang = 'ch'
  } else if (type === 2) { // 繁体中文
    lang = 'ha'
  } else if (type === 3) { // 英文
    lang = 'en'
  }
  Vue.config.lang = lang
  config.lang = lang
  Vue.locale(lang, locales[lang])
}
// 拼接URL参数
export const linkSubString = (url, data) => {
  if (url === null || url === '') {
    return url
  }
  let queryString = ''
  if (typeof data === 'object') {
    for (var i in data) {
      queryString += i + '=' + data[i] + '&'
    }
  }
  if (url.indexOf('?') > url.indexOf('/')) {
    url += '&'
  } else {
    url += '?'
  }
  if (queryString !== '') {
    queryString = queryString.substr(0, queryString.length - 1)
  }
  url += queryString
  return url
}

/**
 * 求一个最接近它的整数,它的值小于或等于这个浮点数
 */
export const floorNumber = number => {
  return Math.floor(number) ? Math.floor(number) : 0
}

/**
 * 解析一个字符串,并返回一个浮点数。
 */
export const parseFloatNumber = number => {
  return parseFloat(number) ? parseFloat(number) : 0
}

// 用户头像
export const GetAvatarImageFilter = (imageUrl, width, height, quality, scale) => {
  if (!imageUrl) {
    imageUrl = 'https://picobd-sk.yxt.com/common/imgs/default_head.png'
  }
  let imgeMogrList = []
  // 默认给80%的画质
  if (quality > 0) {
    imgeMogrList.push('q_' + quality)
  } else {
    imgeMogrList.push('q_80')
  }
  if (width > 0) {
    imgeMogrList.push('w_' + width)
  }
  if (height > 0) {
    imgeMogrList.push('h_' + height)
  }
  if (width && height && scale) {
    imgeMogrList.push('s_' + scale)
  }
  imageUrl += (imageUrl.indexOf('@') > 0 ? '|' : '@')
  imageUrl += imgeMogrList.join(',')
  return imageUrl
}

// 图片
export const GetCommonImageFilter = (imageUrl, width, height, quality, scale) => {
  if (!imageUrl) {
    imageUrl = 'https://picobd-bbs.yxt.com/common/imgs/covers/fail_img.png'
  }
  if (imageUrl.indexOf('xuanyes.com') > -1 || (imageUrl.indexOf('.yunxuetang.') === -1 && imageUrl.indexOf('.yxt.') === -1)) {
    return GetXuankeImageFilter(imageUrl, width, height, quality)
  }
  let imgeMogrList = []
  // 默认给80%的画质
  if (quality > 0) {
    imgeMogrList.push('q_' + quality)
  } else {
    imgeMogrList.push('q_80')
  }
  if (width > 0) {
    imgeMogrList.push('w_' + width)
  }
  if (height > 0) {
    imgeMogrList.push('h_' + height)
  }
  if (width && height && scale) {
    imgeMogrList.push('s_' + scale)
  }
  imageUrl += (imageUrl.indexOf('@') > 0 ? '|' : '@')
  imageUrl += imgeMogrList.join(',')
  return imageUrl
}

// 炫课图片(阿里云)
export const GetXuankeImageFilter = (imageUrl, width, height, quality) => {
  if (!imageUrl || imageUrl.indexOf('.yunxuetang.') > -1 || imageUrl.indexOf('.yxt.') > -1) {
    return GetCommonImageFilter(imageUrl, width, height, quality)
  }
  if (imageUrl.indexOf('xuanyes.com') === -1) {
    return imageUrl
  }
  imageUrl = imageUrl.split('?')[0]
  imageUrl = imageUrl.split('@')[0]
  let paramStr = '?x-oss-process=image'
  let resizeParams = ['resize']
  let qualityParams = ['quality']
  // 默认给80%的画质
  if (quality > 0) {
    qualityParams.push('q_' + quality)
  } else {
    qualityParams.push('q_80')
  }
  if (width > 0) {
    resizeParams.push('w_' + width)
  }
  if (height > 0) {
    resizeParams.push('h_' + height)
  }
  imageUrl += paramStr
  if (width || height) {
    imageUrl += '/' + resizeParams.join(',')
  }
  imageUrl += '/' + qualityParams.join(',')
  return imageUrl
}

/**
 *  短日期,如2018年8月20日
 */

export const fomateSort = (time) => {
  let friendlyDate = ''
  if (time === '' || time === undefined) {
    return friendlyDate
  } else {
    time = time.split('.', 1)[0]
    time = time.replace(new RegExp(/(-)/g), '/')
  }
  let createDate = new Date(time)
  friendlyDate = createDate.FormatDateStr()
  return friendlyDate
}

/**
 *  短日期,如2018-8-20
 */

export const fomateTime = (time) => {
  let friendlyDate = ''
  if (time === '' || time === undefined) {
    return friendlyDate
  } else {
    time = time.split('.', 1)[0]
    time = time.replace(new RegExp(/(-)/g), '/')
  }
  let createDate = new Date(time)
  friendlyDate = createDate.FormatTim()
  return friendlyDate
}

/**
 *  长日期,如2018-8-20 08:10
 */

export const fomateLong = (time) => {
  let friendlyDate = ''
  if (time === '' || time === undefined) {
    return friendlyDate
  } else {
    time = time.split('.', 1)[0]
    time = time.replace(new RegExp(/(-)/g), '/')
  }
  let createDate = new Date(time)
  friendlyDate = createDate.FormatDateLong()
  return friendlyDate
}

export const friendlyDateFilter = (time) => {
  let friendlyDate = ''
  if (time === '' || time === undefined) {
    return friendlyDate
  } else {
    time = time.split('.', 1)[0]
    time = time.replace(new RegExp(/(-)/g), '/')
  }
  let currTimeStr = new Date().Format('yyyy/MM/dd HH:mm:ss') // 当前时间字符串
  let now = new Date(currTimeStr) // 当前时间对象
  let createDate = new Date(time)
  let dayDiff = new Date(time).dateDiff('d', now) // 天数之差
  let minutesDiff = new Date(time).dateDiff('n', now) // 分钟之差
  let hoursDiff = new Date(time).dateDiff('h', now) // 小时之差
  let weeksDiff = new Date(time).dateDiff('w', now) // 星期之差
  if (Math.abs(dayDiff) <= 30) {
    // 上下三十天内
    if (dayDiff === 0) {
      // 当天
      if (minutesDiff === 0) {
        friendlyDate = '现在'
      } else if (Math.abs(minutesDiff) > 60) { // minutesDiff  Math.abs(hoursDiff) >= 1
        // 当天的前后一小时之外
        if (hoursDiff < 0) {
          friendlyDate = Math.abs(hoursDiff) + '小时后'
        } else {
          friendlyDate = Math.abs(hoursDiff) + '小时前'
        }
      } else {
        // 一小时之内
        if (minutesDiff < 0) {
          friendlyDate = Math.abs(minutesDiff) + '分钟后'
        } else {
          friendlyDate = Math.abs(minutesDiff) + '分钟前'
        }
      }
    } else if (dayDiff < 0) {
      // 后三十天内
      if (createDate.getFullYear() === now.getFullYear()) {
        // 同一年
        if (weeksDiff === -1) {
          friendlyDate = '下周' + createDate.getWeekDay()
        } else {
          // n天后
          friendlyDate = Math.abs(dayDiff) + '天后'
        }
      } else {
        // n天后
        friendlyDate = Math.abs(dayDiff) + '天后'
      }
    } else {
      // 前三十天内
      if (createDate.getFullYear() === now.getFullYear()) {
        if (weeksDiff === 1) {
          friendlyDate = '上周' + createDate.getWeekDay()
        } else {
          friendlyDate = Math.abs(dayDiff) + '天前'
        }
      } else {
        friendlyDate = Math.abs(dayDiff) + '天前'
      }
    }
  } else {
    if (createDate.getFullYear() !== now.getFullYear()) {
      friendlyDate = createDate.FormatDateStr()
    } else {
      friendlyDate = createDate.FormatDateStr()
    }
  }
  return friendlyDate
}

export const friendlyDateBeforeFilter = (time) => {
  let friendlyDate = ''
  if (time === '' || time === undefined) {
    return friendlyDate
  } else {
    time = time.split('.', 1)[0]
    time = time.replace(new RegExp(/(-)/g), '/')
  }
  let now = new Date() // 当前时间对象
  let createDate = new Date(time.replace(/-/g, '/'))
  // 去掉 js 时间戳后三位,与php 时间戳保持一致
  time = parseInt((now.getTime() - createDate.getTime()) / 1000)
  // alert(time)

  // 存储转换值
  var s
  if (time < 60 * 1) { // 一分钟内
    return '刚刚'
  } else if ((time < 60 * 60) && (time >= 60 * 1)) {
    // 超过十分钟少于1小时
    s = Math.floor(time / 60)
    return s + '分钟前'
  } else if ((time < 60 * 60 * 24) && (time >= 60 * 60)) {
    // 超过1小时少于24小时
    s = Math.floor(time / 60 / 60)
    return s + '小时前'
  } else if ((time < 60 * 60 * 24 * 2) && (time >= 60 * 60 * 24)) {
    // 超过1天少于3天内
    // s = Math.floor(time / 60 / 60 / 24)
    let hours = (createDate.getHours() < 10 ? '0' : '') + createDate.getHours()
    let minutes = (createDate.getMinutes() < 10 ? '0' : '') + createDate.getMinutes()
    return '昨天 ' + hours + ':' + minutes
  } else if ((time < 60 * 60 * 24 * 3) && (time >= 60 * 60 * 24) * 2) {
    let hours = (createDate.getHours() < 10 ? '0' : '') + createDate.getHours()
    let minutes = (createDate.getMinutes() < 10 ? '0' : '') + createDate.getMinutes()
    return '前天 ' + hours + ':' + minutes
  } else {
    // 超过3天
    // var date = new Date(parseInt(date) * 1000)
    let year = createDate.getFullYear()
    let month = (createDate.getMonth() < 9 ? '0' : '') + (createDate.getMonth() + 1)
    let day = (createDate.getDate() < 10 ? '0' : '') + createDate.getDate()
    return year + '-' + month + '-' + day
  }
}

export const GetXuanThumbnailFilter = (imageUrl, version) => {
  if (imageUrl.indexOf('http://') === -1 && imageUrl.indexOf('https://')) {
    return '//pic.xuanyes.com/works/defaultcourse.png@!small?version=2'
  }
  imageUrl = imageUrl.replace('http://', 'https://')
  imageUrl = imageUrl.replace('!middle', '!small')
  if (imageUrl.indexOf('?') === -1) {
    if (imageUrl.indexOf('@') === -1) {
      imageUrl = imageUrl + '@!small'
    }
    if (version) {
      imageUrl = imageUrl + '?version=' + version
    }
  }
  return imageUrl
}

export const dateToString = (text, format) => {
  if (isNullOrEmpty(text) || !text) {
    return ''
  }
  if (isString(text)) {
    text = text.replace(/\.\d+/, '').replace(/-/g, '/')
  }
  let date = new Date(text)
  if (isNullOrEmpty(date) || date === 'Invalid Date') {
    return ''
  }
  let dateStr = format
  dateStr = dateStr
    .replace('yyyy', date.getFullYear())
    .replace('MM', (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1))
    .replace('dd', (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()))
    .replace('HH', (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()))
    .replace('mm', (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()))
    .replace('ss', (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()))
  dateStr = dateStr
    .replace('M', date.getMonth() + 1)
    .replace('d', date.getDate())
    .replace('H', date.getHours())
    .replace('m', date.getMinutes())
    .replace('s', date.getSeconds())
  return dateStr
}

// 日期字符串变为日期格式
export const stringToDate = (text) => {
  if (!isNullOrEmpty(text) && isString(text)) {
    text = text.replace(/\.\d+/, '').replace(/-/g, '/')
    return new Date(text)
  }
  return text
}

export const getQueryString = (name) => {
  try {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    let r = window.location.search.substr(1).match(reg)
    if (r != null) {
      return decodeURIComponent(r[2])
    }
    r = window.location.hash.substr(window.location.hash.indexOf('?') + 1).match(reg)
    if (r != null) {
      return decodeURIComponent(r[2])
    }
    return null
  } catch (e) {
    return null
  }
}

export const seperate = (time) => {
  let year = time.getFullYear()
  let month = time.getMonth()
  let day = time.getDate()
  let hour = time.getHours()
  let minute = time.getMinutes()
  let second = time.getSeconds()
  return {year, month, day, minute, second, hour}
}

export const objectToString = (obj) => {
  return obj.year + '-' + (obj.month + 1) + '-' + obj.day +
  ' ' + obj.hour + ':' + obj.minute + ':' + obj.second
}

export const hasClass = (el, className) => {
  let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
  return reg.test(el.className)
}

export const addClass = (el, className) => {
  if (hasClass(el, className)) {
    return
  }
  let newClass = el.className.split(' ')
  newClass.push(className)
  el.className = newClass.join(' ')
}

export const goMainStationUrl = (page = 'login') => {
  let protocol = window.location.protocol
  let domainName = window.location.hostname
  return `${protocol}//${domainName}/${page}.htm?fromurl=%2Fworkshop%2F%23%2Findex`
}
export const goUrl = (url) => {
  let protocol = window.location.protocol
  let domainName = window.location.hostname
  return `${protocol}//${domainName}/${url}`
}

let trimFun = ''.trim
export const trim = trimFun && !trimFun.call('\uFEFF\xA0') ? function (e) {
  return e == null ? '' : trimFun.call(e)
} : function (e) {
  return e == null ? '' : (e + '').replace(
    /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
}

export const animate = function (obj, json, sp, fn) {
  let interval = 10
  let lastIcur
  if (!sp) sp = 0.1
  clearInterval(obj.timer)
  function getStyle (obj, arr) {
    if (obj.currentStyle) {
      return obj.currentStyle[arr]
    } else {
      return document.defaultView.getComputedStyle(obj, null)[arr]
    }
  }

  obj.timer = setInterval(function () {
    var flag = true
    for (var arr in json) {
      var icur = 0
      if (arr === 'opacity') {
        icur = Math.round(parseFloat(getStyle(obj, arr)) * 100)
      } else if (arr === 'scrollTop') {
        icur = parseInt(obj.scrollTop)
      } else {
        icur = parseInt(getStyle(obj, arr))
      }
      if (isNaN(icur)) icur = json[arr]
      var speed = (json[arr] - icur) * sp
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
      if (lastIcur !== icur && icur !== json[arr]) {
        flag = false
      }
      lastIcur = icur
      if (arr === 'opacity') {
        obj.style.filter = 'alpha(opacity : \'+(icur + speed)+\' )'
        obj.style.opacity = (icur + speed) / 100
      } else if (arr === 'scrollTop') {
        obj.scrollTop = icur + speed
      } else {
        obj.style[arr] = icur + speed + 'px'
      }
    }

    if (flag) {
      clearInterval(obj.timer)
      if (fn) {
        fn()
      }
    }
  }, interval)
}

export const loadScript = (url) => {
  if (!url) {
    return
  }
  let script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = url
  document.body.appendChild(script)
}
export const isIE9 = () => {
  let userAgent = navigator.userAgent
  let isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1
  let matchArr = userAgent.match(/MSIE\s+(\d+\.\d+);/)
  let ieVersion

  if (isIE && matchArr) {
    ieVersion = parseInt(matchArr[1])
    if (ieVersion <= 9) { return true }
  } return false
}