/**
 * cookie中获取域名
 * */
function GetCookieDomain() {
  var host = location.hostname;
  var ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  if (ip.test(host) === true || host === 'localhost') return host;
  var regex = /([^]*).*/;
  var match = host.match(regex);
  if (typeof match !== "undefined" && null !== match) host = match[1];
  if (typeof host !== "undefined" && null !== host) {
    var strAry = host.split(".");
    if (strAry.length > 1) {
      host = strAry[strAry.length - 2] + "." + strAry[strAry.length - 1];
    }
  }
  return '.' + host;
}
// **
// * cookie中存值
// * */
function setCookie(name, value) {
  var curWwwPath=window.document.location.href;
  var pathName=window.document.location.pathname;
  var pos=curWwwPath.indexOf(pathName);
  var localhostPath=curWwwPath.substring(0,pos);	//获取地址到端口号
  var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); //项目名
  localhostPath = localhostPath.replace(/\"/g, "");
  projectName = projectName.replace(/\"/g, "");

  if (value) {
    var days = 1;	//定义一天
    var exp = new Date();
    exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=" + projectName + ";domain=" + GetCookieDomain();
  }
};
/**
 * cookie中取值
 * */
function getCookie(name) {
  var arr,reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");	//匹配字段
  if (arr = document.cookie.match(reg)) {
    return unescape(arr[2]);
  } else {
    return null;
  }
};
/**
 * 清除全部cookie值
 * */
function clearCookie() {
  console.log('清除成功')
  var curWwwPath=window.document.location.href;
  var pathName=window.document.location.pathname;
  var pos=curWwwPath.indexOf(pathName);
  var localhostPath=curWwwPath.substring(0,pos);	//获取地址到端口号
  var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); //项目名
  localhostPath = localhostPath.replace(/\"/g, "");
  projectName = projectName.replace(/\"/g, "");

  var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
  if (keys) {
    for (var i = keys.length; i--;) {
      document.cookie = keys[i] +'=0;expires=' + new Date( 0).toUTCString() + ";path=" + projectName + ";domain=" + GetCookieDomain();
    }
  }
};
/**
 * 清除指定cookie值
 * */
function delCookie(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = setCookie(name);
  if (cval && cval != null) {
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/video_learning" + ";domain=localhost";
  }
};
export {
  setCookie,
  getCookie,
  clearCookie,
  delCookie
}
