import store from '../store/index';

/*
* 跨平台通用获取参数方法
* 先从url,再从store和storage拿,最后调取原生的方法获取
* @param {key}          String   @des{需要获取的值}
* @param {namespace}    String   @des{store命名空间}
* @param {fnName}       String   @des{原生方法名称}
* @param {param}        Object   @des{传递原生的参数}
* */
export const getParamCommon = (key,namespace='user',fnName,param)=>{

  return new Promise((resolve,reject)=>{
    //url参数解析
    let queryArr = window.location.href.split('?')[1].split('&');
    let obj = {};
    queryArr.forEach((item)=>{
      obj[item.split('=')[0]] = item.split('=')[1]
    })
    //url中存在
    if(key && obj[key]){
      resolve(obj[key]);
      return;
    }
    //store中存在；
    if(!!store.state[namespace][key]){
      resolve(store.state[namespace][key]);
      return;
    }
    //session
    if(!!sessionStorage.getItem(key)){
      let res = sessionStorage.getItem(key).includes('{') && typeof sessionStorage.getItem(key)=== "string" ?JSON.parse(sessionStorage.getItem(key)):sessionStorage.getItem(key);
      resolve(res);
      return;
    }
    //local
    if(!!localStorage.getItem(key)){
      let res = localStorage.getItem(key).includes('{') && typeof localStorage.getItem(key)=== "string" ?JSON.parse(localStorage.getItem(key)):localStorage.getItem(key);
      resolve(res);
      return;
    }
    //app
    if(navigator.userAgent.indexOf('yocaigs') !== -1 || (obj.type && obj.type == 2)){
      let isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if(isIOS){
        if(param && typeof param === 'object'){
          let issur = Object.assign({},param,{'callback':`${fnName}Callback`})
        }
        window.webkit.messageHandlers[fnName].postMessage(JSON.stringify(issur));
        window[`${fnName}Callback`] = function (val) {
          resolve(val)
        }
      }else {
        let res = JSObj[fnName](JSON.stringify(param));
        resolve(res)
      }
    }else {
      resolve()
    }
  })
}

/*
* 设置参数到store(此方法在mutations中使用)
* 先存到store中,再存入store或者storage中
* @param {key}          String   @des{需要设置的键}
* @param {val}          String   @des{需要设置的值}
* @param {isSave}       Bollen   @des{是否需要存储}
* @param {type}         Number   @des{存储在哪里，1：sessition;2：local}
* */
export const setParam = (state,key,val,isSave=false,type=1)=>{
  state[key] = val;
  if(isSave){
    if(type === 1){
      sessionStorage.setItem(key,JSON.stringify(val));
    }else if(type === 2){
      localStorage.setItem(key,JSON.stringify(val));
    }
  }
}