<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 v-model="tab" mobile-breakpoint="100" @change="tabChanged">
          <v-tab>{{ $sock.t("Customer") }}</v-tab>
          <v-tab>{{ $sock.t("Address") }}</v-tab>
          <v-tab>{{ $sock.t("Contacts") }}</v-tab>
          <v-tabs-items v-model="tab">
            <v-tab-item class="mt-4 ml-2">
              <v-row dense>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    ref="name"
                    v-model="obj.name"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('CustomerName')"
                    :rules="[form().required(this, 'name')]"
                    :error-messages="form().serverErrors(this, 'name')"
                    data-cy="name"
                    @input="fieldValueChanged('name')"
                  ></v-text-field>
                </v-col>
                <v-col
                  v-if="form().showMe(this, 'DatabaseID')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    ref="dbId"
                    v-model="obj.dbId"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('DatabaseID')"
                    data-cy="dbId"
                    :error-messages="form().serverErrors(this, 'dbId')"
                    @input="fieldValueChanged('dbId')"
                  ></v-text-field>
                </v-col>
                <v-col
                  v-if="form().showMe(this, 'AccountNumber')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    ref="accountNumber"
                    v-model="obj.accountNumber"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('CustomerAccountNumber')"
                    data-cy="accountNumber"
                    :error-messages="form().serverErrors(this, 'accountNumber')"
                    @input="fieldValueChanged('accountNumber')"
                  ></v-text-field>
                </v-col>

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

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

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

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

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

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

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

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

                <v-col
                  v-if="form().showMe(this, 'HeadOfficeId')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <gz-pick-list
                    ref="headOfficeId"
                    v-model="obj.headOfficeId"
                    :aya-type="sockTypes().HeadOffice"
                    show-edit-icon
                    :readonly="formState.readOnly"
                    :label="$sock.t('HeadOffice')"
                    data-cy="headOfficeId"
                    :error-messages="form().serverErrors(this, 'headOfficeId')"
                    @input="fieldValueChanged('headOfficeId')"
                  ></gz-pick-list>
                </v-col>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-checkbox
                    ref="doNotContact"
                    v-model="obj.doNotContact"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('DoNotContact')"
                    data-cy="doNotContact"
                    :error-messages="form().serverErrors(this, 'doNotContact')"
                    @change="fieldValueChanged('doNotContact')"
                  ></v-checkbox>
                </v-col>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-checkbox
                    ref="active"
                    v-model="obj.active"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('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
                    ref="notes"
                    v-model="obj.notes"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('CustomerNotes')"
                    :error-messages="form().serverErrors(this, 'notes')"
                    data-cy="notes"
                    auto-grow
                    @input="fieldValueChanged('notes')"
                  ></v-textarea>
                </v-col>

                <v-col
                  v-if="form().showMe(this, 'CustomerAlertNotes')"
                  cols="12"
                >
                  <v-textarea
                    ref="alertNotes"
                    v-model="obj.alertNotes"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('CustomerAlertNotes')"
                    :error-messages="form().serverErrors(this, 'alertNotes')"
                    data-cy="alertNotes"
                    auto-grow
                    prepend-icon="$sockiInfoCircle"
                    color="primary"
                    @input="fieldValueChanged('alertNotes')"
                  ></v-textarea>
                </v-col>

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

                <v-col cols="12">
                  <gz-custom-fields
                    ref="customFields"
                    v-model="obj.customFields"
                    :form-key="formCustomTemplateKey"
                    :readonly="formState.readOnly"
                    :parent-v-m="this"
                    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
                    ref="wiki"
                    v-model="obj.wiki"
                    :aya-type="sockType"
                    :aya-id="obj.id"
                    :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="sockType"
                    :aya-id="obj.id"
                  ></gz-attachments
                ></v-col>
              </v-row>
            </v-tab-item>
            <v-tab-item class="mt-4 ml-2">
              <v-row dense>
                <v-col cols="12">
                  <v-menu v-if="rights.change" offset-y>
                    <template v-slot:activator="{ on, attrs }">
                      <span class="text-h6">
                        {{ $sock.t("AddressTypePhysical") }}</span
                      ><v-btn icon v-bind="attrs" v-on="on">
                        <v-icon small>$sockiEllipsisV</v-icon>
                      </v-btn>
                    </template>
                    <v-list>
                      <v-list-item @click="AddressCopyPhysicalToClipBoard()">
                        <v-list-item-icon>
                          <v-icon>$sockiCopy</v-icon>
                        </v-list-item-icon>
                        <v-list-item-title>{{
                          $sock.t("CopyToClipboard")
                        }}</v-list-item-title>
                      </v-list-item>
                      <v-list-item @click="AddressCopyToPostal">
                        <v-list-item-icon>
                          <v-icon>$sockiClone</v-icon>
                        </v-list-item-icon>
                        <v-list-item-title>{{
                          $sock.t("AddressCopyToPostal")
                        }}</v-list-item-title>
                      </v-list-item>
                      <v-list-item @click="GeoCapture">
                        <v-list-item-icon>
                          <v-icon>$sockiMapMarker</v-icon>
                        </v-list-item-icon>
                        <v-list-item-title>{{
                          $sock.t("GeoCapture")
                        }}</v-list-item-title>
                      </v-list-item>
                    </v-list>
                  </v-menu>
                  <span v-else class="text-h6">
                    {{ $sock.t("AddressTypePhysical") }}</span
                  >
                </v-col>
                <v-col
                  v-if="form().showMe(this, 'Address')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    ref="address"
                    v-model="obj.address"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('AddressDeliveryAddress')"
                    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')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    ref="city"
                    v-model="obj.city"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('AddressCity')"
                    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')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    ref="region"
                    v-model="obj.region"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('AddressStateProv')"
                    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')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    ref="country"
                    v-model="obj.country"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('AddressCountry')"
                    data-cy="country"
                    :error-messages="form().serverErrors(this, 'country')"
                    @input="fieldValueChanged('country')"
                  ></v-text-field>
                </v-col>

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

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

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

                <v-col cols="12">
                  <v-menu v-if="rights.change" offset-y>
                    <template v-slot:activator="{ on, attrs }">
                      <span class="text-h6">
                        {{ $sock.t("AddressTypePostal") }}</span
                      ><v-btn icon v-bind="attrs" v-on="on">
                        <v-icon small>$sockiEllipsisV</v-icon>
                      </v-btn>
                    </template>
                    <v-list>
                      <v-list-item @click="AddressCopyPostalToClipBoard()">
                        <v-list-item-icon>
                          <v-icon>$sockiCopy</v-icon>
                        </v-list-item-icon>
                        <v-list-item-title>{{
                          $sock.t("CopyToClipboard")
                        }}</v-list-item-title>
                      </v-list-item>
                      <v-list-item @click="AddressCopyToPhysical">
                        <v-list-item-icon>
                          <v-icon>$sockiClone</v-icon>
                        </v-list-item-icon>
                        <v-list-item-title>{{
                          $sock.t("AddressCopyToPhysical")
                        }}</v-list-item-title>
                      </v-list-item>
                    </v-list>
                  </v-menu>
                  <span v-else class="text-h6">
                    {{ $sock.t("AddressTypePostal") }}</span
                  >
                </v-col>

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

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

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

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

                <v-col
                  v-if="form().showMe(this, 'PostCode')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    ref="postCode"
                    v-model="obj.postCode"
                    dense
                    :readonly="formState.readOnly"
                    :label="$sock.t('AddressPostalPostal')"
                    data-cy="postCode"
                    :error-messages="form().serverErrors(this, 'postCode')"
                    @input="fieldValueChanged('postCode')"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-tab-item>
            <v-tab-item class="mt-4 ml-2">
              <v-row dense>
                <v-col cols="12">
                  <v-data-table
                    v-model="selected"
                    dense
                    :headers="headers"
                    :items="contactsObj"
                    class="elevation-1"
                    :disable-pagination="true"
                    :disable-filtering="true"
                    hide-default-footer
                    :sort-by="['name']"
                    :show-select="false"
                    :header-props="{ sortByText: $sock.t('Sort') }"
                    data-cy="custUsersTable"
                    :no-data-text="$sock.t('NoData')"
                    @click:row="contactsRowClick"
                  >
                    <template v-slot:[`item.active`]="{ item }">
                      <v-simple-checkbox
                        v-model="item.active"
                        disabled
                      ></v-simple-checkbox>
                    </template>

                    <template v-slot:top>
                      <div class="text-right mb-6">
                        <v-btn
                          :disabled="obj.id == 0"
                          @click="contactsGetDataFromApi"
                        >
                          <v-icon data-cy="refresh">$sockiSync</v-icon>
                        </v-btn>
                        <v-btn
                          class="ml-12"
                          :disabled="obj.id == 0 || formState.readOnly"
                          @click="addContact"
                        >
                          <v-icon data-cy="add">$sockiPlus</v-icon>
                        </v-btn>
                      </div>
                    </template>
                  </v-data-table>
                </v-col>
              </v-row>
            </v-tab-item>
          </v-tabs-items>
        </v-tabs>
      </v-form>
    </div>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
  </div>
</template>
<script>
const FORM_KEY = "customer-edit";
const API_BASE_URL = "customer/";
const FORM_CUSTOM_TEMPLATE_KEY = "Customer";
export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      selectLists: {
        usertypes: []
      },
      obj: {
        id: 0,
        concurrency: 0,
        name: undefined,
        dbId: null,
        active: true,
        doNotContact: false,
        notes: null,
        wiki: null,
        customFields: "{}",
        tags: [],
        webAddress: null,
        alertNotes: null,
        billHeadOffice: false,
        headOfficeId: null,
        accountNumber: null,
        phone1: null,
        phone2: null,
        phone3: null,
        phone4: null,
        phone5: null,
        emailAddress: null,
        postAddress: null,
        postCity: null,
        postRegion: null,
        postCountry: null,
        postCode: null,
        address: null,
        city: null,
        region: null,
        country: null,
        addressPostal: 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(),
      sockType: window.$gz.type.Customer,
      contactsObj: [],
      hasFetchedContacts: false,
      headers: [],
      selected: [],
      availableRoles: [],
      timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
      languageName: window.$gz.locale.getResolvedLanguage(),
      hour12: window.$gz.locale.getHour12()
    };
  },
  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;
    let completelyNew = false;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(window.$gz.type.Customer);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      let setDirty = false;
      //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);
        }
      } 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.name = `${this.obj.name} - ${window.$gz.translation.get(
            "Copy"
          )}`;
          setDirty = true;
        } else {
          completelyNew = true;
        }
      }
      window.$gz.form.setFormState({
        vm: vm,
        loading: false,
        dirty: setDirty,
        valid: true
      });
      generateMenu(vm);
    } catch (error) {
      window.$gz.errorHandler.handleFormError(error, vm);
    } finally {
      vm.formState.ready = true;
      if (completelyNew) {
        //completely new record pre-break name rule so it shows as required
        //trigger rule breaking / validation
        this.$nextTick(() => {
          this.obj.name = null;
          this.fieldValueChanged(`name`);
        });
      }
    }
  },
  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);
  },
  methods: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: function() {
      return this.formState.valid && !this.formState.dirty;
    },
    sockTypes: 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) {
      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,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    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 {
          if (res.data.id) {
            //POST
            vm.obj = res.data;
            this.$router.replace({
              name: "customer-edit",
              params: {
                recordid: res.data.id,
                obj: res.data
              }
            });
          } else {
            //PUT
            vm.obj.concurrency = res.data.concurrency;
          }
          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() {
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        window.$gz.form.setFormState({
          vm: this,
          loading: true
        });
        if (this.$route.params.recordid == 0) {
          JUST_DELETED = true;
          this.$router.go(-1);
        } else {
          window.$gz.form.deleteAllErrorBoxErrors(this);
          const res = await window.$gz.api.remove(
            API_BASE_URL + this.$route.params.recordid
          );
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            JUST_DELETED = true;
            this.$router.go(-1);
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    },
    duplicate() {
      this.$router.push({
        name: "customer-edit",
        params: {
          recordid: 0,
          obj: this.obj
        }
      });
    },
    tabChanged: async function(tab) {
      if (tab == 2) {
        //contacts tab, load contacts if not done already
        if (!this.hasFetchedContacts) {
          await this.contactsGetDataFromApi();
        }
      }
    },
    addContact() {
      if (this.obj.id == 0) {
        return;
      }
      this.$router.push({
        name: "cust-user",
        params: { recordid: 0, customerid: this.obj.id }
      });
    },
    contactsRowClick(item) {
      window.$gz.eventBus.$emit("openobject", {
        type: window.$gz.type.User,
        id: item.id,
        inside: false
      });
    },
    rolesDisplayFromRoles(roles) {
      const roleNames = [];
      if (roles != null && roles != 0) {
        for (let i = 0; i < this.availableRoles.length; i++) {
          const role = this.availableRoles[i];
          if (roles & role.id) {
            roleNames.push(role.name);
          }
        }
      }
      return roleNames.join(", ");
    },
    async contactsGetDataFromApi() {
      const vm = this;
      vm.formState.loading = true;

      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get(
          `user/customer-contacts/${vm.obj.id}`
        );
        vm.hasFetchedContacts = true;
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data) {
            const ret = [];
            for (let i = 0; i < res.data.length; i++) {
              const o = res.data[i];
              ret.push({
                id: o.id,
                name: o.name,
                emailAddress: o.emailAddress,
                phone1: o.phone1,
                phone2: o.phone2,
                phone3: o.phone3,
                active: o.active,
                lastLogin: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
                  o.lastLogin,
                  this.timeZoneName,
                  this.languageName,
                  this.hour12
                )
              });
            }
            vm.contactsObj = ret;
          } else {
            vm.rawObj = [];
            vm.contactsObj = [];
          }
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          generateMenu(vm);
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    AddressCopyToPostal() {
      const vm = this;
      vm.obj.postAddress = vm.obj.address;
      vm.obj.postCity = vm.obj.city;
      vm.obj.postRegion = vm.obj.region;
      vm.obj.postCountry = vm.obj.country;
      this.formState.dirty = true;
    },
    AddressCopyToPhysical() {
      const vm = this;
      vm.obj.address = vm.obj.postAddress;
      vm.obj.city = vm.obj.postCity;
      vm.obj.region = vm.obj.postRegion;
      vm.obj.country = vm.obj.postCountry;
      this.formState.dirty = true;
    },
    AddressCopyPhysicalToClipBoard() {
      const 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";
      }

      if (vm.obj.addressPostal) {
        //Postal codes should have two spaces before them according to regs.
        ret += "  " + vm.obj.addressPostal + "\n";
      }

      window.$gz.util.copyToClipboard(ret);
    },
    AddressCopyPostalToClipBoard() {
      const vm = this;
      let ret = "";
      if (vm.obj.name) {
        ret += vm.obj.name + "\n";
      }
      if (vm.obj.postAddress) {
        ret += vm.obj.postAddress + "\n";
      }

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

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

      if (vm.obj.postCode) {
        //Postal codes should have two spaces before them according to regs.
        ret += "  " + vm.obj.postCode + "\n";
      }

      if (vm.obj.postCountry) {
        ret += vm.obj.postCountry + "\n";
      }
      window.$gz.util.copyToClipboard(ret);
    },
    async GeoCapture() {
      const vm = this;
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const 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);
      }
    }
  }
};

/////////////////////////////
//
//
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 "delete":
        m.vm.remove();
        break;
      case "new":
        m.vm.$router.push({
          name: "customer-edit",
          params: { recordid: 0 }
        });
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      case "report":
        {
          const res = await m.vm.$refs.reportSelector.open(
            {
              SockType: window.$gz.type.Customer,
              selectedRowIds: [m.vm.obj.id]
            },
            m.id
          );
          if (res == null) {
            return;
          }
          window.$gz.form.setLastReportMenuItem(FORM_KEY, res, m.vm);
        }
        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,
          addressPostal: m.vm.obj.addressPostal
        });
        break;
      case "CustomerNoteList":
        m.vm.$router.push({
          name: "customer-notes",
          params: { customerid: m.vm.obj.id, customername: m.vm.obj.name }
        });
        break;
      case "SubscriptionList":
        m.vm.$router.push({
          name: "biz-subscription-list",
          params: {
            aType: m.vm.sockType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.name
          }
        });
        break;
      case "PurchaseList":
        m.vm.$router.push({
          name: "biz-purchase-list",
          params: {
            aType: m.vm.sockType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.name
          }
        });
        break;
      case "LicenseList":
        m.vm.$router.push({
          name: "biz-license-list",
          params: {
            aType: m.vm.sockType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.name
          }
        });
        break;
      case "SubscriptionServerList":
        m.vm.$router.push({
          name: "biz-subscription-server-list",
          params: {
            aType: m.vm.sockType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.name
          }
        });
        break;
      case "GZCaseList":
        m.vm.$router.push({
          name: "biz-gzcase-list",
          params: {
            aType: m.vm.sockType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.name
          }
        });
        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: "$sockiAddressCard",
    title: "Customer",
    helpUrl: "customers",
    formData: {
      sockType: window.$gz.type.Customer,
      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: "$sockiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  menuOptions.menuItems.push({
    title: "Report",
    icon: "$sockiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  const lastReport = window.$gz.form.getLastReport(FORM_KEY);
  if (lastReport != null) {
    menuOptions.menuItems.push({
      title: lastReport.name,
      notrans: true,
      icon: "$sockiFileAlt",
      key: FORM_KEY + ":report:" + lastReport.id,
      vm: vm
    });
  }

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

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

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

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

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

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

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

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

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

  //---- SHOW ALL ---

  menuOptions.menuItems.push({
    title: "GeoView",
    icon: "$sockiMapMarked",
    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();
  await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY, vm);
  await createTableHeaders(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "Customer",
    "CustomerName",
    "CustomerNotes",
    "WebAddress",
    "CustomerAlertNotes",
    "CustomerBillHeadOffice",
    "HeadOffice",
    "CustomerTechNotes",
    "CustomerAccountNumber",
    "CustomerPhone1",
    "CustomerPhone2",
    "CustomerPhone3",
    "CustomerPhone4",
    "CustomerPhone5",
    "CustomerEmail",
    "AddressTypePhysical",
    "AddressTypePostal",
    "AddressCopyToPostal",
    "AddressCopyToPhysical",
    "Address",
    "AddressPostalDeliveryAddress",
    "AddressPostalCity",
    "AddressPostalStateProv",
    "AddressPostalCountry",
    "AddressPostalPostal",
    "AddressDeliveryAddress",
    "AddressCity",
    "AddressStateProv",
    "AddressCountry",
    "AddressPostal",
    "AddressLatitude",
    "AddressLongitude",
    "CustomerCustom1",
    "CustomerCustom2",
    "CustomerCustom3",
    "CustomerCustom4",
    "CustomerCustom5",
    "CustomerCustom6",
    "CustomerCustom7",
    "CustomerCustom8",
    "CustomerCustom9",
    "CustomerCustom10",
    "CustomerCustom11",
    "CustomerCustom12",
    "CustomerCustom13",
    "CustomerCustom14",
    "CustomerCustom15",
    "CustomerCustom16",
    "UserEmailAddress",
    "UserPhone1",
    "UserPhone2",
    "UserPageAddress",
    "Contact",
    "LastLogin",
    "CustomerNoteList",
    "CustomerNoteNotes",
    "CustomerNoteNoteDate",
    "DoNotContact",
    "DatabaseID"
  ]);
}

//////////////////////
//
//
async function createTableHeaders(vm) {
  vm.headers = [
    { text: vm.$sock.t("Contact"), value: "name" },
    { text: vm.$sock.t("UserEmailAddress"), value: "emailAddress" },
    { text: vm.$sock.t("UserPhone1"), value: "phone1" },
    { text: vm.$sock.t("UserPhone2"), value: "phone2" },
    { text: vm.$sock.t("UserPageAddress"), value: "phone3" },
    { text: vm.$sock.t("Active"), value: "active" },
    { text: vm.$sock.t("LastLogin"), value: "lastLogin" }
  ];
}
</script>
