<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="true"
              :label="$ay.t('Part')"
              ref="selectedPartId"
              data-cy="selectedPartId"
            ></gz-pick-list>
          </v-col>
          <v-col cols="12" sm="6" v-if="!formState.readOnly">
            <v-textarea
              outlined
              v-model="newSerial"
              :label="$ay.t('Add')"
              clearable
              :rows="$vuetify.breakpoint.xs ? 3 : 10"
              ref="newSerial"
              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>
    <template v-if="!formState.ready">
      <v-progress-circular
        indeterminate
        color="primary"
        :size="60"
      ></v-progress-circular>
    </template>
  </div>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
const FORM_KEY = "inv-part-serials";
//const API_BASE_URL = "part/";
const FORM_CUSTOM_TEMPLATE_KEY = "inv-part-serials"; //<-- Should always be CoreBizObject AyaType name here where possible

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 a new record don't load one
      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 {
      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
    };
  },

  //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() {
      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];
      let 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;
    },
    // fieldValueChanged(ref) {
    //   if (
    //     this.formState.ready &&
    //     !this.formState.loading &&
    //     !this.formState.readOnly
    //   ) {
    //     window.$gz.form.fieldValueChanged(this, ref);
    //   }
    // },
    async getDataFromApi(recordId) {
      let vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      let url = `part/serials/${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/serials/${vm.$route.params.recordid}`;
        let url = `part/serials/${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 serials from server
          //PRETTY SURE DON"T NEED ANY OF THIS
          //   //Logic for detecting if a post or put: if id then it was a post, if no id then it was a put
          //   if (res.data.id) {
          //     //POST - whole new object returned
          //     vm.obj = res.data;
          //     //Change URL to new record
          //     //NOTE: will not cause a page re-render, almost nothing does unless forced with a KEY property or using router.GO()

          //     this.$router.push({
          //       name: "project-edit",
          //       params: {
          //         recordid: res.data.id,
          //         obj: res.data // Pass data object to new form
          //       }
          //     });
          //   } else {
          //     //PUT - only concurrency token is returned (**warning, if server changes object other fields then this needs to act more like POST above but is more efficient this way**)
          //     //Handle "put" of an existing record (UPDATE)
          //     vm.obj.concurrency = res.data.concurrency;
          //   }
          //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: "PartSerialNumbersAvailable",
    helpUrl: "inv-part-serials",
    formData: {
      // ayaType: window.$gz.type.Par,
      // 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
    });
  }

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

let JUST_DELETED = false;

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  //await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY, vm);
}

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