<template>
  <v-layout v-if="this.formReady">
    <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="errorBoxMessage"
              color="error"
              icon="fa-exclamation-circle "
              value="true"
              transition="scale-transition"
              class="multi-line"
              outline
            >{{errorBoxMessage}}</v-alert>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.name"
              clearable
              :counter="255"
              :label="this.$gzlocale.get('WidgetName')"
              :rules="[this.$gzv.max255(this,'name'),this.$gzv.required(this,'name')]"
              :error-messages="this.$gzv.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
              :counter="10"
              :label="this.$gzlocale.get('WidgetSerial')"
              :rules="[this.$gzv.maxLength(this,'serial',10)]"
              :error-messages="this.$gzv.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
              :counter="10"
              :label="this.$gzlocale.get('WidgetCount')"
              ref="count"
              :rules="[this.$gzv.integerValid(this,'count'),this.$gzv.required(this,'count')]"
              :error-messages="this.$gzv.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.$gzv.decimalValid(this,'dollarAmount'),this.$gzv.required(this,'dollarAmount')]"
              :error-messages="this.$gzv.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.$gzv.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.$gzv.datePrecedence(this,'startDate','endDate')]"
              :error-messages="this.$gzv.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.$gzv.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.$gzv.integerValid(this,'roles'),this.$gzv.required(this,'roles')]"
              :error-messages="this.$gzv.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>
            <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.formReady = true))
      .catch(err => {
        this.formReady = 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: {},
      errorBoxMessage: null,
      appError: null,
      formReady: false
    };
  },
  methods: {
    onChange(ref) {
      this.$gzv.onChange(this, ref);
    },
    getDataFromApi() {
      var url = "Widget/" + this.$route.params.id;
      var vm = this;
      this.$gzv.deleteAllErrorBoxErrors(this);
      this.$gzapi
        .get(url)
        .then(res => {
          if (res.error) {
            vm.serverError = res.error;
            vm.$gzv.setErrorBoxErrors(vm);
          } else {
            vm.obj = res.data;
          }
        })
        .catch(function handleGetDataFromAPIError(error) {
          vm.$gzHandleFormError(error, vm);
        });
    },
    submit() {
      //check if form is valid, as far as I know this is the way you're supposed to do it and in testing it does not force all fields to revalidate individually
      if (this.$refs.form.validate()) {
        var vm = this;
        var url = "Widget/" + this.$route.params.id;

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

        this.$gzapi
          .upsert(url, this.obj)
          .then(res => {
            if (res.error) {
              vm.serverError = res.error;
              vm.$gzv.setErrorBoxErrors(vm);
            } else {
              //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.$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'
    ]
  }
}
*/
