//form js
export default{
  data(){
    return {
      tmpId:(''+Math.random()).split('.')[1]
    };
  },
  watch:{
    data(){
      this.init();
    }
  },
  mounted(){
    //onez.data(this,['items']);
    this.init();
  },
  methods:{
    init(){
      if(this.data && this.data.js && this.data.js.length>0){
        this.$nextTick(()=>{
          if(this.data.jsBefore){
            eval(this.data.jsBefore);
          }
          if(this.data.jsUrl && this.data.jsUrl.length>0){
            this.loadJS(this.data.jsUrl);
          }else{
            this.runJS();
          }
        });
      }
    },
    loadJS(urls){
      if(urls.length<1){
        this.runJS();
      }else{
        var url=urls.shift();
        $.getScript(url,()=>{
          this.loadJS(urls);
        });
      }
    },
    runJS(){
      var that=this;
      var code=this.data.js;
      code=code.replace('onez.formpost','that.formpost');
      setTimeout(()=>{
        eval(code);
      });
    },
    formpost(form){
      var o = {};
      var a = $(form).serializeArray();
      $.each(a, function() {
        if (o[this.name] !== undefined) {
          if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
          }
          o[this.name].push(this.value || '');
        } else {
          o[this.name] = this.value || '';
        }
      });
      try{
        var _vue=this;
        while(true){
          if(typeof _vue.onSubmit=='function'){
            return _vue.onSubmit(o,this);
          }
          _vue=_vue.$parent;
          if(!_vue||_vue===this.$root){
            break;
          }
        }
      }catch(e){
        console.log(e);
      }
      o['action']='data';
      o['$action']=this.$root.action;
      o['$file']=this.$root.path;
      onez.post(o,(data)=>{
        console.log(data);
        if(data.error){
          onez.alert(data.error);
        }
        if(data.message){
          if(data.goto){
            onez.alert(data.message,()=>{
              this.doit(data);
            });
          }else{
            onez.alert(data.message);
          }
        }else{
          if(data.goto){
            this.doit(data);
          }
        }
      });
    },
    doit(data){
      if(data.goto=='close'){
      }else if(data.goto=='reload'){
        this.$root.$emit('update');
      }else if(data.goto=='reload2'){
        onez.vue.reload();
      }
      if(this.$root.close){
        this.$root.close();
      }
    }
  }
}
