import { ENV_CONFIG } from './enumerate';

const { NUXT_ENV_APP } = process.env;

export const getSearchByName = name => {
  const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.href);
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
};

export const getItem = name => {
  if (!name) return;
  const v = sessionStorage.getItem(name);
  let val = null;
  try {
    val = JSON.parse(v);
  } catch (e) {
    // JSON.parse 失败 后 直接赋v给val;
    val = v;
  }
  return val;
};

export const setItem = (name, value) => {
  if (!name) return;
  if (typeof value !== 'string') {
    value = JSON.stringify(value);
  }
  sessionStorage.setItem(name, value);
};

export const removeItem = name => {
  if (!name) return;
  sessionStorage.removeItem(name);
};

export const getConfigByEvtType = key => {
  return ENV_CONFIG[NUXT_ENV_APP][key];
}

export const getNoticeUrl = url => {
  return `${getConfigByEvtType('noticeUrl')}${url}`;
}

export const getWxLoginUrl = url => {
  return `${getConfigByEvtType('wxLoginUrl')}`;
}

export const getWxAPPID = url => {
  return `${getConfigByEvtType('APPID')}`;
}

// 获取SC服务器域名地址
export const getBaseUrl = url => {
  return `${getConfigByEvtType('baseUrl')}${url}`;
}

// 获取API服务器域名地址
export const getApiUrl = url => {
  return `${getConfigByEvtType('apiUrl')}${url}`;
}

export const getWxDomainUrl = url => {
  return `${getConfigByEvtType('domain')}`;
}

export const getShareUrl = url => {
  return `${getConfigByEvtType('shareUrl')}`;
}

export const getBaseMainUrl = url => {
  return `${getConfigByEvtType('baseUrl')}`;
}

export const getCookie = cname => {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        //console.log("获取cookie,现在循环")
        for (var i = 0; i < ca.length; i++) {
          var c = ca[i];
         // console.log(c)
          while (c.charAt(0) == ' ') c = c.substring(1);
          if (c.indexOf(name) != -1){
            return c.substring(name.length, c.length);
          }
        }
        return "";
    };

 export const delCookie = (name,domain) =>{

    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    
    if(cval!=null){
        //document.cookie = name + "="+cval+";expires="+exp.toGMTString();
        document.cookie = name + '=; path=/; expires=' + new Date(0).toUTCString();
        document.cookie = name + '=; path=/; domain=.yunqueyi.com; expires=' + new Date(0).toUTCString();
    } 

};

export const setCookie = (cname, cvalue, exdays) => {
	        var d = new Date();
	        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
					//d.setTime(d.getTime() + (2* 60 * 1000));
	        var expires = "expires=" + d.toUTCString();
	       // console.info(cname + "=" + cvalue + "; " + expires);
	        document.cookie = cname + "=" + cvalue + ";path=/;" + expires;
	        //console.info(document.cookie);
	    };

export const setEventByModuleCode = (itemData, token) => {
  let modeCode = itemData.code || '';
  let paramList = itemData.paramList ? itemData.paramList : '';
  if (modeCode === 'M001' || modeCode === 'M002' || modeCode === 'M003') {
    paramList = '';
  } else if (
    modeCode === 'M100' ||
    modeCode === 'M300' ||
    modeCode === 'M500' || modeCode === 'M301'
  ) {
    let urlPara = getUrlParmByCode(paramList, token);
    paramList[0] && (paramList[0].value += urlPara);
    // 前端拼接了数据，原生不用再拼接
		paramList = paramList.slice(0, 1)
  }

  if (typeof paramList === 'string' && !paramList) {
    paramList = [];
  }

  return paramList;
}

export const refreFun = () => {
  let str = location.href,
    a = '',
    b = '',
    url = ''
  if(str.indexOf('?code') > -1){
    a = str.split('#')[0].split('?')[0];
    b = str.split('#')[1];
    url = a + '#' + b;
    console.log(url)
    setTimeout(()=>{
      location.href = url;
    },1000)
    
  }
}

export const pageBurialPoin = (options) => {
  let opt = {
    menuLevel: options.menuLevel || '',
    functionCode: options.functionCode || '',
    actionCode: options.actionCode || '',
    // label:options.label || '',
    labelId: options.labelId || '',
    labelValue: options.labelValue || '',
    createdTime: options.createdTime || new Date().getTime(),
    //type: options.type || '0',
    menuCode: options.menuCode || '',
    //  menuToCode:options.menuToCode || '',
    duration: options.duration || 0,
    menuFromCode: options.menuFromCode || '',
    params: options.params || '',
    session: options.session || ''
  };
  rocNative.appBuryingPointEntrust(opt);
}

function getUrlParmByCode(paramList, token) {
  if (paramList.length <= 1) return `?token=${token}`;
  let dataStr = '', list = [];
  let str = paramList.length > 0 && paramList[0].value.indexOf('?') > -1 ? '&' : '?';

  for (let i = 1; i < paramList.length; i++) {
    list.push(paramList[i].key + '=' + encodeURI(paramList[i].value));
  }
  dataStr = list.join('&');
	s
  if (dataStr !== '') return `${str}${dataStr}&token=${token}`;
  return `${str}token=${token}`;
}

// 根据不同环境获取topic的URL
// export function getTopicUrl() {
//   return getConfigByEvtType('topicUrl')
// }




// // 获取WEB部署服务器域名地址


// export function getBaseMainUrl() {
//   return getConfigByEvtType('baseUrl');
// }

// 根据不同环境，生成URL