<template>
  <v-layout v-if="this.formState.ready">
    <v-flex>
      <v-form ref="form">
        <v-layout align-center justify-left row wrap>
          <v-flex xs12 mt-1 mb-2>
            <v-alert
              ref="errorbox"
              v-show="formState.errorBoxMessage"
              color="error"
              icon="fa-exclamation-circle "
              value="true"
              transition="scale-transition"
              class="multi-line"
              outline
            >{{formState.errorBoxMessage}}</v-alert>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.name"
              clearable
              @click:clear="onChange('name')"
              :counter="255"
              :label="this.$gzlocale.get('WidgetName')"
              :rules="[this.$gzform.max255(this,'name'),this.$gzform.required(this,'name')]"
              :error-messages="this.$gzform.serverErrors(this,'name')"
              ref="name"
              @change="onChange('name')"
            ></v-text-field>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.serial"
              clearable
              @click:clear="onChange('serial')"
              :counter="10"
              :label="this.$gzlocale.get('WidgetSerial')"
              :rules="[this.$gzform.maxLength(this,'serial',10)]"
              :error-messages="this.$gzform.serverErrors(this,'serial')"
              ref="serial"
              @change="onChange('serial')"
            ></v-text-field>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.count"
              clearable
              @click:clear="onChange('count')"
              :counter="10"
              :label="this.$gzlocale.get('WidgetCount')"
              ref="count"
              :rules="[this.$gzform.integerValid(this,'count'),this.$gzform.required(this,'count')]"
              :error-messages="this.$gzform.serverErrors(this,'count')"
              required
              @change="onChange('count')"
              type="number"
            ></v-text-field>
          </v-flex>

          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.dollarAmount"
              :prefix="this.$gzlocale.formats.currencySymbol"
              :label="this.$gzlocale.get('WidgetDollarAmount')"
              ref="dollarAmount"
              required
              :rules="[this.$gzform.decimalValid(this,'dollarAmount'),this.$gzform.required(this,'dollarAmount')]"
              :error-messages="this.$gzform.serverErrors(this,'dollarAmount')"
              @change="onChange('dollarAmount')"
              type="number"
            ></v-text-field>
          </v-flex>

          <v-flex xs12 sm6 lg4 xl3 px-2>
            <gz-date-time-picker
              :label="this.$gzlocale.get('WidgetStartDate')"
              v-model="obj.startDate"
              ref="startDate"
              :error-messages="this.$gzform.serverErrors(this,'startDate')"
              @change="onChange('startDate')"
            ></gz-date-time-picker>
          </v-flex>

          <v-flex xs12 sm6 lg4 xl3 px-2>
            <gz-date-time-picker
              :label="this.$gzlocale.get('WidgetEndDate')"
              :rules="[this.$gzform.datePrecedence(this,'startDate','endDate')]"
              :error-messages="this.$gzform.serverErrors(this,'endDate')"
              v-model="obj.endDate"
              ref="endDate"
              @change="onChange('endDate')"
            ></gz-date-time-picker>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-checkbox
              v-model="obj.active"
              :label="this.$gzlocale.get('Active')"
              ref="active"
              :error-messages="this.$gzform.serverErrors(this,'active')"
              required
              @change="onChange('active')"
            ></v-checkbox>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.roles"
              :label="this.$gzlocale.get('WidgetRoles')"
              ref="roles"
              :rules="[this.$gzform.integerValid(this,'roles'),this.$gzform.required(this,'roles')]"
              :error-messages="this.$gzform.serverErrors(this,'roles')"
              required
              @change="onChange('roles')"
              type="number"
            ></v-text-field>
          </v-flex>
        </v-layout>

        <v-layout align-left justify-center row wrap mt-5>
          <v-flex xs6 sm4>
            READY: {{formState.ready}}
            <br>
            LOADING: {{formState.loading}}
            <br>
            DIRTY: {{formState.dirty}}
            <br>
            VALID: {{formState.valid}}
            <br>
            READONLY: {{formState.readOnly}}
            <br>
          </v-flex>
        </v-layout>
        <!-- <v-layout align-left justify-center row wrap mt-5>
          <v-flex xs6 sm4>
            <v-btn small @click="remove">{{ this.$gzlocale.get("Delete")}}</v-btn>
          </v-flex>
          <v-flex xs6 sm4>
            <v-btn small @click="stubTestClick">TEST BUTTON</v-btn>
          </v-flex>
          <v-flex xs6 sm4>
            <v-btn small @click="submit">{{ this.$gzlocale.get("Save")}}</v-btn>
          </v-flex>
        </v-layout>-->
      </v-form>
    </v-flex>
  </v-layout>
</template>

<script>
/*  Xeslint-disable    */

function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  var m = this.$gzmenu.parseMenuItem(menuItem);
  if (m.owner == "inventory-widget-edit" && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      default:
        alert("inventory-widget-edit.vue::context click: [" + m.key + "]");
    }
  }
}

export default {
  beforeCreate() {
    //Cache all required lt keys
    var ltKeysRequired = [
      "Widget",
      "WidgetName",
      "WidgetSerial",
      "WidgetDollarAmount",
      "WidgetCount",
      "WidgetRoles",
      "WidgetStartDate",
      "WidgetEndDate",
      "WidgetNotes",
      "WidgetCustom1",
      "WidgetCustom2",
      "WidgetCustom3",
      "WidgetCustom4",
      "WidgetCustom5",
      "WidgetCustom6",
      "WidgetCustom7",
      "WidgetCustom8",
      "WidgetCustom9",
      "WidgetCustom10",
      "WidgetCustom11",
      "WidgetCustom12",
      "WidgetCustom13",
      "WidgetCustom14",
      "WidgetCustom15",
      "WidgetCustom16"
    ];
    var vm = this;
    this.$gzlocale
      .fetch(ltKeysRequired)
      .then(() => (this.formState.ready = true))
      .catch(err => {
        this.formState.ready = true;
        vm.$gzHandleFormError(err);
      });
  },
  created() {
    this.$gzevent.$emit("menu-change", {
      isMain: false,
      icon: "fa-splotch",
      title: this.$gzlocale.get("Widget"),
      helpUrl: "intro/#searching",

      menuItems: [
        {
          title: this.$gzlocale.get("Save"),
          icon: "save",
          surface: true,
          key: "inventory-widget-edit:save",
          vm: this
        },
        {
          title: this.$gzlocale.get("Delete"),
          icon: "trash-alt",
          surface: true,
          key: "inventory-widget-edit:delete",
          vm: this
        },
        { divider: true, inset: false },
        {
          title: this.$gzlocale.get("Duplicate"),
          icon: "clone",
          key: "inventory-widget-edit:duplicate",
          vm: this
        }
      ]
    });

    this.$gzevent.$on("menu-click", clickHandler);
    this.getDataFromApi();
  },
  beforeDestroy() {
    this.$gzevent.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      obj: {},
      serverError: {},

      appError: null,
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null
      }
    };
  },
  // ,
  // watch: {
  //   canSave: {
  //     // xeslint-disable-next-line
  //     handler: function(newState) {
  //       this.$gzevent.$emit(
  //         "menu-replace-item",
  //         "inventory-widget-edit:save",
  //         newState
  //       );
  //       //todo: change the save button state here
  //       //console.log("Valid CHANGED, was " + oldObj + " Now is " + newObj);
  //     }
  //   }
  // },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  methods: {
    onChange(ref) {
      if (!this.formState.loading) {
        this.$gzform.onChange(this, ref);
      }
    },
    getDataFromApi() {
      this.formState.loading = true;
      var url = "Widget/" + this.$route.params.id;
      var vm = this;
      this.$gzform.deleteAllErrorBoxErrors(this);
      this.$gzapi
        .get(url)
        .then(res => {
          if (res.error) {
            vm.serverError = res.error;
            vm.$gzform.setErrorBoxErrors(vm);
          } else {
            vm.obj = res.data;
            //Update the form status
            vm.$gzform.setFormState({
              vm: vm,
              dirty: false,
              valid: true,
              loading: false
            });
          }
        })
        .catch(function handleGetDataFromAPIError(error) {
          //Update the form status
          vm.$gzform.setFormState({
            vm: vm,
            loading: false
          });
          vm.$gzHandleFormError(error, vm);
        });
    },
    submit() {
      if (this.canSave) {
        this.formState.loading = true;
        var vm = this;
        var url = "Widget/" + this.$route.params.id;

        //clear any errors vm might be around from previous submit
        this.$gzform.deleteAllErrorBoxErrors(this);

        this.$gzapi
          .upsert(url, this.obj)
          .then(res => {
            this.formState.loading = false;
            if (res.error) {
              vm.serverError = res.error;
              vm.$gzform.setErrorBoxErrors(vm);
            } else {
              vm.$gzform.setFormState({
                vm: vm,
                dirty: false
              });

              //Logic for detecting if a post or put: if id then it was a post, if no id then it was a put
              if (res.id) {
                //Handle "post" of new record
                vm.obj = res.data;
              } else {
                //Handle "put" of an existing record
                vm.obj.concurrencyToken = res.data.concurrencyToken;
              }
            }
          })
          .catch(function handleSubmitError(error) {
            vm.formState.loading = false;
            vm.$gzHandleFormError(error, vm);
          });
      }
    },
    remove() {
      //check rights
      //do the delete
      alert("STUB: DELETE");
    },
    duplicate() {
      //only if not dirty
      //check rights
      //duplicate
      //navigate to new record
      alert("STUB: DUPLICATE");
    },
    stubTestClick() {
      this.$gzevent.$emit("menu-replace-item", {
        title: this.$gzlocale.get("Save"),
        surface: true,
        icon: "save",
        color: "error",
        disabled: true,
        key: "inventory-widget-edit:save"
      });
      // alert("stub test click");
    }
  }
};
</script>

<style>
</style>

/*
Sample widget record api v8
{
  "data": {
    "id": 100,
    "concurrencyToken": 2675248,
    "ownerId": 1,
    "name": "Fantastic Wooden Chips 122",
    "serial": 100,
    "dollarAmount": 584.83,
    "active": true,
    "roles": 8212,
    "startDate": "2019-02-12T10:12:39.594206",
    "endDate": "2019-02-12T13:40:59.986405",
    "notes": "Eum optio incidunt blanditiis laboriosam. Sed ipsam occaecati minus corrupti repudiandae delectus. Culpa nostrum est ullam assumenda animi ut. Velit sunt ex ipsum. Temporibus cum quaerat at omnis at quas. Commodi dolor molestiae beatae.",
    "count": 0,
    "customFields": null,
    "tags": [
      "brown",
      "red"
    ]
  }
}

IN JS FORMAT
{
  data: {
    id: 100,
    concurrencyToken: 2675248,
    ownerId: 1,
    name: 'Fantastic Wooden Chips 122',
    serial: 100,
    dollarAmount: 584.83,
    active: true,
    roles: 8212,
    startDate: '2019-02-12T10:12:39.594206',
    endDate: '2019-02-12T13:40:59.986405',
    notes: 'Eum optio incidunt blanditiis laboriosam. Sed ipsam occaecati minus corrupti repudiandae delectus. Culpa nostrum est ullam assumenda animi ut. Velit sunt ex ipsum. Temporibus cum quaerat at omnis at quas. Commodi dolor molestiae beatae.',
    count: 0,
    customFields: null,
    tags: [
      'brown',
      'red'
    ]
  }
}
*/
