<template>
  <div>
    <gz-report-selector ref="reportSelector"></gz-report-selector>
    <div v-if="formState.ready">
      <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
      <v-form ref="form">
        <v-row dense>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="description"
              v-model="obj.description"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('PartInventoryTransactionDescription')"
              :rules="[form().required(this, 'description')]"
              :error-messages="form().serverErrors(this, 'description')"
              data-cy="description"
              @input="fieldValueChanged('description')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-pick-list
              ref="partId"
              v-model="obj.partId"
              :aya-type="ayaTypes().Part"
              show-edit-icon
              :allow-no-selection="false"
              :readonly="formState.readOnly"
              :label="$ay.t('Part')"
              data-cy="partId"
              :error-messages="form().serverErrors(this, 'partId')"
              @input="fieldValueChanged('partId')"
            ></gz-pick-list>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-pick-list
              ref="partWarehouseId"
              v-model="obj.partWarehouseId"
              :aya-type="ayaTypes().PartWarehouse"
              show-edit-icon
              :allow-no-selection="false"
              :readonly="formState.readOnly"
              :label="$ay.t('PartWarehouse')"
              data-cy="partWarehouseId"
              :error-messages="form().serverErrors(this, 'partWarehouseId')"
              @input="fieldValueChanged('partWarehouseId')"
            ></gz-pick-list>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-decimal
              ref="quantity"
              v-model="obj.quantity"
              :readonly="formState.readOnly"
              :label="$ay.t('PartInventoryTransactionQuantity')"
              data-cy="quantity"
              :rules="[
                form().decimalValid(this, 'quantity'),
                form().required(this, 'quantity')
              ]"
              :error-messages="form().serverErrors(this, 'quantity')"
              @input="fieldValueChanged('quantity')"
            ></gz-decimal>
          </v-col>
        </v-row>
      </v-form>
    </div>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
  </div>
</template>
<script>
//THIS FORM IS CREATE ONLY
//no delete, no duplicate, no fetch, just create or leave
//
const FORM_KEY = "inv-part-adjustment";
const API_BASE_URL = "part-inventory/";
export default {
  data() {
    return {
      obj: {
        id: 0,
        concurrency: 0,
        description: null,
        partId: null,
        partWarehouseId: null,
        quantity: 0
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      ayaType: window.$gz.type.PartInventory
    };
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }

        if (val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }

        if (!val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit(
            "menu-enable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":new");
        } else {
          window.$gz.eventBus.$emit(
            "menu-disable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":new");
        }
      },
      deep: true
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.obj.partId = window.$gz.util.stringToIntOrNull(
        vm.$route.params.partId
      );
      vm.obj.partWarehouseId = window.$gz.util.stringToIntOrNull(
        vm.$route.params.partWarehouseId
      );
      vm.rights = window.$gz.role.getRights(window.$gz.type.PartInventory);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);

      window.$gz.form.setFormState({
        vm: vm,
        loading: false,
        dirty: false,
        valid: true
      });
      generateMenu(vm);
    } catch (error) {
      window.$gz.errorHandler.handleFormError(error, vm);
    } finally {
      vm.formState.ready = true;
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: function() {
      return this.formState.valid && !this.formState.dirty;
    },
    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 submit() {
      const vm = this;
      if (vm.canSave == false) {
        return;
      }

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.post(API_BASE_URL, vm.obj);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          window.$gz.form.setFormState({
            vm: vm,
            loading: false,
            dirty: false,
            valid: true
          });
          vm.$router.go(-1);
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    }
  }
};

/////////////////////////////
//
//
async 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;

      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: "$ayiPeopleCarry",
    title: "PartInventoryAdjustment",
    helpUrl: "inv-part-inventory-transactions",
    formData: {
      ayaType: window.$gz.type.PartInventory,
      recordId: vm.$route.params.recordid,
      recordName: vm.obj.name
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }
  menuOptions.menuItems.push({ divider: true, inset: false });
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "PartInventoryAdjustment",
    "PartInventoryTransactionDescription",
    "PartInventoryTransactionQuantity",
    "Part",
    "PartWarehouse"
  ]);
}
</script>
