<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-tabs mobile-breakpoint="100" v-model="tab">
          <v-tab>{{ $ay.t("Unit") }}</v-tab>
          <v-tab>{{ $ay.t("Address") }}</v-tab>
          <v-tab>{{ $ay.t("UnitOverrideWarranty") }}</v-tab>
          <v-tabs-items v-model="tab">
            <v-tab-item class="mt-4 ml-2">
              <v-row>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    v-model="obj.serial"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitSerial')"
                    :rules="[form().required(this, 'serial')]"
                    :error-messages="form().serverErrors(this, 'serial')"
                    ref="serial"
                    data-cy="serial"
                    @input="fieldValueChanged('serial')"
                  ></v-text-field>
                </v-col>

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

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

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

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

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

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

                <v-col
                  v-if="
                    form().showMe(this, 'ContractExpires') && obj.contractId
                  "
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <gz-date-time-picker
                    :label="$ay.t('ContractExpires')"
                    v-model="obj.contractExpires"
                    :readonly="formState.readOnly"
                    ref="contractExpires"
                    data-cy="contractExpires"
                    :error-messages="
                      form().serverErrors(this, 'contractExpires')
                    "
                    @input="fieldValueChanged('contractExpires')"
                  ></gz-date-time-picker>
                </v-col>

                <!-- <v-col
                  v-if="form().showMe(this, 'UsesBanking')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-checkbox
                    v-model="obj.usesBanking"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UsesBanking')"
                    ref="usesBanking"
                    data-cy="usesBanking"
                    :error-messages="form().serverErrors(this, 'usesBanking')"
                    @change="fieldValueChanged('usesBanking')"
                  >
                    <template v-slot:append v-if="canOpenServiceBank()">
                      <v-btn
                        outlined
                        small
                        color="primary"
                        @click="openServiceBank"
                        class="ml-12"
                      >
                        <v-icon>$ayiCarBattery</v-icon></v-btn
                      >
                    </template>
                  </v-checkbox>
                </v-col> -->

                <v-col
                  v-if="form().showMe(this, 'UnitMetered')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-checkbox
                    v-model="obj.metered"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitMetered')"
                    ref="metered"
                    data-cy="metered"
                    :error-messages="form().serverErrors(this, 'metered')"
                    @change="fieldValueChanged('metered')"
                  >
                    <template v-slot:append v-if="canOpenMeter()">
                      <v-btn
                        outlined
                        small
                        color="primary"
                        @click="openMeter"
                        class="ml-12"
                      >
                        <v-icon>$ayiWeight</v-icon></v-btn
                      >
                    </template>
                  </v-checkbox>
                </v-col>

                <v-col
                  v-if="form().showMe(this, 'UnitBoughtHere')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-checkbox
                    v-model="obj.boughtHere"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitBoughtHere')"
                    ref="boughtHere"
                    data-cy="boughtHere"
                    :error-messages="form().serverErrors(this, 'boughtHere')"
                    @change="fieldValueChanged('boughtHere')"
                  ></v-checkbox>
                </v-col>

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

                <v-col
                  v-if="form().showMe(this, 'UnitPurchasedDate')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <gz-date-time-picker
                    :label="$ay.t('UnitPurchasedDate')"
                    v-model="obj.purchasedDate"
                    :readonly="formState.readOnly"
                    ref="purchasedDate"
                    data-cy="purchasedDate"
                    :error-messages="form().serverErrors(this, 'purchasedDate')"
                    @input="fieldValueChanged('purchasedDate')"
                  ></gz-date-time-picker>
                </v-col>

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

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

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

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

                <v-col
                  v-if="form().showMe(this, 'UnitText4')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    v-model="obj.text4"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitText4')"
                    :error-messages="form().serverErrors(this, 'text4')"
                    ref="text4"
                    data-cy="text4"
                    @input="fieldValueChanged('text4')"
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-checkbox
                    v-model="obj.active"
                    :readonly="formState.readOnly"
                    :label="$ay.t('Active')"
                    ref="active"
                    data-cy="active"
                    :error-messages="form().serverErrors(this, 'active')"
                    @change="fieldValueChanged('active')"
                  ></v-checkbox>
                </v-col>
                <!-- --------------------------------- -->
                <v-col v-if="form().showMe(this, 'Notes')" cols="12">
                  <v-textarea
                    v-model="obj.notes"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitNotes')"
                    :error-messages="form().serverErrors(this, 'notes')"
                    ref="notes"
                    data-cy="notes"
                    @input="fieldValueChanged('notes')"
                    auto-grow
                  ></v-textarea>
                </v-col>

                <v-col v-if="form().showMe(this, 'Tags')" cols="12">
                  <gz-tag-picker
                    v-model="obj.tags"
                    :readonly="formState.readOnly"
                    ref="tags"
                    data-cy="tags"
                    :error-messages="form().serverErrors(this, 'tags')"
                    @input="fieldValueChanged('tags')"
                  ></gz-tag-picker>
                </v-col>

                <v-col cols="12">
                  <gz-custom-fields
                    v-model="obj.customFields"
                    :form-key="formCustomTemplateKey"
                    :readonly="formState.readOnly"
                    :parent-v-m="this"
                    ref="customFields"
                    data-cy="customFields"
                    :error-messages="form().serverErrors(this, 'customFields')"
                    @input="fieldValueChanged('customFields')"
                  ></gz-custom-fields>
                </v-col>

                <v-col v-if="form().showMe(this, 'Wiki')" cols="12">
                  <gz-wiki
                    :aya-type="ayaType"
                    :aya-id="obj.id"
                    ref="wiki"
                    v-model="obj.wiki"
                    :readonly="formState.readOnly"
                    @input="fieldValueChanged('wiki')"
                  ></gz-wiki
                ></v-col>

                <v-col
                  v-if="form().showMe(this, 'Attachments') && obj.id"
                  cols="12"
                >
                  <gz-attachments
                    :readonly="formState.readOnly"
                    :aya-type="ayaType"
                    :aya-id="obj.id"
                  ></gz-attachments
                ></v-col>
              </v-row>
            </v-tab-item>
            <!-- 
                
                ################################# ADDRESS TAB ######################### 
            
            -->
            <v-tab-item class="mt-4 ml-2">
              <v-row>
                <v-col cols="12">
                  <v-checkbox
                    v-model="obj.unitHasOwnAddress"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitUnitHasOwnAddress')"
                    ref="unitHasOwnAddress"
                    data-cy="unitHasOwnAddress"
                    :error-messages="
                      form().serverErrors(this, 'unitHasOwnAddress')
                    "
                    @change="fieldValueChanged('unitHasOwnAddress')"
                  ></v-checkbox>
                  <v-col cols="12" v-if="obj.unitHasOwnAddress">
                    <v-menu offset-y v-if="rights.change">
                      <template v-slot:activator="{ on, attrs }">
                        <span class="text-h6">
                          {{ $ay.t("AddressTypePhysical") }}</span
                        ><v-btn icon v-bind="attrs" v-on="on">
                          <v-icon small>$ayiEllipsisV</v-icon>
                        </v-btn>
                      </template>
                      <v-list>
                        <v-list-item @click="AddressCopyPhysicalToClipBoard()">
                          <v-list-item-icon>
                            <v-icon>$ayiCopy</v-icon>
                          </v-list-item-icon>
                          <v-list-item-title>{{
                            $ay.t("CopyToClipboard")
                          }}</v-list-item-title>
                        </v-list-item>

                        <v-list-item @click="GeoCapture">
                          <v-list-item-icon>
                            <v-icon>$ayiMapMarker</v-icon>
                          </v-list-item-icon>
                          <v-list-item-title>{{
                            $ay.t("GeoCapture")
                          }}</v-list-item-title>
                        </v-list-item>
                      </v-list>
                    </v-menu>
                    <span class="text-h6" v-else>
                      {{ $ay.t("AddressTypePhysical") }}</span
                    >
                  </v-col>
                </v-col>
                <v-col
                  v-if="form().showMe(this, 'Address') && obj.unitHasOwnAddress"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    v-model="obj.address"
                    :readonly="formState.readOnly"
                    :label="$ay.t('AddressDeliveryAddress')"
                    ref="address"
                    data-cy="address"
                    :error-messages="form().serverErrors(this, 'address')"
                    @input="fieldValueChanged('address')"
                  ></v-text-field>
                </v-col>

                <v-col
                  v-if="form().showMe(this, 'City') && obj.unitHasOwnAddress"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    v-model="obj.city"
                    :readonly="formState.readOnly"
                    :label="$ay.t('AddressCity')"
                    ref="city"
                    data-cy="city"
                    :error-messages="form().serverErrors(this, 'city')"
                    @input="fieldValueChanged('city')"
                  ></v-text-field>
                </v-col>

                <v-col
                  v-if="form().showMe(this, 'Region') && obj.unitHasOwnAddress"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    v-model="obj.region"
                    :readonly="formState.readOnly"
                    :label="$ay.t('AddressStateProv')"
                    ref="region"
                    data-cy="region"
                    :error-messages="form().serverErrors(this, 'region')"
                    @input="fieldValueChanged('region')"
                  ></v-text-field>
                </v-col>

                <v-col
                  v-if="form().showMe(this, 'Country') && obj.unitHasOwnAddress"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    v-model="obj.country"
                    :readonly="formState.readOnly"
                    :label="$ay.t('AddressCountry')"
                    ref="country"
                    data-cy="country"
                    :error-messages="form().serverErrors(this, 'country')"
                    @input="fieldValueChanged('country')"
                  ></v-text-field>
                </v-col>

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

                <v-col
                  v-if="form().showMe(this, 'Longitude')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <gz-decimal
                    v-model="obj.longitude"
                    :readonly="formState.readOnly"
                    :label="$ay.t('AddressLongitude')"
                    ref="longitude"
                    data-cy="longitude"
                    :rules="[form().decimalValid(this, 'longitude')]"
                    :error-messages="form().serverErrors(this, 'longitude')"
                    @input="fieldValueChanged('longitude')"
                    :precision="6"
                  ></gz-decimal>
                </v-col>
              </v-row>
            </v-tab-item>
            <!-- 
                
                ################################# WARRANTY TAB ######################### 
            
            -->
            <v-tab-item class="mt-4 ml-2">
              <v-row>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-checkbox
                    v-model="obj.overrideModelWarranty"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitOverrideWarranty')"
                    ref="overrideModelWarranty"
                    data-cy="overrideModelWarranty"
                    :error-messages="
                      form().serverErrors(this, 'overrideModelWarranty')
                    "
                    @change="fieldValueChanged('overrideModelWarranty')"
                  ></v-checkbox>
                </v-col>

                <v-col
                  v-if="
                    form().showMe(this, 'UnitOverrideLifeTime') &&
                      obj.overrideModelWarranty
                  "
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-checkbox
                    v-model="obj.lifeTimeWarranty"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitOverrideLifeTime')"
                    ref="lifeTimeWarranty"
                    data-cy="lifeTimeWarranty"
                    :error-messages="
                      form().serverErrors(this, 'lifeTimeWarranty')
                    "
                    @change="fieldValueChanged('lifeTimeWarranty')"
                  ></v-checkbox>
                </v-col>

                <v-col
                  v-if="
                    form().showMe(this, 'UnitOverrideLength') &&
                      obj.overrideModelWarranty &&
                      !obj.lifeTimeWarranty
                  "
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    v-model="obj.warrantyLength"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitOverrideLength')"
                    ref="warrantyLength"
                    data-cy="warrantyLength"
                    :rules="[form().integerValid(this, 'warrantyLength')]"
                    :error-messages="
                      form().serverErrors(this, 'warrantyLength')
                    "
                    @input="fieldValueChanged('warrantyLength')"
                    type="number"
                  ></v-text-field>
                </v-col>

                <v-col
                  v-if="
                    form().showMe(this, 'UnitOverrideWarrantyTerms') &&
                      obj.overrideModelWarranty
                  "
                  cols="12"
                >
                  <v-textarea
                    v-model="obj.warrantyTerms"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UnitOverrideWarrantyTerms')"
                    :error-messages="form().serverErrors(this, 'warrantyTerms')"
                    ref="warrantyTerms"
                    data-cy="warrantyTerms"
                    @input="fieldValueChanged('warrantyTerms')"
                    auto-grow
                  ></v-textarea>
                </v-col>
              </v-row>
            </v-tab-item>
          </v-tabs-items>
        </v-tabs>
      </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 = "unit-edit";
const API_BASE_URL = "unit/";
const FORM_CUSTOM_TEMPLATE_KEY = "Unit"; //<-- 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.Unit);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);

      let setDirty = false;
      let setValid = true;

      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid != 0) {
        //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;
        } else {
          await vm.getDataFromApi(vm.$route.params.recordid); //let getdata handle loading
        }
      } else {
        //Might be a duplicate and contain another record
        if (this.$route.params.obj) {
          this.obj = this.$route.params.obj;
          this.obj.concurrency = undefined;
          this.obj.id = 0;
          this.obj.serial = `${this.obj.serial} - ${window.$gz.translation.get(
            "Copy"
          )}`;
          setDirty = true;
        } else {
          //check for generate unit from part info on route params
          //(set by workorder item part when user selects generate unit from part)
          let gen = this.$route.params.genFromPart;
          if (gen) {
            //get the part then set the values accordingly
            let res = await window.$gz.api.get(`part/${gen.partId}`);
            if (res.error) {
              window.$gz.eventBus.$emit(
                "notify-warning",
                window.$gz.errorHandler.errorToString(res, this)
              );
            } else {
              let p = res.data;
              this.obj.boughtHere = true;
              this.obj.customerId = gen.customerId;
              this.obj.serial = gen.serial;
              this.obj.purchasedDate = gen.purchaseDate;
              this.obj.description = p.partNumber;
              if (
                gen.address ||
                gen.city ||
                gen.region ||
                gen.country ||
                gen.latitude ||
                gen.longitude
              ) {
                this.obj.unitHasOwnAddress = true;
                this.obj.address = gen.address ?? null;
                this.obj.city = gen.city ?? null;
                this.obj.region = gen.region ?? null;
                this.obj.country = gen.country ?? null;
                this.obj.latitude = gen.latitude ?? null;
                this.obj.longitude = gen.longitude ?? null;
              }

              if (p.name) {
                this.obj.description += ` ${p.name}`;
              }
            }
            setDirty = true;
          }
        }
      }

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

      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:
        //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": 90979,
		"concurrency": 2880802,
		"active": true,
		"notes": "Autem quia quod beatae reprehenderit et voluptatem aut animi.",
		"wiki": null,
		"customFields": null,
		"tags": [
			"zone3"
		],
		"serial": "00008962",
		"customerId": 19027,
		"parentUnitId": null,
		"unitModelId": 40,
		"unitHasOwnAddress": true,
		"boughtHere": true,
		"purchasedFromVendorId": null,
		"receipt": "376373",
		"purchasedDate": "2012-04-09T04:26:32.454688Z",
		"description": "Intelligent Metal Shirt",
		"replacedByUnitId": null,
		"overrideModelWarranty": false,
		"warrantyLength": null,
		"warrantyTerms": null,
		"usesBanking": false,
		"metered": false,
		"lifeTimeWarranty": false,
		"text1": null,
		"text2": null,
		"text3": null,
		"text4": null,
		"address": "453 Isabelle Alley",
		"city": "Douglasshire",
		"region": "California",
		"country": "Saint Lucia",
		"latitude": -22.1701,
		"longitude": 167.3475
	}
}
       */
        {
          id: 0,
          concurrency: 0,
          serial: null,
          active: true,
          notes: null,
          wiki: null,
          customFields: "{}",
          tags: [],
          customerId: null,
          parentUnitId: null,
          unitModelId: null,
          unitHasOwnAddress: false,
          boughtHere: false,
          purchasedFromVendorId: null,
          receipt: null,
          purchasedDate: null,
          description: null,
          replacedByUnitId: null,
          overrideModelWarranty: false,
          warrantyLength: null,
          warrantyTerms: null,
          //usesBanking: false,
          contractId: null,
          contractExpires: null,
          metered: false,
          lifeTimeWarranty: false,
          text1: null,
          text2: null,
          text3: null,
          text4: null,
          address: null,
          city: null,
          region: null,
          country: null,
          latitude: null,
          longitude: null
        },
      tab: 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.Unit
    };
  },
  //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
    }
  },
  methods: {
    // canOpenServiceBank: function() {
    //   return this.obj.usesBanking == true && this.$route.params.recordid != 0;
    // },
    // openServiceBank: function() {
    //   if (this.canOpenServiceBank()) {
    //     this.$router.push({
    //       name: "service-banks",
    //       params: {
    //         aType: window.$gz.type.Unit,
    //         objectId: this.$route.params.recordid,
    //         viz: this.obj.serial,
    //         icon: "$ayiFan"
    //       }
    //     });
    //   }
    // },
    canOpenMeter: function() {
      return this.obj.metered == true && this.$route.params.recordid != 0;
    },
    openMeter: function() {
      if (this.canOpenMeter()) {
        this.$router.push({
          name: "meter-readings",
          params: {
            aType: window.$gz.type.Unit,
            objectId: this.$route.params.recordid
          }
        });
      }
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: 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(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,
            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; // + 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 {
          //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.replace({
              name: "unit-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
        });
      }
    },
    async remove() {
      let vm = this;
      try {
        let dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        //do the delete
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        //No need to delete a new record, just abandon it...
        if (vm.$route.params.recordid == 0) {
          //this should not get offered for delete but to be safe and clear just in case:
          JUST_DELETED = true;
          // navigate backwards
          vm.$router.go(-1);
        } else {
          let url = API_BASE_URL + vm.$route.params.recordid;

          window.$gz.form.deleteAllErrorBoxErrors(vm);
          let res = await window.$gz.api.remove(url);
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            //workaround to prevent warning about leaving dirty record
            //For some reason I couldn't just reset isdirty in formstate
            JUST_DELETED = true;
            // navigate backwards
            vm.$router.go(-1);
          }
        }
      } catch (error) {
        //Update the form status
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    duplicate() {
      //Navigate to new record
      this.$router.push({
        name: "unit-edit",
        params: {
          recordid: 0,
          obj: this.obj
        }
      });
    },

    AddressCopyPhysicalToClipBoard() {
      let vm = this;
      let ret = "";
      if (vm.obj.name) {
        ret += vm.obj.name + "\n";
      }
      if (vm.obj.address) {
        ret += vm.obj.address + "\n";
      }

      if (vm.obj.city) {
        ret += vm.obj.city + " ";
      }

      if (vm.obj.region) {
        ret += vm.obj.region + " ";
      }

      if (vm.obj.country) {
        ret += vm.obj.country + "\n";
      }
      window.$gz.util.copyToClipboard(ret);
    },
    async GeoCapture() {
      let vm = this;
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        let loc = await window.$gz.util.getGeoLocation();
        vm.obj.latitude = loc.latitude;
        vm.fieldValueChanged("latitude");
        vm.obj.longitude = loc.longitude;
        vm.fieldValueChanged("longitude");
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      }
    }

    //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 "delete":
        m.vm.remove();
        break;
      case "new":
        m.vm.$router.push({
          name: "unit-edit",
          params: { recordid: 0 }
        });
        break;
      case "duplicate":
        m.vm.duplicate();
        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.Unit }
          });
        } else {
          //general report selector chosen

          let res = await m.vm.$refs.reportSelector.open({
            AType: window.$gz.type.Unit,
            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.Unit }
          });
        }
        break;

      case "geoview":
        window.$gz.util.viewGeoLocation({
          latitude: m.vm.obj.latitude,
          longitude: m.vm.obj.longitude,
          address: m.vm.obj.address || m.vm.obj.postAddress,
          city: m.vm.obj.city || m.vm.obj.postCity,
          region: m.vm.obj.region || m.vm.obj.postRegion,
          country: m.vm.obj.country || m.vm.obj.postCountry,
          postCode: m.vm.obj.postCode
        });
        break;
      case "WorkOrderItemUnitList":
        m.vm.$router.push({
          name: "svc-workorder-item-units",
          params: {
            aType: m.vm.ayaType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.serial
          }
        });
        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: "$ayiFan",
    title: "Unit",
    helpUrl: "svc-units",
    formData: {
      ayaType: window.$gz.type.Unit,
      recordId: vm.$route.params.recordid,
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      recordName: vm.obj.serial
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  if (vm.rights.delete && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Delete",
      icon: "$ayiTrashAlt",
      surface: false,
      key: FORM_KEY + ":delete",
      vm: vm
    });
  }

  //REPORTS
  //Report not Print, print is a further option
  menuOptions.menuItems.push({
    title: "Report",
    icon: "$ayiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  //get last report selected
  let lastReport = window.$gz.form.getLastReport(FORM_KEY);
  if (lastReport != null) {
    menuOptions.menuItems.push({
      title: lastReport.name,
      icon: "$ayiFileAlt",
      key: FORM_KEY + ":report:" + lastReport.id,
      vm: vm
    });
  }

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "New",
      icon: "$ayiPlus",
      key: FORM_KEY + ":new",
      vm: vm
    });
  }

  if (vm.rights.change && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Duplicate",
      icon: "$ayiClone",
      key: FORM_KEY + ":duplicate",
      vm: vm
    });
  }

  menuOptions.menuItems.push({ divider: true, inset: false });

  menuOptions.menuItems.push({
    title: "UnitModels",
    icon: "$ayiDiceD20",
    data: "svc-unit-models",
    key: "app:nav"
  });

  //---- SHOW ALL ---

  menuOptions.menuItems.push({
    title: "WorkOrderList", //note: technically it opens teh woitemunitlist not workorders but it's confusing in the UI otherwise and this is how people would think about it
    icon: "$ayiTools",
    key: FORM_KEY + ":WorkOrderItemUnitList",
    vm: vm
  });

  //MIGRATE_OUTSTANDING show all: workorderlist, unitlist, quotelist, pmlist

  menuOptions.menuItems.push({
    title: "QuoteList",
    icon: "$ayiPencilAlt",
    key: FORM_KEY + ":QuoteList",
    vm: vm
  });

  menuOptions.menuItems.push({
    title: "PMList",
    icon: "$ayiBusinessTime",
    key: FORM_KEY + ":PMList",
    vm: vm
  });
  //--- /show all ---

  menuOptions.menuItems.push({
    title: "GeoView",
    icon: "$ayiMapMarked",
    key: FORM_KEY + ":geoview",
    vm: vm
  });

  menuOptions.menuItems.push({ divider: true, inset: false });

  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([
    "Unit",
    "UnitSerial",
    "UnitNotes",
    "Customer",
    "UnitParentUnitID",
    "UnitModel",
    "UnitUnitHasOwnAddress",
    "UnitBoughtHere",
    "UnitPurchaseFromID",
    "UnitReceipt",
    "UnitPurchasedDate",
    "UnitDescription",
    "UnitReplacedByUnitID",
    "UnitOverrideWarranty",
    "UnitOverrideLength",
    "UnitOverrideWarrantyTerms",
    "UsesBanking",
    "Contract",
    "ContractExpires",
    "UnitMetered",
    "UnitOverrideLifeTime",
    "UnitText1",
    "UnitText2",
    "UnitText3",
    "UnitText4",
    "AddressTypePhysical",
    "Address",
    "AddressDeliveryAddress",
    "AddressCity",
    "AddressStateProv",
    "AddressCountry",
    "AddressLatitude",
    "AddressLongitude",
    "UnitCustom1",
    "UnitCustom2",
    "UnitCustom3",
    "UnitCustom4",
    "UnitCustom5",
    "UnitCustom6",
    "UnitCustom7",
    "UnitCustom8",
    "UnitCustom9",
    "UnitCustom10",
    "UnitCustom11",
    "UnitCustom12",
    "UnitCustom13",
    "UnitCustom14",
    "UnitCustom15",
    "UnitCustom16"
  ]);
}
</script>
