<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 v-if="!formState.readOnly" cols="12" sm="6">
            <v-textarea
              ref="newSerial"
              v-model="newSerial"
              dense
              outlined
              :label="$ay.t('Add')"
              clearable
              :rows="$vuetify.breakpoint.xs ? 3 : 10"
              data-cy="newSerial"
              append-outer-icon="$ayiPlus"
              @click:append-outer="addItem()"
            ></v-textarea>
          </v-col>
          <v-col cols="12" sm="6" class="mt-n5">
            <v-simple-table>
              <template v-slot:default>
                <thead>
                  <tr>
                    <th>{{ $ay.t("PartSerialNumbersAvailable") }}</th>
                    <th />
                  </tr>
                </thead>

                <tbody>
                  <tr v-for="(item, index) in sortedList()" :key="index">
                    <td>
                      {{ item }}
                    </td>
                    <td>
                      <v-icon class="ml-6" @click="removeItem(index)">
                        $ayiTrashAlt
                      </v-icon>
                    </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-serials";
const FORM_CUSTOM_TEMPLATE_KEY = "inv-part-serials";
export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      obj: {
        id: 0,
        name: null
      },
      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),
      newSerial: null
    };
  },
  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() {
      if (this.obj == null || this.obj.length == 0) {
        return [];
      }
      return this.obj.slice().sort();
    },
    removeItem: function(index) {
      this.obj.splice(index, 1);
      this.formState.dirty = true;
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    addItem: function() {
      if (this.newSerial == null || this.newSerial == "") {
        return;
      }
      //add to list, may be in various formats so handle that
      let splitted = this.newSerial.split(/[\s,]+/).filter(Boolean); //filter Boolean is equivalent to array.filter(item => Boolean(item)) and it's to filter out nulls concisely from badly formatted strings
      splitted = [...splitted, ...this.obj];
      const uniqueItems = [...new Set(splitted)]; //remove any dupes with Set
      uniqueItems.sort();
      this.obj = uniqueItems;
      this.formState.dirty = true;
      this.newSerial = null;
    },
    ayaTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    async getDataFromApi(recordId) {
      const vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.get(`part/serials/${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/serials/${vm.$route.params.recordid}`,
          vm.obj
        );
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data; //updated list of serials from server
          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: "PartSerialNumbersAvailable",
    helpUrl: "inv-part-serials",
    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([
    "PartSerialNumbersAvailable"
  ]);
}
</script>
