<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="this.$gzv.ErrorBoxErrors(this)"
              color="error"
              icon="fa-exclamation-circle "
              value="true"
              transition="scale-transition"
              class="multi-line"
              outline
            >{{this.$gzv.ErrorBoxErrors(this)}}</v-alert>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.name"
              :counter="255"
              :label="this.$gzlocale.get('WidgetName')"
              :rules="[this.$gzv.Max255(this,'name')]"
              :error-messages="this.$gzv.ServerErrors(this,'name')"
              ref="name"
              @change="Change('name')"
            ></v-text-field>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.serial"
              :counter="10"
              :label="this.$gzlocale.get('WidgetSerial')"
              :rules="[this.$gzv.MaxLength(this,'serial',10)]"
              :error-messages="this.$gzv.ServerErrors(this,'count')"
              ref="serial"
              @change="Change('serial')"
            ></v-text-field>
          </v-flex>
          <v-flex xs12 sm6 lg4 xl3 px-2>
            <v-text-field
              v-model="obj.count"
              :counter="10"
              :label="this.$gzlocale.get('WidgetCount')"
              ref="count"
              :rules="[this.$gzv.Integer(this,'count'),this.$gzv.Required(this,'count')]"
              :error-messages="this.$gzv.ServerErrors(this,'count')"
              required
              @change="Change('count')"
            ></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.Decimal(this,'dollarAmount'),this.$gzv.Required(this,'dollarAmount')]"
              :error-messages="this.$gzv.ServerErrors(this,'dollarAmount')"
              @change="Change('dollarAmount')"
            ></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="Change('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.After(this,'startDate','endDate')]"
              :error-messages="this.$gzv.ServerErrors(this,'endDate')"
              v-model="obj.endDate"
              ref="endDate"
              @change="Change('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="Change('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.Integer(this,'roles'),this.$gzv.Required(this,'roles')]"
              :error-messages="this.$gzv.ServerErrors(this,'roles')"
              required
              @change="Change('roles')"
            ></v-text-field>
          </v-flex>
        </v-layout>

        <v-layout align-center justify-space-around row wrap mt-5>
          <v-flex xs1>
            <v-btn>test 1</v-btn>
          </v-flex>
          <v-flex xs1>
            <v-btn>test2</v-btn>
          </v-flex>
          <v-flex xs1>
            <v-btn @click="submit">save</v-btn>
          </v-flex>
        </v-layout>
      </v-form>
    </v-flex>
  </v-layout>
</template>

<script>
/*  eslint-disable */

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"
    ];
    this.$gzlocale
      .fetch(ltKeysRequired)
      .then(() => (this.formReady = true))
      .catch(err => {
        this.formReady = true;
        this.$gzerror(err);
      });
  },
  created() {
    this.getDataFromApi();
  },
  components: {},
  data() {
    return {
      obj: {},
      serverError: {},
      formReady: false,
      someerror:
        "blah blahv <br/> blah blah" + "\n test line 3" + "\r\n Test line 4"
    };
  }, 
  methods: {  
    Change(ref){
      //debugger;
      //console.log("CHANGE - " + ref);
      this.$gzv.Change(this,ref);
    } ,
    getDataFromApi() {
      var url = "Widget/" + this.$route.params.id;
      this.$gzapi.get(url).then(res => {
        this.obj = res.data;
      });
    },
    submit() {
      // debugger;

      //TODO: CHECK FOR BROKEN RULES AND DON'T SUBMIT IF THERE ARE ANY HERE

      var that = this;
      var url = "Widget/" + this.$route.params.id;
      //clear any errors that might be around from previous submit
      this.serverErrors = [];
      this.$gzapi
        .upsert(url, this.obj)
        .then(res => {
          if (res.error) {
            //debugger;
            //Set errors so form can pick them up for controls in canHasServerErrors
            that.serverError = res.error;
            // that.$refs.form.resetValidation();
            // that.$refs.form.validate();
            //example error when submit when there are no roles set at all (blank)
            //{"error":{"code":"2200","details":[{"code":"2200","message":"","target":"roles","error":"VALIDATION_FAILED"}],"message":"Object did not pass validation"}}
          } 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
              that.obj = res.data;
            } else {
              //Handle "put" of an existing record
              that.obj.concurrencyToken = res.data.concurrencyToken;
            }
          }
        })
        .catch(function(error) {
          //we should be here if it was a gross error of some kind not a mild one like validation but more like if the server doesn't exist or something I guess

          console.log(error);
          alert("Houston, we have a problem");
        });

      //example from login form
      //  if (this.input.username != "" && this.input.password != "") {
      //   auth
      //     .authenticate(this.input.username, this.input.password)
      //     .then(() => {
      //       this.$router.replace({ name: "home" });
      //     })
      //     .catch(function(error) {
      //       /* xeslint-disable-next-line */
      //       //console.log(error);
      //       alert("login failed: " + error);
      //     });
      // }
    } //end of submit()
  }
};
</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'
    ]
  }
}
*/