<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <!-- Prevent implicit submission of the form on enter key, this is not necessary on a form with a text area which is why I never noticed it with the other forms -->
        <button
          type="submit"
          disabled
          style="display: none"
          aria-hidden="true"
        ></button>
        <v-row>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="purchaseOrderNextSerial"
              v-model="obj.purchaseOrderNextSerial"
              :readonly="formState.readOnly"
              :label="$ay.t('NextPONumber')"
              data-cy="purchaseOrderNextSerial"
              :rules="[
                form().integerValid(this, 'purchaseOrderNextSerial'),
                form().required(this, 'purchaseOrderNextSerial')
              ]"
              :error-messages="
                form().serverErrors(this, 'purchaseOrderNextSerial')
              "
              append-outer-icon="$ayiSave"
              @input="fieldValueChanged('purchaseOrderNextSerial')"
              @click:append-outer="
                submit(ayaTypes().PurchaseOrder, obj.purchaseOrderNextSerial)
              "
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="workorderNextSerial"
              v-model="obj.workorderNextSerial"
              :readonly="formState.readOnly"
              :label="$ay.t('NextWorkorderNumber')"
              data-cy="workorderNextSerial"
              :rules="[
                form().integerValid(this, 'workorderNextSerial'),
                form().required(this, 'workorderNextSerial')
              ]"
              :error-messages="form().serverErrors(this, 'workorderNextSerial')"
              append-outer-icon="$ayiSave"
              @input="fieldValueChanged('workorderNextSerial')"
              @click:append-outer="
                submit(ayaTypes().WorkOrder, obj.workorderNextSerial)
              "
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="quoteNextSerial"
              v-model="obj.quoteNextSerial"
              :readonly="formState.readOnly"
              :label="$ay.t('NextQuoteNumber')"
              data-cy="quoteNextSerial"
              :rules="[
                form().integerValid(this, 'quoteNextSerial'),
                form().required(this, 'quoteNextSerial')
              ]"
              :error-messages="form().serverErrors(this, 'quoteNextSerial')"
              append-outer-icon="$ayiSave"
              @input="fieldValueChanged('quoteNextSerial')"
              @click:append-outer="
                submit(ayaTypes().Quote, obj.quoteNextSerial)
              "
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="pmNextSerial"
              v-model="obj.pmNextSerial"
              :readonly="formState.readOnly"
              :label="$ay.t('NextPMNumber')"
              data-cy="pmNextSerial"
              :rules="[
                form().integerValid(this, 'pmNextSerial'),
                form().required(this, 'pmNextSerial')
              ]"
              :error-messages="form().serverErrors(this, 'pmNextSerial')"
              append-outer-icon="$ayiSave"
              @input="fieldValueChanged('pmNextSerial')"
              @click:append-outer="submit(ayaTypes().PM, obj.pmNextSerial)"
            ></v-text-field>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
//
//NOTE: This is a simple form with no need for business rules or validation so stripped out any extraneous code related to all that
//
const FORM_KEY = "adm-global-seeds";
const API_BASE_URL = "global-biz-setting/seeds/";
export default {
  data() {
    return {
      obj: {
        purchaseOrderNextSerial: null,
        workorderNextSerial: null,
        quoteNextSerial: null,
        pmNextSerial: null
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.getRights(window.$gz.type.Global)
    };
  }, //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        const canSave = val.dirty && val.valid && !val.readOnly;
        if (canSave) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
      },
      deep: true
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.formState.ready = true;
      vm.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //NOTE: this would normally be in getDataFromAPI but this form doesn't really need that function so doing it here
      generateMenu(vm);
      await vm.getDataFromApi();
      vm.formState.loading = false;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  methods: {
    ayaTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (
        this.formState.ready &&
        !this.formState.loading &&
        !this.formState.readOnly
      ) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi() {
      const vm = this;
      vm.formState.loading = true;

      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get(API_BASE_URL);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;

          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async submit(aType, nextNumber) {
      window.$gz.form.deleteAllErrorBoxErrors(this);
      try {
        const res = await window.$gz.api.put(
          `${API_BASE_URL}${aType}/${nextNumber}`
        );
        this.formState.loading = false;
        if (res.error) {
          this.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(this);
        } else {
          window.$gz.form.setFormState({
            vm: this,
            dirty: false
          });
        }
      } catch (error) {
        this.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, this);
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: false,
    readOnly: vm.formState.readOnly,
    icon: null,
    title: "GlobalNextSeeds",
    helpUrl: "adm-global-seeds",
    formData: {
      ayaType: window.$gz.type.global,
      formCustomTemplateKey: undefined
    },
    menuItems: []
  };
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "GlobalNextSeeds",
    "NextPONumber",
    "NextQuoteNumber",
    "NextWorkorderNumber",
    "NextPMNumber"
  ]);
}
</script>
