<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">
            <gz-pick-list
              readonly
              v-model="selectedPartId"
              :aya-type="ayaTypes().Part"
              show-edit-icon
              :label="$ay.t('Part')"
              ref="selectedPartId"
              data-cy="selectedPartId"
            ></gz-pick-list>
          </v-col>
          <v-col cols="12">
            <gz-pick-list
              v-model="selectedPartWarehouseId"
              :aya-type="ayaTypes().PartWarehouse"
              show-edit-icon
              :label="$ay.t('PartSerialWarehouseID')"
              ref="partWarehouseId"
              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 in sortedList()"
                    :key="
                      item.partWarehouseId.toString() +
                        item.minimumQuantity.toString()
                    "
                  >
                    <td>
                      {{ item.partWarehouseDisplay }}
                      <template v-if="$vuetify.breakpoint.xs">
                        <div class="my-3">
                          <v-icon class="ml-2" @click="openItem(item)">
                            $ayiEdit
                          </v-icon>
                          <v-icon class="ml-6" @click="removeItem(item)">
                            $ayiTrashAlt
                          </v-icon>
                        </div>
                      </template>
                      <template v-else>
                        <v-icon class="ml-6" @click="openItem(item)">
                          $ayiEdit
                        </v-icon>
                        <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>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
const FORM_KEY = "inv-part-stock-levels";
//const API_BASE_URL = "part/";

export default {
  async created() {
    let 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); //let getdata handle loading
      }

      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);
  },
  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
    };
  },

  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        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");
        }
      },
      deep: true
    }
  },
  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() {
      let vm = this;

      let selectedPartWarehouse = vm.$refs.partWarehouseId.getFullSelectionValue();
      //vm.selectedPartWarehouseId = null;
      if (selectedPartWarehouse == null || selectedPartWarehouse.id == null) {
        return;
      }
      let 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) {
      let vm = this;
      let 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) {
      let vm = this;
      if (item.minimumQuantity == null || item.minimumQuantity < 1) {
        let 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() {
      let vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!vm.$route.params.recordid) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      let url = `part/stock-levels/${vm.$route.params.recordid}`;
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);

        let res = await window.$gz.api.get(url);

        if (res.error) {
          //Not found?
          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;
          //modify the menu as necessary
          generateMenu(vm);
          //Update the form status
          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() {
      let vm = this;
      if (vm.canSave == false) {
        return;
      }

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        let url = `part/stock-levels/${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.put(url, vm.obj);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data; //updated list of stock levels from server

          //Update the form status
          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
        });
      }
    }
    //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: 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(vm) {
  await fetchTranslatedText(vm);
}

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