import axios from "axios";
import { divide } from "lodash";

export default {
  data() {
    return {
      fields: {},
      errors: {},
      loaded: true,
      action: '',
      is_update: '',
      modal:''
    }
  },
  mounted: function(e) { 
    const _this = this;
    $(document).on('draw.dt',function(e){
      _this.$root.load = false;
      $('.edit-link').click(function(e){
        e.preventDefault();
        _this.edit($(this).attr('href'));
        if(_this.modal) $("#"+_this.modal).modal('show');
      });
    });
    jQuery("[required]").parent().addClass('required');
  },
  methods: {
    create(){
      this.fields = {status:true}; //Clear input fields.
      this.action_update = '';
      if(this.modal) $("#"+this.modal).modal('show');
    },
    save(){
      this.submit();
      if(this.modal) $("#"+this.modal).modal('hide');
    },
    submit() {
      if (this.loaded) {
        this.loaded = false;
        this.errors = {};
        const request = this.action_update?axios.put(this.action_update, this.fields):axios.post(this.action, this.fields)
        request.then(response => {
          this.success();
          this.fields = {status: true}; //Clear input fields.
          this.loaded = true;
          this.reload();
          if(this.action_update){
            this.action_update = '';
            if(this.modal) $("#"+this.modal).modal('hide');
          }
        }).catch(error => {
          this.loaded = true;
          if (error.response.status === 422) {
            this.errors = error.response.data.errors || {};
          }
          this.error(error);
        });
      }
    },
    edit(href){
      axios.get(href)
      .then(res=>{
        this.action_update = href;
        this.fields = res.data;
      });
    }

  },
}