<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">
            <gz-pick-list
              ref="selectedPartId"
              v-model="selectedPartId"
              readonly
              :aya-type="ayaTypes().Part"
              show-edit-icon
              :label="$ay.t('Part')"
              data-cy="selectedPartId"
            ></gz-pick-list>
          </v-col>
          <v-col cols="12">
            <gz-pick-list
              ref="partWarehouseId"
              v-model="selectedPartWarehouseId"
              :aya-type="ayaTypes().PartWarehouse"
              show-edit-icon
              :label="$ay.t('PartSerialWarehouseID')"
              data-cy="partWarehouseId"
              @input="addItem()"
            ></gz-pick-list>
          </v-col>

          <v-col cols="12" sm="6" class="mt-n5">
            <v-simple-table class="my-6">
              <template v-slot:default>
                <thead>
                  <tr>
                    <th class="text-left">
                      {{ $ay.t("PartSerialWarehouseID") }}
                    </th>
                    <th class="text-left">
                      {{ $ay.t("PartByWarehouseInventoryMinStockLevel") }}
                    </th>
                  </tr>
                </thead>

                <tbody>
                  <!-- Note the use of partWarehouseId which is unique plus quantity, without that quantity Vue doesn't update the display of quantity if it's changed by the quanittyChanged method -->
                  <tr v-for="(item, index) in obj" :key="index">
                    <td>
                      {{ item.partWarehouseDisplay }}
                      <template v-if="$vuetify.breakpoint.xs">
                        <div class="my-3">
                          <v-icon class="ml-6" @click="removeItem(item)">
                            $ayiTrashAlt
                          </v-icon>
                        </div>
                      </template>
                      <template v-else>
                        <v-icon class="ml-6" @click="removeItem(item)">
                          $ayiTrashAlt
                        </v-icon>
                      </template>
                    </td>
                    <td>
                      <gz-decimal
                        v-model="item.minimumQuantity"
                        :readonly="formState.readOnly"
                        @input="quantityChanged(item)"
                      >
                      </gz-decimal>
                    </td>
                  </tr>
                </tbody>
              </template>
            </v-simple-table>
          </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>
const FORM_KEY = "inv-part-stock-levels";
export default {
  data() {
    return {
      obj: [],
      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.Part,
      selectedPartId: Number(this.$route.params.recordid),
      selectedPartWarehouseId: null,
      minimumQuantity: 1
    };
  },
  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");
        }
      },
      deep: true
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(window.$gz.type.Part);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid == 0) {
        throw "Invalid partid";
      } else {
        await vm.getDataFromApi(vm.$route.params.recordid);
      }
      window.$gz.form.setFormState({
        vm: vm,
        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 || JUST_DELETED) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    sortedList: function() {
      function compare(a, b) {
        if (a.partWarehouseDisplay < b.partWarehouseDisplay) return -1;
        if (a.partWarehouseDisplay > b.partWarehouseDisplay) return 1;
        return 0;
      }
      return this.obj.slice().sort(compare);
    },
    addItem: function() {
      const vm = this;
      const selectedPartWarehouse = vm.$refs.partWarehouseId.getFullSelectionValue();
      if (selectedPartWarehouse == null || selectedPartWarehouse.id == null) {
        return;
      }
      const index = vm.obj.findIndex(
        z => z.partWarehouseId == selectedPartWarehouse.id
      );
      if (index != -1) {
        //already in the list
        return;
      }
      vm.obj.push({
        partId: vm.$route.params.recordid,
        partWarehouseId: selectedPartWarehouse.id,
        partWarehouseDisplay: selectedPartWarehouse.name,
        minimumQuantity: 1
      });
      vm.formState.dirty = true;
    },
    removeItem: function(item) {
      const vm = this;
      const index = vm.obj.findIndex(
        z => z.partWarehouseId == item.partWarehouseId
      );
      if (index == -1) {
        return;
      }
      vm.obj.splice(index, 1);
      vm.formState.dirty = true;
    },
    // openItem: function(item) {
    //   window.$gz.eventBus.$emit("openobject", {
    //     type: window.$gz.type.PartWarehouse,
    //     id: item.partWarehouseId
    //   });
    // },
    quantityChanged: function(item) {
      const vm = this;
      if (item.minimumQuantity == null || item.minimumQuantity < 1) {
        const index = vm.obj.findIndex(
          z => z.partWarehouseId == item.partWarehouseId
        );
        if (index == -1) {
          return;
        }
        item.minimumQuantity = 1;
      }
      vm.formState.dirty = true;
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    ayaTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    async getDataFromApi() {
      const vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!vm.$route.params.recordid) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.get(
          `part/stock-levels/${vm.$route.params.recordid}`
        );
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          generateMenu(vm);
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    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.put(
          `part/stock-levels/${vm.$route.params.recordid}`,
          vm.obj
        );
        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
          });
        }
      } 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: null,
    title: "PartStockingLevels",
    helpUrl: "inv-part-stock-levels",
    formData: {},
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

let JUST_DELETED = false;

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "PartStockingLevels",
    "PartByWarehouseInventoryMinStockLevel",
    "PartSerialWarehouseID"
  ]);
}
</script>
