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

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

          <v-col
            v-if="form().showMe(this, 'ServiceBankHours')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-decimal
              v-model="obj.hours"
              :readonly="formState.readOnly"
              :label="$ay.t('ServiceBankHours')"
              ref="hours"
              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
              v-model="obj.incidents"
              :readonly="formState.readOnly"
              :label="$ay.t('ServiceBankIncidents')"
              ref="incidents"
              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>
    <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 = "service-bank-edit";
const API_BASE_URL = "service-bank/";
const FORM_CUSTOM_TEMPLATE_KEY = "ServiceBank"; //<-- 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.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 a new record don't load one
      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); //let getdata handle loading
      } else {
        //New record so there has to be a object type and objectId in route
        // path: "/home-service-banks/:recordid/:objectType?/:objectId?",
        vm.obj.objectId = window.$gz.util.stringToIntOrNull(
          vm.$route.params.objectId
        );
        vm.obj.objectType = window.$gz.util.stringToIntOrNull(
          vm.$route.params.objectType
        );

        if (!vm.obj.objectId || !vm.obj.objectType) {
          throw "ObjectType 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.objectType,
          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);
  },
  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
        /*
        {"data":{"id":1,"concurrency":1387706,"name":"Prepaid for $500 labor","entryDate":"2005-11-27T19:04:00Z","lastEntryDate":null,"objectId":1,"objectType":8,
        "sourceId":0,"sourceType":55,"incidents":0.0000,"incidentsBalance":0.0000,"lastIncidentsBalance":null,
        "currency":500.0000,"currencyBalance":500.0000,"lastCurrencyBalance":null,
        "hours":0.0000,"hoursBalance":0.0000,"lastHoursBalance":null}}
        */
        //THIS FORM IS ONLY USED TO CREATE ENTRIES SO DEFAULTS TO THOSE REQUIREMENTS
        {
          id: 0,
          concurrency: 0,
          name: null,
          objectId: null,
          objectType: 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
    };
  },
  //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");
        }

        //enable / disable duplicate / new button
        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
    }
  },
  computed: {
    iconForType() {
      return window.$gz.util.iconForType(this.obj.objectType);
    }
  },
  methods: {
    navToTarget: function() {
      window.$gz.eventBus.$emit("openobject", {
        type: this.obj.objectType,
        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() {
      let vm = this;
      if (vm.canSave == false) {
        return;
      }

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        let url = API_BASE_URL; // + 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.upsert(url, vm.obj);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          JUST_SAVED = true;
          //success, back to list, nothing to see here
          vm.$router.go(-1);
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    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 = API_BASE_URL + 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,
            readOnly: true, //service banks are always read only after they are saved
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, 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;

      case "report":
        if (m.id != null) {
          //last report selected is in m.id
          m.vm.$router.push({
            name: "ay-report",
            params: { recordid: m.id, ayatype: window.$gz.type.ServiceBank }
          });
        } else {
          //general report selector chosen

          let res = await m.vm.$refs.reportSelector.open({
            ObjectType: window.$gz.type.ServiceBank,
            selectedRowIds: [m.vm.obj.id]
          });

          //if null for no selection
          //just bail out
          if (res == null) {
            return;
          }
          //persist last report selected
          window.$gz.form.setLastReport(FORM_KEY, res);

          //Now open the report viewer...
          m.vm.$router.push({
            name: "ay-report",
            params: { recordid: res.id, ayatype: window.$gz.type.ServiceBank }
          });
        }
        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: "$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);
}

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