<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">
          <v-tab>{{ $ay.t("Contact") }}</v-tab>
          <v-tab>{{ $ay.t("UserSettings") }}</v-tab>
          <v-tabs-items v-model="tab">
            <v-tab-item class="mt-4 ml-2">
              <v-row dense>
                <v-col
                  v-if="form().showMe(this, 'customerId') && obj.userType == 3"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <gz-pick-list
                    ref="customerId"
                    v-model="obj.customerId"
                    :aya-type="ayaTypes().Customer"
                    show-edit-icon
                    :include-inactive="true"
                    :readonly="true"
                    :disabled="true"
                    :label="$ay.t('Customer')"
                    data-cy="customerId"
                    :error-messages="form().serverErrors(this, 'customerId')"
                    @input="fieldValueChanged('customerId')"
                  ></gz-pick-list>
                </v-col>

                <v-col
                  v-if="
                    form().showMe(this, 'headOfficeId') && obj.userType == 4
                  "
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <gz-pick-list
                    ref="headOfficeId"
                    v-model="obj.headOfficeId"
                    :aya-type="ayaTypes().HeadOffice"
                    show-edit-icon
                    :include-inactive="true"
                    :readonly="true"
                    :disabled="true"
                    :label="$ay.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-text-field
                    ref="name"
                    v-model="obj.name"
                    dense
                    :readonly="formState.readOnly"
                    :label="$ay.t('Name')"
                    :rules="[form().required(this, 'name')]"
                    :error-messages="form().serverErrors(this, 'name')"
                    data-cy="name"
                    @input="fieldValueChanged('name')"
                  ></v-text-field>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-role-picker
                    ref="roles"
                    v-model="obj.roles"
                    :label="$ay.t('AuthorizationRoles')"
                    :readonly="formState.readOnly"
                    data-cy="roles"
                    :error-messages="form().serverErrors(this, 'roles')"
                    limit-selection-to="outside"
                    @input="fieldValueChanged('roles')"
                  ></gz-role-picker>
                </v-col>

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

                <v-col v-if="obj.allowLogin" cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    id="username"
                    ref="login"
                    v-model="login"
                    dense
                    name="username"
                    :readonly="formState.readOnly"
                    prepend-icon="$ayiUser"
                    autocomplete="off"
                    autocorrect="off"
                    autocapitalize="off"
                    spellcheck="false"
                    :label="$ay.t('NewLogin')"
                    :error-messages="form().serverErrors(this, 'login')"
                    @input="fieldValueChanged('login')"
                  ></v-text-field>
                </v-col>

                <v-col v-if="obj.allowLogin" cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    id="password"
                    ref="password"
                    v-model="password"
                    dense
                    name="password"
                    :readonly="formState.readOnly"
                    :append-outer-icon="reveal ? '$ayiEye' : '$ayiEyeSlash'"
                    prepend-icon="$ayiKey"
                    :label="$ay.t('NewPassword')"
                    :type="reveal ? 'text' : 'password'"
                    :error-messages="form().serverErrors(this, 'password')"
                    @input="fieldValueChanged('password')"
                    @click:append-outer="reveal = !reveal"
                  ></v-text-field>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-date-time-picker
                    ref="lastLogin"
                    v-model="obj.lastLogin"
                    :label="$ay.t('LastLogin')"
                    readonly
                    data-cy="lastLogin"
                  ></gz-date-time-picker>
                </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="$ay.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="$ay.t('UserNotes')"
                    :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, '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="ayaType"
                    :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="ayaType"
                    :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" sm="6" lg="4" xl="3">
                  <v-select
                    ref="translationId"
                    v-model="optionsObj.translationId"
                    dense
                    :items="selectLists.translations"
                    item-text="name"
                    item-value="id"
                    :readonly="formState.readOnly"
                    :label="$ay.t('Translation')"
                    :error-messages="form().serverErrors(this, 'translationId')"
                    @input="fieldValueChanged('translationId')"
                  ></v-select>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-email
                    ref="emailAddress"
                    v-model="optionsObj.emailAddress"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UserEmailAddress')"
                    :error-messages="form().serverErrors(this, 'emailAddress')"
                    data-cy="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="optionsObj.phone1"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UserPhone1')"
                    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="optionsObj.phone2"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UserPhone2')"
                    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="optionsObj.phone3"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UserPageAddress')"
                    data-cy="phone3"
                    :error-messages="form().serverErrors(this, 'phone3')"
                    @input="fieldValueChanged('phone3')"
                  ></gz-phone>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    ref="mapUrlTemplate"
                    v-model="optionsObj.mapUrlTemplate"
                    dense
                    :readonly="formState.readOnly"
                    :label="$ay.t('MapUrlTemplate')"
                    :error-messages="
                      form().serverErrors(this, 'mapUrlTemplate')
                    "
                    data-cy="mapUrlTemplate"
                    :hint="obj.mapUrlTemplate == null ? 'Google maps' : ''"
                    persistent-hint
                    @input="fieldValueChanged('mapUrlTemplate')"
                  ></v-text-field>
                  <v-select
                    dense
                    :items="selectLists.mapUrls"
                    item-text="name"
                    item-value="value"
                    @input="mapUrlSelectionChanged"
                  ></v-select>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-checkbox
                    ref="hour12"
                    v-model="optionsObj.hour12"
                    dense
                    :readonly="formState.readOnly"
                    :label="$ay.t('Hour12')"
                    :error-messages="form().serverErrors(this, 'hour12')"
                    @change="fieldValueChanged('hour12')"
                  ></v-checkbox>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    ref="currencyName"
                    v-model="optionsObj.currencyName"
                    dense
                    :hint="
                      optionsObj.currencyName == null ||
                      optionsObj.currencyName == ''
                        ? locale().getCurrencyName()
                        : ''
                    "
                    persistent-hint
                    :readonly="formState.readOnly"
                    :label="$ay.t('CurrencyCode')"
                    :error-messages="form().serverErrors(this, 'currencyName')"
                    append-outer-icon="$ayiQuestionCircle"
                    @input="fieldValueChanged('currencyName')"
                    @click:append-outer="goHelp()"
                  ></v-text-field>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    ref="languageOverride"
                    v-model="optionsObj.languageOverride"
                    dense
                    :hint="locale().getResolvedLanguage()"
                    persistent-hint
                    :readonly="formState.readOnly"
                    :label="$ay.t('LanguageCode')"
                    :error-messages="
                      form().serverErrors(this, 'languageOverride')
                    "
                    append-outer-icon="$ayiQuestionCircle"
                    @input="fieldValueChanged('languageOverride')"
                    @click:append-outer="goHelp()"
                  ></v-text-field>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    ref="timeZoneOverride"
                    v-model="optionsObj.timeZoneOverride"
                    dense
                    :hint="locale().getResolvedTimeZoneName()"
                    persistent-hint
                    :readonly="formState.readOnly"
                    :label="$ay.t('TimeZone')"
                    :error-messages="
                      form().serverErrors(this, 'timeZoneOverride')
                    "
                    append-outer-icon="$ayiQuestionCircle"
                    @input="fieldValueChanged('timeZoneOverride')"
                    @click:append-outer="goHelp()"
                  ></v-text-field>
                </v-col>
                <!-- 
                <v-col cols="12" sm="6" lg="4" xl="3">
             
                  <span class="text-caption">
                    {{ $ay.t("UserColor") }}
                  </span>
                  <v-color-picker
                    v-model="optionsObj.uiColor"
                    :readonly="formState.readOnly"
                    hide-mode-switch
                    mode="hexa"
                    :error-messages="form().serverErrors(this, 'uiColor')"
                    ref="uiColor"
                    @input="fieldValueChanged('uiColor')"
                  ></v-color-picker>
                </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 = "contact-edit";
const API_BASE_URL = "user/";
const FORM_CUSTOM_TEMPLATE_KEY = "Contact"; //<--- deliberately not 'User' as is customary as this is it's own form but also edit's User type objects so needs it's own customization key

export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      selectLists: {
        usertypes: [],
        translations: [],
        mapUrls: window.$gz.util.mapProviderUrls()
      },
      obj: {
        id: 0,
        concurrency: 0,
        active: true,
        allowLogin: false,
        name: null,
        roles: 2048,
        userType: 3,
        employeeNumber: null,
        notes: null,
        customerId: null,
        headOfficeId: null,
        vendorId: null,
        wiki: null,
        customFields: "{}",
        tags: [],
        lastLogin: null
      },
      optionsObj: {
        id: 0,
        concurrency: 0,
        emailAddress: null,
        phone1: null,
        phone2: null,
        phone3: null,
        mapUrlTemplate: null,
        //uiColor: "#000000ff",
        languageOverride: null,
        timeZoneOverride: null,
        currencyName: "USD",
        hour12: true,
        translationId: 1
      },
      login: null,
      password: null,
      reveal: true,
      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.User
    };
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        if (val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
        if (!val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit(
            "menu-enable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":new");
        } else {
          window.$gz.eventBus.$emit(
            "menu-disable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":new");
        }
      },
      deep: true
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      //## NOTE: This is a Contact form so follows Customer rights even  though User object
      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;
          this.optionsObj = this.$route.params.optionsObj;
        } 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.optionsObj = this.$route.params.optionsObj;
          this.obj.concurrency = undefined;
          this.optionsObj.concurrency = undefined;
          this.obj.id = 0;
          this.optionsObj.id = 0;
          this.obj.name = `${this.obj.name} - ${window.$gz.translation.get(
            "Copy"
          )}`;
          this.password = window.$gz.util.getRandomPassword();
          setDirty = true;
        } else {
          vm.password = window.$gz.util.getRandomPassword();
          if (vm.$route.params.customerid && vm.$route.params.customerid != 0) {
            vm.obj.customerId = vm.$route.params.customerid;
            vm.obj.userType = 3;
          } else if (
            vm.$route.params.headofficeid &&
            vm.$route.params.headofficeid != 0
          ) {
            vm.obj.headOfficeId = vm.$route.params.headofficeid;
            vm.obj.userType = 4;
          } else {
            //no customer or headoffice id, can't proceed
            vm.$router.go(-1);
          }
        }
      }
      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;
    }
  },
  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: {
    goHelp() {
      window.open(window.$gz.api.helpUrl() + "ay-start-localization", "_blank");
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: function() {
      return this.formState.valid && !this.formState.dirty;
    },
    ayaTypes: function() {
      return window.$gz.type;
    },
    translation() {
      return window.$gz.translation;
    },
    locale() {
      return window.$gz.locale;
    },
    mapUrlSelectionChanged(val) {
      this.optionsObj.mapUrlTemplate = val;
      this.fieldValueChanged("mapUrlTemplate");
    },
    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;
      vm.formState.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);
          vm.formState.loading = false;
        } else {
          vm.obj = res.data;
          generateMenu(vm);
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          await vm.getUserOptionsDataFromApi();
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
        vm.formState.loading = false;
      }
    },
    async submit() {
      const vm = this;
      if (vm.canSave == false) {
        return;
      }
      try {
        vm.formState.loading = true;
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        //add in password and login if changed
        if (vm.password != null && vm.password != "") {
          vm.obj.password = vm.password;
        }
        if (vm.login != null && vm.login != "") {
          vm.obj.login = vm.login;
        }
        if (vm.obj.roles == null) {
          vm.obj.roles = 0;
        }
        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;
            vm.optionsObj.userId = res.data.id;
            await vm.submitOptions();
            this.$router.replace({
              name: "cust-user",
              params: {
                recordid: res.data.id,
                obj: res.data,
                optionsObj: vm.optionsObj
              }
            });
          } else {
            //PUT
            vm.obj.concurrency = res.data.concurrency;
            await vm.submitOptions();
          }
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true
          });
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        vm.formState.loading = false;
      }
    },
    async remove() {
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
        this.formState.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 (ex) {
        window.$gz.errorHandler.handleFormError(ex, this);
      } finally {
        this.formState.loading = false;
      }
    },
    duplicate() {
      this.$router.push({
        name: "cust-user",
        params: {
          recordid: 0,
          obj: this.obj,
          optionsObj: this.optionsObj
        }
      });
    },
    async getUserOptionsDataFromApi() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get(`user-option/${vm.obj.id}`);
        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.optionsObj = res.data;
          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);
      }
    },
    async submitOptions() {
      const vm = this;
      if (vm.canSave) {
        vm.formState.loading = true;
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        try {
          const res = await window.$gz.api.put(
            `user-option/${vm.obj.id}`,
            vm.optionsObj
          );
          vm.formState.loading = false;
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            //UserOptions is never a POST as it always exists and can't be deleted so always a PUT
            vm.optionsObj.concurrency = res.data.concurrency;
            window.$gz.form.setFormState({
              vm: vm,
              dirty: false
            });
          }
        } catch (error) {
          vm.formState.loading = false;
          window.$gz.errorHandler.handleFormError(error, vm);
        }
      }
    },
    async sendResetCode() {
      const vm = this;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.post(
          `auth/request-reset-password/${vm.obj.id}`,
          null
        );
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj.concurrency = res.data.concurrency;
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async disableTfa() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.post(`auth/totp-disable/${vm.obj.id}`);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          await window.$gz.dialog.displayLTModalNotificationMessage(
            "AuthTwoFactorDisabled"
          );
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        vm.loading = false;
      }
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      case "report":
        {
          const res = await m.vm.$refs.reportSelector.open(
            {
              AType: window.$gz.type.User,
              selectedRowIds: [m.vm.obj.id]
            },
            m.id
          );
          if (res == null) {
            return;
          }
          window.$gz.form.setLastReportMenuItem(FORM_KEY, res, m.vm);
        }
        break;
      case "directnotify":
        //nav to direct notify with list of users appended to route
        if (m.vm.obj.id == 0) {
          m.vm.$router.push({
            name: "home-notify-direct"
          });
        } else {
          m.vm.$router.push({
            name: "home-notify-direct",
            params: { userIdList: m.vm.obj.id }
          });
        }
        break;
      case "sendreset":
        m.vm.sendResetCode();
        break;
      case "disable2fa":
        m.vm.disableTfa();
        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: "$ayiUser",
    title: "Contact",
    helpUrl: "cust-contacts",
    formData: {
      ayaType: window.$gz.type.User,
      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: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  menuOptions.menuItems.push({
    title: "Report",
    icon: "$ayiFileAlt",
    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: "$ayiFileAlt",
      key: FORM_KEY + ":report:" + lastReport.id,
      vm: vm
    });
  }
  if (vm.rights.change && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Duplicate",
      icon: "$ayiClone",
      key: FORM_KEY + ":duplicate",
      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
    });
  }

  menuOptions.menuItems.push({ divider: true, inset: false });
  if (vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "DirectNotification",
      icon: "$ayiCommentAlt",
      key: FORM_KEY + ":directnotify",
      vm: vm
    });

    if (vm.rights.change) {
      menuOptions.menuItems.push({
        title: "SendPasswordResetCode",
        icon: null,
        key: FORM_KEY + ":sendreset",
        vm: vm
      });

      if (vm.obj.twoFactorEnabled) {
        menuOptions.menuItems.push({
          title: "AuthDisableTwoFactor",
          icon: "$ayiLock",
          key: FORM_KEY + ":disable2fa",
          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 populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "UserSettings",
    "Contact",
    "Name",
    "Customer",
    "HeadOffice",
    "NewLogin",
    "NewPassword",
    "AuthorizationRoles",
    "LastLogin",
    "UserNotes",
    "UserType",
    "Active",
    "UserCustom1",
    "UserCustom2",
    "UserCustom3",
    "UserCustom4",
    "UserCustom5",
    "UserCustom6",
    "UserCustom7",
    "UserCustom8",
    "UserCustom9",
    "UserCustom10",
    "UserCustom11",
    "UserCustom12",
    "UserCustom13",
    "UserCustom14",
    "UserCustom15",
    "UserCustom16",
    "CurrencyCode",
    "LanguageCode",
    "TimeZone",
    "Hour12",
    "UserEmailAddress",
    "UserColor",
    "Translation",
    "DarkMode",
    "MapUrlTemplate",
    "UserPhone1",
    "UserPhone2",
    "UserPageAddress",
    "SendPasswordResetCode",
    "AuthDisableTwoFactor",
    "AuthTwoFactorDisabled",
    "AllowLogin"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  //http://localhost:7575/api/v8/translation/list
  const res = await window.$gz.api.get("translation/list");
  if (res.error) {
    vm.formState.serverError = res.error;
    window.$gz.form.setErrorBoxErrors(vm);
  } else {
    vm.selectLists.translations = res.data;
  }
}
</script>
