<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>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.description"
              :readonly="formState.readOnly"
              :label="$ay.t('PartInventoryTransactionDescription')"
              :rules="[form().required(this, 'description')]"
              :error-messages="form().serverErrors(this, 'description')"
              ref="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
              :aya-type="ayaTypes().Part"
              :show-edit-icon="true"
              :allow-no-selection="false"
              v-model="obj.partId"
              :readonly="formState.readOnly"
              :label="$ay.t('Part')"
              ref="partId"
              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
              :aya-type="ayaTypes().PartWarehouse"
              :show-edit-icon="true"
              :allow-no-selection="false"
              v-model="obj.partWarehouseId"
              :readonly="formState.readOnly"
              :label="$ay.t('PartWarehouse')"
              ref="partWarehouseId"
              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
              v-model="obj.quantity"
              :readonly="formState.readOnly"
              :label="$ay.t('PartInventoryTransactionQuantity')"
              ref="quantity"
              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>
    <template v-if="!formState.ready">
      <v-progress-circular
        indeterminate
        color="primary"
        :size="60"
      ></v-progress-circular>
    </template>
  </div>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//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 {
  async created() {
    let vm = this;

    try {
      await initForm(vm);

      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);
  },
  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
    };
  },
  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        //enable / disable save button
        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");
        }

        //enable / disable duplicate / new button
        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
    }
  },
  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() {
      let vm = this;
      if (vm.canSave == false) {
        return;
      }

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        let url = API_BASE_URL; // + vm.$route.params.recordid;
        //clear any errors vm might be around from previous submit
        window.$gz.form.deleteAllErrorBoxErrors(vm);

        let res = await window.$gz.api.post(url, vm.obj);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //success, no need to be here anymore this is not an update form so navigate backwards since we don't know which list we came from
          //and it's not worth spending time coding that shit in
          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
        });
      }
    }
    //end methods
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let 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) {
  let 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,
      // formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      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(vm) {
  await fetchTranslatedText(vm);
}

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