<template>
  <div>
    <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">
            <gz-pick-list
              :aya-type="ayaTypes().TaxCode"
              :show-edit-icon="true"
              v-model="obj.taxPartPurchaseId"
              :readonly="formState.readOnly"
              :label="$ay.t('GlobalTaxPartPurchaseID')"
              ref="taxPartPurchaseId"
              data-cy="taxPartPurchaseId"
              :error-messages="form().serverErrors(this, `taxPartPurchaseId`)"
              @input="fieldValueChanged(`taxPartPurchaseId`)"
            ></gz-pick-list>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-pick-list
              :aya-type="ayaTypes().TaxCode"
              :show-edit-icon="true"
              v-model="obj.taxRateSaleId"
              :readonly="formState.readOnly"
              :label="$ay.t('GlobalTaxRateSaleID')"
              ref="taxRateSaleId"
              data-cy="taxRateSaleId"
              :error-messages="form().serverErrors(this, `taxRateSaleId`)"
              @input="fieldValueChanged(`taxRateSaleId`)"
            ></gz-pick-list>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-pick-list
              :aya-type="ayaTypes().TaxCode"
              :show-edit-icon="true"
              v-model="obj.taxPartSaleId"
              :readonly="formState.readOnly"
              :label="$ay.t('GlobalTaxPartSaleID')"
              ref="taxPartSaleId"
              data-cy="taxPartSaleId"
              :error-messages="form().serverErrors(this, `taxPartSaleId`)"
              @input="fieldValueChanged(`taxPartSaleId`)"
            ></gz-pick-list>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              v-model="obj.searchCaseSensitiveOnly"
              :readonly="formState.readOnly"
              :label="$ay.t('GlobalSearchCaseSensitiveOnly')"
              ref="searchCaseSensitiveOnly"
              data-cy="searchCaseSensitiveOnly"
              @change="fieldValueChanged('searchCaseSensitiveOnly')"
            ></v-checkbox>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              v-model="obj.useInventory"
              :readonly="formState.readOnly"
              :label="$ay.t('GlobalUseInventory')"
              ref="useInventory"
              data-cy="useInventory"
              @change="fieldValueChanged('useInventory')"
            ></v-checkbox>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-duration-picker
              v-model="obj.workOrderCompleteByAge"
              :readonly="formState.readOnly"
              :label="$ay.t('GlobalWorkOrderCompleteByAge')"
              :show-seconds="false"
              ref="workOrderCompleteByAge"
              data-cy="workOrderCompleteByAge"
              :error-messages="
                form().serverErrors(this, 'workOrderCompleteByAge')
              "
              @input="fieldValueChanged('workOrderCompleteByAge')"
            ></gz-duration-picker>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.workLaborScheduleDefaultMinutes"
              :readonly="formState.readOnly"
              :label="$ay.t('GlobalLaborSchedUserDfltTimeSpan')"
              ref="workLaborScheduleDefaultMinutes"
              data-cy="workLaborScheduleDefaultMinutes"
              :rules="[
                form().integerValid(this, 'workLaborScheduleDefaultMinutes'),
                form().required(this, 'workLaborScheduleDefaultMinutes')
              ]"
              :error-messages="
                form().serverErrors(this, 'workLaborScheduleDefaultMinutes')
              "
              @input="fieldValueChanged('workLaborScheduleDefaultMinutes')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.workOrderTravelDefaultMinutes"
              :readonly="formState.readOnly"
              :label="$ay.t('GlobalTravelDfltTimeSpan')"
              ref="workOrderTravelDefaultMinutes"
              data-cy="workOrderTravelDefaultMinutes"
              :rules="[
                form().integerValid(this, 'workOrderTravelDefaultMinutes'),
                form().required(this, 'workOrderTravelDefaultMinutes')
              ]"
              :error-messages="
                form().serverErrors(this, 'workOrderTravelDefaultMinutes')
              "
              @input="fieldValueChanged('workOrderTravelDefaultMinutes')"
            ></v-text-field>
          </v-col>
          <v-col cols="12">
            <span class="text-h6"> {{ $ay.t("UserInterfaceSettings") }}</span>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-card elevation="0" outlined v-if="formState.ready">
              <v-list subheader>
                <!-- <v-subheader>{{ $ay.t("UserInterfaceSettings") }}</v-subheader> -->
                <v-list-item link to="adm-global-logo" data-cy="logo">
                  <v-list-item-title>{{
                    $ay.t("GlobalLogo")
                  }}</v-list-item-title>
                </v-list-item>
                <v-list-item
                  link
                  to="adm-global-select-templates"
                  data-cy="pickListTemplates"
                >
                  <v-list-item-title>{{
                    $ay.t("PickListTemplates")
                  }}</v-list-item-title>
                </v-list-item>
                <v-list-item link to="adm-global-seeds" data-cy="seeds">
                  <v-list-item-title>{{
                    $ay.t("GlobalNextSeeds")
                  }}</v-list-item-title>
                </v-list-item>
              </v-list>
            </v-card>
          </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 = "global-settings-edit";
const API_BASE_URL = "global-biz-setting/";
//const FORM_CUSTOM_TEMPLATE_KEY = "Global"; //<-- 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.Global);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //NOTE: slightly different in this form as there is only ever a single global object so no need for a bunch of code
      //is there already an obj from a prior operation?
      if (this.$route.params.obj) {
        //yes, no need to fetch it
        this.obj = this.$route.params.obj;
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      } else {
        await vm.getDataFromApi(); //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) {
      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:
        //IMPORTANT NOTE: Fields that are NON NULLABLE in the schema for the table but *are* hideable **MUST** have a default value set here or else there will be no way to save the record
        //I.E. Serial, usertype fields, ACTIVE
        //Also, if it's a non-nullable Enum backed field then it should have a valid selection i.e. not zero if there is no zero
        {
          id: 0,
          concurrency: 0,
          searchCaseSensitiveOnly: false,
          useInventory: true,
          taxPartPurchaseId: null,
          taxPartSaleId: null,
          taxRateSaleId: null,
          workOrderCompleteByAge: "00:00:00",
          workOrderTravelDefaultMinutes: 0,
          workLaborScheduleDefaultMinutes: 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.Project
    };
  },
  //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");
        }
      },
      deep: true
    }
  },
  methods: {
    canSave: 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 getDataFromApi() {
      let vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });

      let url = API_BASE_URL;
      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 = API_BASE_URL;
        //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 {
          //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: "$ayiCogs",
    title: "AdministrationGlobalSettings",
    helpUrl: "adm-global-settings",
    formData: {
      ayaType: window.$gz.type.Project,
      recordId: vm.$route.params.recordid
      //,
      //formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
    },
    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);
  //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([
    "UserInterfaceSettings",
    "PickListTemplates",
    "GlobalLogo",
    "GlobalUseInventory",
    "GlobalSearchCaseSensitiveOnly",
    "GlobalTaxPartPurchaseID",
    "GlobalTaxPartSaleID",
    "GlobalTaxRateSaleID",
    "GlobalNextSeeds",
    "GlobalWorkOrderCompleteByAge",
    "GlobalLaborSchedUserDfltTimeSpan",
    "GlobalTravelDfltTimeSpan"
  ]);
}
</script>
