<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">
        <div v-if="obj.aType" class="mb-6">
          <v-icon large @click="navToTarget()">{{ iconForType }}</v-icon
          ><span class="text-h5" @click="navToTarget()"> {{ name }}</span>
        </div>
        <v-row dense>
          <v-col cols="12">
            <v-textarea
              ref="name"
              v-model="obj.name"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('ServiceBankDescription')"
              :rules="[form().required(this, 'name')]"
              :error-messages="form().serverErrors(this, 'name')"
              data-cy="name"
              auto-grow
              @input="fieldValueChanged('name')"
            ></v-textarea>
          </v-col>

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

          <v-col
            v-if="form().showMe(this, 'ServiceBankHours')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-decimal
              ref="hours"
              v-model="obj.hours"
              :readonly="formState.readOnly"
              :label="$ay.t('ServiceBankHours')"
              data-cy="hours"
              :rules="[
                form().decimalValid(this, 'hours'),
                form().required(this, 'hours')
              ]"
              :error-messages="form().serverErrors(this, 'hours')"
              @input="fieldValueChanged('hours')"
            ></gz-decimal>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'ServiceBankIncidents')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-decimal
              ref="incidents"
              v-model="obj.incidents"
              :readonly="formState.readOnly"
              :label="$ay.t('ServiceBankIncidents')"
              data-cy="incidents"
              :rules="[
                form().decimalValid(this, 'incidents'),
                form().required(this, 'incidents')
              ]"
              :error-messages="form().serverErrors(this, 'incidents')"
              @input="fieldValueChanged('incidents')"
            ></gz-decimal>
          </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 = "service-bank-edit";
const API_BASE_URL = "service-bank/";
const FORM_CUSTOM_TEMPLATE_KEY = "ServiceBank";
export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      obj: {
        id: 0,
        concurrency: 0,
        name: null,
        objectId: null,
        aType: null,
        sourceId: 0, //default for manual entries
        sourceType: window.$gz.type.ServiceBank,
        incidents: 0,
        currency: 0,
        hours: 0
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      name: null
    };
  },
  computed: {
    iconForType() {
      return window.$gz.util.iconForType(this.obj.aType);
    }
  },
  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");
        }

        if (!val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit(
            "menu-enable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":new");
        } else {
          window.$gz.eventBus.$emit(
            "menu-disable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":new");
        }
      },
      deep: true
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(window.$gz.type.ServiceBank);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //NOTE: THIS FORM IS CREATE ONLY NO OPEN OLD ONES SO...

      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid != 0) {
        //Ok, we're here to *view* an existing record
        //so we must fetch the deets now
        await vm.getDataFromApi(vm.$route.params.recordid);
      } else {
        //New record so there has to be a object type and objectId in route
        // path: "/home-service-banks/:recordid/:aType?/:objectId?",
        vm.obj.objectId = window.$gz.util.stringToIntOrNull(
          vm.$route.params.objectId
        );
        vm.obj.aType = window.$gz.util.stringToIntOrNull(
          vm.$route.params.aType
        );

        if (!vm.obj.objectId || !vm.obj.aType) {
          throw "AType and ObjectId are required to create a service bank entry";
        }
        vm.name = vm.$route.params.name;

        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }

      if (!vm.name) {
        vm.name = await window.$gz.api.fetchBizObjectName(
          vm.obj.aType,
          vm.obj.objectId
        );
      }

      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_SAVED) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    navToTarget: function() {
      window.$gz.eventBus.$emit("openobject", {
        type: this.obj.aType,
        id: this.obj.objectId
      });
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },

    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (
        this.formState.ready &&
        !this.formState.loading &&
        !this.formState.readOnly
      ) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    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.upsert(API_BASE_URL, vm.obj);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          JUST_SAVED = true;

          vm.$router.go(-1);
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    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(API_BASE_URL + 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,
            readOnly: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, 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;

      case "report":
        {
          const res = await m.vm.$refs.reportSelector.open(
            {
              AType: window.$gz.type.ServiceBank,
              selectedRowIds: [m.vm.obj.id]
            },
            m.id
          );
          if (res == null) {
            return;
          }
          window.$gz.form.setLastReportMenuItem(FORM_KEY, res, m.vm);
        }
        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: "$ayiCarBattery",
    title: "ServiceBank",
    helpUrl: "acc-service-banks",
    formData: {
      ayaType: window.$gz.type.ServiceBank,
      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);
}

let JUST_SAVED = 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() {
  await window.$gz.translation.cacheTranslations([
    "ServiceBank",
    "ServiceBankDescription",
    "ServiceBankCurrency",
    "ServiceBankHours",
    "ServiceBankIncidents"
  ]);
}
</script>
