var lastWin;
if(typeof window=='undefined'){
  window={};
}
window.openWin=function(href,title,maxwidth,reload,maxheight){
  lastWin=onez.open('@'+href,'',{
    title:title,
    width:maxwidth,
    reload:'',
    height:maxheight
  });
};
window.closeWin=function(){
  layer.close(lastWin);
};
window.ONEZ=function(){
  var that=this;
  that.$=window.jQuery||layui.$;
  if(window.layui){
    that.each=window.layui.each;
    that.getStyle=window.layui.getStyle;
    that.img=window.layui.img;
    that.sort=window.layui.sort;
    that.url=window.layui.url;
    that.stope=window.layui.stope;
  }
  that.is_ios=function(){
    return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  };
  that.is_android=function(){
    var u = navigator.userAgent;
    return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
  };
  that.is_mobile=function(){
    if(window && $ && $(window).width()<750){
      return true;
    }
    return that.is_ios()||that.is_android();
  };
  that.is_weixin=function(){
    return navigator.userAgent.indexOf('MicroMessenger')>-1;
  };
  that.is_qq=function(){
    return navigator.userAgent.indexOf('QQ')>-1;
  };
  that.is_alipay=function(){
    return navigator.userAgent.indexOf('AlipayClient')>-1;
  };
  that.time = function() {
    return Math.floor((new Date()).getTime() / 1000);
  };
  that.loadingIndex;
  that.loading=function(bool){
    if(bool){
      if(!that.loadingIndex){
        that.loadingIndex=layer.load();
      }
    }else{
      if(that.loadingIndex){
        layer.close(that.loadingIndex);
        that.loadingIndex=null;
      }
    }
  };
  that.cache=function(key,value){
    if(typeof key=='undefined'){
      return'';
    }
    if(typeof value=='undefined'){
  		if(window.localStorage.getItem(key)!=null){
  			return window.localStorage.getItem(key);
  		}else{
        return'';
      }
    }else{
      window.localStorage.setItem(key,value);
    }
  };
  that.data_cache=function(key,value){
    if(that.noCache){
      return false;
    }
    if(typeof key=='undefined'){
      return false;
    }
    if(key.indexOf('noCache')!=-1){
      return false;
    }
    if(key.indexOf('?')!=-1){
      return false;
    }
    key=md5(key);
    if(typeof value=='undefined'){
  		var r=onez.cache(key);
      if(r.length>0){
        if(r.substr(0,1)=='['||r.substr(0,1)=='{'){
          return JSON.parse(r);
        }else{
          return r;
        }
      }
      return false;
    }else{
      if(typeof value=='object'){
        return onez.cache(key,JSON.stringify(value));
      }else{
        return onez.cache(key,value);
      }
    }
  };
  that.tpl='';
  that.ext='.php';
  Vue.prototype.onez = this;
  //官方文档
  that.document=function(title){
    that.open('onez-page-onez-view',{
      width:960,
      height:600,
      title:title,
      urlAdd:{
        key:'/document/'+title
      }
    });
  };
  that.location=function(action){
    that.onEvent({token:'page',action:action});
  };
  //是否当前页
  that.curPage=function(item){
    if(!item||!item.href){
      return false;
    }
    if(item.path){
      if(that.vue.action.indexOf(item.path)==0 || that.vue.action.indexOf(':'+item.path)!=-1){
        return true;
      }
    }
    if(that.ext!='.php'){
      item.href=item.href.replace('.php',that.ext);
    }
    return that.vue.action.indexOf(item.href)==0;
  };
  //获取变量
  that.get=function($data,key){
    if($data){
      return $data[key];
    }
  };
  //
  //获取变量
  that.tip=function(text){
    return layer.msg(text);
  };
  //
  that.alert=function(text,func){
    layer.alert(text,function(index){
      onez.backs=null;
      layer.close(index);
      if(typeof func=='function'){
        func();
      }
    },{title:'系统提示'});
    onez.backs=layer.closeAll;
  };
  that.confirm=function(text,func){
    layer.confirm(text, {icon: 3, title:'系统提示'}, function(index){
      layer.close(index);
      func();
    });
  };
  that.replaces=function(action){
    action=action.replace('$bp.','bs.plugins.');
    return action;
  };
  //事件处理
  that.onEvent=function(event,vue){
    if(event.token=='page'){
      var action=event.action;
      if(that.ext!='.php'){
        action=action.replace('.php',that.ext);
      }
      if(action.substr(0,5)=='#http'){
        action=action.substr(1);
      }
      if(action.indexOf('#')===0){
        if(action=='#'){
          return;
        }
        action=action.substr(1);
      }
      if(action.indexOf('javascript:')===0){
        return;
      }
      if(action.substr(0,4)=='http'){
        if(event.target&&event.target=='_blank'){
          window.open(action,'','');
        }else{
          location.href=action;
        }
        return;
      }
      if(action.substr(0,1)=='@'){
        location.href=action.substr(1);
        return;
      }
      if(action.substr(0,2)=='./'){
        var o=vue.$root.action.split('/');
        o[o.length-1]=action.substr(2);
        action=o.join('/');
      }
      event.option=event.option||{};
      event.option.action=that.replaces(action);
      event.option.urlAdd=event.option.urlAdd||{};
      if(event.args){
        that.objWithArgs(event.option,event.args);
        delete event.args;
      }
      if(action.indexOf('?')!=-1){
        var o=action.split('?');
        action=o[0];
        that.objWithArgs(event.option.urlAdd,o[1]);
      }else if(action.indexOf('&')!=-1){
        var s=action.substr(0,action.indexOf('&'));
        that.objWithArgs(event.option.urlAdd,action.substr(action,s.length));
        action=s;
      }
      if(event.option.width){
        that.open('onez-page-'+that.hrefToPageKey(action),event.option,vue);
        return;
      }
      var urlAdd=[];
      for(var k in event.option.urlAdd){
        urlAdd.push(k+'='+event.option.urlAdd[k]);
      }
      if(urlAdd.length>0){
        action+='?'+urlAdd.join('&');
      }
      that.run(action);
    }else if(event.token=='open'){
      window.open(event.action,'','');
    }else if(event.token=='location'){
      location.href=event.action;
    }else if(event.token=='remote'){
      if(event.confirm){
        that.confirm(event.confirm,function(){
          that.remote(event,vue);
        });
      }else{
        that.remote(event,vue);
      }
    }else if(event.token=='api'){
      return that.api(vue,event.action,event.option);
    }
  };
  that.objWithArgs=function(obj,args){
    obj=obj||{};
    if(args){
      var strs=args.split("&");
      for(var i=0;i<strs.length;i++) {
        var o=strs[i].split("=");
        if(o.length>=2){
          obj[o[0]]=o[1];
        }
      }
    }
  };
  that.remote=function(opt,vue){
    var vue=vue||that.vue;
    var opt=opt.postdata||{};
    opt['$action']=vue.$root.action;
    opt['$file']=vue.$root.path;
    that.post(opt,(data)=>{
      //console.log(data);
      if(data.error){
        that.alert(data.error);
      }
      if(data.message){
        if(data.goto){
          that.alert(data.message,()=>{
            that.doit(data,vue);
          });
        }else{
          that.alert(data.message);
        }
      }else{
        if(data.goto){
          that.doit(data,vue);
        }
      }
    });
  };
  that.api=function(vue,name,req){
    return new Promise((resolve, reject) => {
      var funcName=name;
      var ptoken='';
      if(funcName.indexOf(':')!=-1){
        var o=funcName.split(':');
        ptoken=o[0];
        funcName=o[1];
      }
      if(typeof that[funcName]=='undefined'){
        that.post({
          $action:vue.$root.action,
          $file:vue.$root.path,
          action:'$api',
          ptoken:ptoken,
          funcName:funcName
        },function(data){
          if(data.res){
            that.loadRes(vue,data.res,function(){
              console.log('onez.api',funcName,typeof that[funcName]);
              if(typeof that[funcName]=='function'){
                that[funcName](vue,req).then(resolve);
              }else{
                setTimeout(()=>{
                  if(typeof that[funcName]=='function'){
                    that[funcName](vue,req).then(resolve);
                  }
                },100);
              }
            });
          }else{
            console.warn(name,'api not exists');
            resolve([false,'api not exists']);
          }
        });
      }else{
        that[funcName](vue,req).then(resolve);
      }
    });
  };
  that.clouds={};
  that.cloud=function(name,el,args){
    if(typeof name=='object'){
      if(name.js){
        if(!name.jsUrl || name.jsUrl.length<1){
          eval(name.js);
        }else{
          if(typeof name.jsUrl=='string'){
            name.jsUrl=name.jsUrl.split('|');
          }
          that.loadJS(name.jsUrl,function(){
            eval(name.js);
          });
        }
      }
      return;
    }
    var vue=that.vue;
    if(typeof that.clouds[name]!='undefined'){
      that.cloud(that.clouds[name],el,args);
      return;
    }
    that.post({
      $action:vue.$root.action,
      $file:vue.$root.path,
      action:'$cloud',
      name:name
    },function(data){
      that.clouds[name]=data;
      that.cloud(that.clouds[name],el,args);
    });
  };
  that.loadJS=function(urls,callback){
    if(urls.length<1){
      if(typeof callback=='function'){
        callback();
      }
    }else{
      var url=urls.shift();
      var script = document.createElement('script');
      script.id = 'res-'+md5(url);
      script.type = 'text/javascript';
      script.onload = ()=>{
        this.loadJS(urls,callback);
      };
      script.src = url;
      document.getElementsByTagName('body')[0].appendChild(script);
    }
  };
  that.loadRes=function(vue,arr,callback){
    var jsUrl=[];
    for(var i=0;i<arr.length;i++){
      var url=arr[i];
      if(url.substr(0,2)=='./'){
        var o=vue.path.split('/');
        o[o.length-1]=url.substr(2);
        url=o.join('/');
      }
      var type='';
      var idName='res-'+md5(url);
      if(onez.$('#'+idName).length>0){
        continue;
      }
      if(url.indexOf('.js')!=-1){
        type='js';
      }else if(url.indexOf('.css')!=-1){
        type='css';
      }
      if(type=='js'){
        jsUrl.push(url);
      }else if(type=='css'){
        $('<link rel="stylesheet" id="'+idName+'" href="'+url+'" />').appendTo('head');
      }
    }
    if(jsUrl.length<1){
      if(typeof callback==='function'){
        callback();
      }
    }else{
      this.loadJS(jsUrl,callback);
    }
  };
  //
  that.doit=function(data,vue){
    var vue=vue||that.vue;
    if(vue.$root.winType!='win'){
      location.reload();
      return
    }
    if(data.goto=='close'){
      vue.$root.close();
    }else if(data.goto=='reload'){
      vue.$root.$emit('update');
      vue.$root.close();
    }else if(data.goto=='reload2'){
      onez.vue.reload();
      vue.$root.close();
    }
  };
  //重写a标签
  that.link=function(e,vue){
    var target=e.currentTarget||e.target;
    target=target||e;
    var href=target.getAttribute("data-href");
    if(!href){
      href=target.getAttribute("href");
    }
    if(!href){
      return;
    }
    var _target=target.getAttribute("target");
    if(_target&&_target=='_blank'){
      window.open(href,'_blank','');
      return;
    }
    return that.onEvent({
      token:'page',
      action:href,
      args:target.getAttribute("args"),
      target:target.getAttribute("target"),
      title:target.innerText
    },vue);
  };
  //弹出新窗口
  that.openVues=[];
  that.open=function(action,opt,parent){
    var opt=opt||{};
    if(action.substr(0,1)=='@'){
      opt.type=2;
      return that.win(action.substr(1),opt);
    }
    var urlAdd='';
    if(opt.urlAdd){
      for(var k in opt.urlAdd){
        urlAdd+='&'+k+'='+opt.urlAdd[k];
      }
    }
    //console.log(args);
    var id='div'+(''+Math.random()).split('.')[1];
    var vueTpl='<'+action+' url-add="'+urlAdd+'" />';
    if(typeof(Vue.component(action))!=='function'){
      vueTpl='<onez-cloud _name="'+action+'" _action="'+opt.action+'" url-add="'+urlAdd+'" />';
    }
    var div=layui.$('<div id="'+id+'">'+vueTpl+'</div>').appendTo('body');
    var vm=new Vue({
      data(){
        return {
          winType:'win',
          id:id,
          parent:parent,
          action:opt.action,
          layerIndex:0
        }
      },
      methods:{
        resize(){
          layer.style(this.layerIndex, {
            width: '1000px',
            top: '10px'
          });
        },
        close(){
          layer.close(this.layerIndex);
        },
        autoResize(){
          if(opt.auto_resize){
            this.$nextTick(()=>{
              setTimeout(()=>{
                var obj=$(this.$el).find('>*');
                var width=obj.outerWidth();
                var height=obj.outerHeight();
                height=Math.min(height,$(window).height()*0.8);
                height=Math.max(height,200);
                layer.style(this.layerIndex, {
                  height: height+70+'px'
                });
              },100);
            });
          }
        }
      },
      updated(){
        this.autoResize();
      },
      created(){
        this.layerIndex=that.win(div,opt,this,id);
      },
      mounted(){
        that.openVues.push(this);
        this.autoResize();
      },
      destroyed(){
        for(var i=that.openVues.length-1;i>=0;i--){
          if(that.openVues[i].id==id){
            that.openVues.splice(i,1);
          }
        }
      },
      el:'#'+id
    });
    
  };
  that.win=function(div,opt,vm,id){
    var title=opt.title||'系统提示';
    var width=opt.width||'960';
    var height=opt.height||'600';
    if(typeof $!='undefined' && typeof window!='undefined'){
      height=Math.min(height,$(window).height()*0.9)||600;
    }
    var dlg={
      type: opt.type||1
      ,title: title
      ,skin: 'pop-win '+opt.classname
      ,content: div
      ,area: height?[width+'px',height+'px']:(width+'px')
      ,shade: 0
      ,zIndex: layer.zIndex
      ,success: function(layero){
        //layer.setTop(layero);
      }
      ,end:function(){
        layui.$('#'+id).remove();
        if(vm){
          vm.$destroy();
        }
      }
    };
    if(opt.noTitle){
      dlg.title=false;
      dlg.closeBtn=0;
      dlg.move='.onez-win-title';
    }
    if(opt.maxmin){
      dlg.maxmin=true;
    }
    if(opt.noScroll){
      dlg.scrollbar=false;
    }
    if(opt.shade){
      dlg.shade=[0.01,'#000000'];
      dlg.shadeClose=opt.shadeClose||false;
      dlg.isOutAnim=false;
    }
    if(opt.dlgId){
      dlg.id=opt.dlgId;
    }
    if(opt.auto){
      if(opt.width){
        dlg.area=opt.width+'px';
      }else{
        dlg.area='auto';
      }
    }
    if(opt.other){
      for(var k in opt.other){
        dlg[k]=opt.other[k];
      }
    }
    if(opt.pos){
      if(opt.pos=='mouse'){
        if(window.event){
          dlg.offset=[window.event.pageY+'px',window.event.pageX+'px'];
        }
      }
    }
    return layer.open(dlg);
  };
  //刷新页面
  that.getUrl=function(add){
    var action=that.vue.action,opt={};
    var opt={};
    if(action.indexOf('?')!=-1){
      var strs=action.substr(action.indexOf('?')+1).split("&");
      action=action.split('?')[0];
      for(var i=0;i<strs.length;i++) {
        opt[strs[i].split("=")[0]]=strs[i].split("=")[1];
      }
    }
    opt=Object.assign(opt,add);
    var args='';
    for(var k in opt){
      args+='&'+k+'='+opt[k];
    }
    if(args.length>0){
      action+='?'+args.substr(1);
    }
    return action;
  },
  //异步获取远程数据
  that.data=function(vue,keys){
    window.caches=window.caches||{};
    if(typeof keys=='string'){
      keys=keys.split(',');
    }
    var keys2=[];
    for(var i=0;i<keys.length;i++){
      var f=keys[i].substr(0,1);
      if(f=='@'){
        keys2.push(keys[i].substr(1));
        if(window.caches[keys2[i]]){
          Vue.set(vue,keys2[i],window.caches[keys2[i]]);
        }
      }else if(f=='+'){
        keys2.push(keys[i].substr(1));
      }else{
        keys2.push(keys[i]);
      }
      var key=vue.path+'\t'+keys2[i];
      var cache=that.data_cache(key);
      if(cache){
        Vue.set(vue,keys2[i],cache);
      }
    }
    var loadIndex=layer.load();
    setTimeout(()=>{
      layer.close(loadIndex);
    },2000);
    var action=vue.$root.action+'';
    if(vue.urlAdd){
      if(action.indexOf('?')==-1){
        action+='?'+vue.urlAdd;
      }else{
        action+='&'+vue.urlAdd;
      }
    }
    that.post({
      $action:action,
      $file:vue.path,
      action:'data',
      keys:keys2
    },function(data){
      for(var i=0;i<keys.length;i++){
        var f=keys[i].substr(0,1);
        if(f=='@'){
          window.caches[keys2[i]]=data[keys2[i]];
        }else if(f=='+'){
          if(vue.data){
            data[keys2[i]]=Object.assign(data[keys2[i]],vue.data);
          }
        }
        Vue.set(vue,keys2[i],data[keys2[i]]);
        var key=vue.path+'\t'+keys2[i];
        that.data_cache(key,data[keys2[i]]);
      }
      layer.close(loadIndex);
    });
  },
  that.postList={};
  that.postIng=false;
  that.post=function(postdata,callback){
    that.postList[Math.random()+'']=[postdata,callback];
    that.postOnce();
  };
  that.postOnce=function(){
    if(that.postIng){
      return;
    }
    that.postIng=true;
    setTimeout(function(){
      var postdatas={};
      for(var k in that.postList){
        postdatas[k]=that.postList[k][0];
      }
      axios.post(window.location.href,{action:'$post',req:postdatas}).then(function (response) {
        if(response.data){
          if(response.data.error){
            onez.alert(response.data.error);
            return;
          }else if(response.data.location){
            location.href=response.data.location;
          }else if(response.data.results){
            for(var k in response.data.results){
              if(that.postList[k]){
                try{
                  that.postList[k][1](response.data.results[k]);
                }catch(e){
                  console.log(e);
                }
                delete that.postList[k];
                delete postdatas[k];
              }
            }
          }
        }
        for(var k in postdatas){
          that.postList[k][1]({status:'error',error:'no data'});
          delete that.postList[k];
          delete postdatas[k];
        }
        that.postIng=false;
        for(var k in that.postList){
          setTimeout(that.postOnce,100);
          break;
        }
      }).catch(function (error) {
        for(var k in postdatas){
          that.postList[k][1]({status:'error',error:error});
          delete that.postList[k];
          delete postdatas[k];
        }
        that.postIng=false;
        for(var k in that.postList){
          setTimeout(that.postOnce,100);
          break;
        }
      });
    },100);
  };
  //读取、修改网址中的hash
  that.hashObj={};
  that.hash=function(key,value){
    if(typeof value=='undefined'){
      var hash=location.hash;
      if(hash.length>1 && hash.substr(0,1)=='#'){
        var o=hash.substr(1).split('|');
        that.hashObj.action=o[0];
        for(var i=1;i<o.length-1;i+=2){
          that.hashObj[o[i]]=o[i+1];
        }
      }
      that.hashObj.action=that.hashObj.action||'/index'+that.ext;
      return that.hashObj[key]||'';
    }else{
      that.hashObj[key]=value;
      var hash=that.hashObj.action||'/index'+that.ext;
      if(key!='action'){
        for(var k in that.hashObj){
          if(k!='action' && that.hashObj[k]){
            hash+='|'+k+'|'+that.hashObj[k];
          }
        }
      }
      location.hash=hash;
    }
  };
  this.hrefToPageKey=function(href){
    var pageKey=href;
    if(that.ext.length>0){
      if(pageKey.indexOf(that.ext)!=-1){
        pageKey=pageKey.split(that.ext)[0];
      }
    }
    if(pageKey.indexOf('?')!=-1){
      pageKey=pageKey.split('?')[0];
    }
    if(pageKey.substr(0,1)=='/'){
      pageKey=pageKey.substr(1);
    }
    pageKey=pageKey.replace(/[^0-9a-zA-Z\-\_]/g,'-');
    //console.log(pageKey);
    return pageKey;
  }
  //渲染vue
  this.run=function(action){
    var action=action||that.hash('action');
    var action=action||'/index'+that.ext;
    if(action.indexOf('javascript')!=-1 || action=='' || action=='#'){
      return;
    }
    if(that.vue){
      that.vue.$destroy();
    }
    var pageKey=that.hrefToPageKey(action);
    if(typeof(Vue.component('onez-page-'+pageKey))!=='function'){
      if(typeof that.onErrorPage=='function'){
        var r=that.onErrorPage(action);
        if(r===false){
          return;
        }
      }
      Vue.component('onez-page-'+pageKey,{
        props:['urlAdd'],
        template:'<div><onez-cloud _name="onez-page-cloud-'+pageKey+'" _action="'+that.replaces(action)+'" :url-add="urlAdd" /></div>'
      });
    }
    if(that.tpl){
      document.getElementById('app').innerHTML='<onez-'+that.tpl+' tpl="onez-page-'+pageKey+'" />';
    }else{
      document.getElementById('app').innerHTML='<onez-page-'+pageKey+' />';
    }
    that.hash('action',action);
    that.vue=new Vue({
      el:'#app',
      data(){
        return {
          action:action
        }
      },
      methods:{
        reload(add){
          if(typeof add=='object'){
            this.action=that.getUrl(add);
          }else if(typeof add=='string'){
            this.action=add;
          }
          that.run(this.action);
        }
      }
    });
    layer.closeAll();
  };
  var innerDocClick;
  document.addEventListener('mouseleave',function(){
    innerDocClick=false;
  });
  document.addEventListener('mousemove',function(){
    innerDocClick=true;
  });
  window.onhashchange=function(){
    //if(!innerDocClick){
      that.run(that.hash('action'));
    //}
  }
};
ONEZ.prototype.fn=ONEZ.prototype;
var onez=new ONEZ;