<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("User") }}</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>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    ref="name"
                    v-model="obj.name"
                    :readonly="formState.readOnly"
                    :disabled="obj.id === 1"
                    :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 v-if="obj.userType == 5" cols="12" sm="6" lg="4" xl="3">
                  <gz-pick-list
                    ref="vendorId"
                    v-model="obj.vendorId"
                    :aya-type="ayaTypes().Vendor"
                    show-edit-icon
                    :readonly="formState.readOnly"
                    :label="$ay.t('Vendor')"
                    data-cy="vendorId"
                    :error-messages="form().serverErrors(this, 'vendorId')"
                    @input="fieldValueChanged('vendorId')"
                  ></gz-pick-list>
                </v-col>
                <v-col
                  v-if="form().showMe(this, 'EmployeeNumber') && obj.id != 1"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    ref="employeeNumber"
                    v-model="obj.employeeNumber"
                    :readonly="formState.readOnly"
                    :label="$ay.t('UserEmployeeNumber')"
                    :error-messages="
                      form().serverErrors(this, 'employeeNumber')
                    "
                    data-cy="employeeNumber"
                    @input="fieldValueChanged('employeeNumber')"
                  ></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"
                    :disabled="obj.id === 1"
                    data-cy="roles"
                    :error-messages="form().serverErrors(this, 'roles')"
                    limit-selection-to="inside"
                    @input="fieldValueChanged('roles')"
                  ></gz-role-picker>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-select
                    ref="usertype"
                    v-model="obj.userType"
                    :items="selectLists.usertypes"
                    item-text="name"
                    item-value="id"
                    :readonly="formState.readOnly"
                    :disabled="obj.id === 1"
                    :label="$ay.t('UserType')"
                    data-cy="usertype"
                    :rules="[form().integerValid(this, 'usertype')]"
                    :error-messages="form().serverErrors(this, 'usertype')"
                    @input="fieldValueChanged('usertype')"
                  ></v-select>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    id="username"
                    ref="login"
                    v-model="login"
                    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 cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    id="password"
                    ref="password"
                    v-model="password"
                    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
                  v-if="form().showMe(this, 'LastLogin')"
                  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"
                    :readonly="formState.readOnly"
                    :disabled="obj.id === 1"
                    :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"
                    :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>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-select
                    ref="translationId"
                    v-model="optionsObj.translationId"
                    :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"
                    :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
                    :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"
                    :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"
                    :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"
                    :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"
                    :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 = "user-edit";
const API_BASE_URL = "user/";
const FORM_CUSTOM_TEMPLATE_KEY = "User";

export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      selectLists: {
        usertypes: [],
        translations: [],
        mapUrls: window.$gz.util.mapProviderUrls()
      },
      obj: {
        id: 0,
        concurrency: 0,
        active: true,
        name: null,
        roles: null,
        userType: 2,
        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: "#000000",
        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);
      vm.rights = window.$gz.role.getRights(window.$gz.type.User);
      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;
        }
      }

      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);
          return;
        } else {
          if (res.data.id) {
            //POST
            vm.obj = res.data;
            vm.optionsObj.userId = res.data.id;
            await vm.submitOptions();
            this.$router.replace({
              name: "adm-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: "adm-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 {
          //always a put but may not have a concurrency token if it's a duplicate
          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 {
            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 "new":
        m.vm.$router.push({
          name: "adm-user",
          params: { recordid: 0 }
        });
        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":
        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;
      case "WorkOrderItemScheduledUserList":
        m.vm.$router.push({
          name: "svc-workorder-item-scheduled-users",
          params: {
            aType: m.vm.ayaType,
            objectId: m.vm.obj.id,
            name: m.vm.obj.name
          }
        });
        break;
      case "WorkOrderItemLaborList":
        m.vm.$router.push({
          name: "svc-workorder-item-labors",
          params: {
            aType: m.vm.ayaType,
            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: "$ayiUser",
    title: "User",
    helpUrl: "adm-users",
    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) {
    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
    });
  }

  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
        });
      }
      if (vm.obj.userType == 1 || vm.obj.userType == 5) {
        menuOptions.menuItems.push({
          title: "WorkOrderItemScheduledUserList",
          icon: "$ayiUserClock",
          key: FORM_KEY + ":WorkOrderItemScheduledUserList",
          vm: vm
        });
        menuOptions.menuItems.push({
          title: "WorkOrderItemLaborList",
          icon: "$ayiHammer",
          key: FORM_KEY + ":WorkOrderItemLaborList",
          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);
  await populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "Vendor",
    "User",
    "UserSettings",
    "Name",
    "UserEmployeeNumber",
    "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",
    "WorkOrderItemScheduledUserList",
    "WorkOrderItemLaborList"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  //ensure the pick lists required are pre-fetched
  await window.$gz.enums.fetchEnumList("insideusertype");
  vm.selectLists.usertypes = window.$gz.enums.getSelectionList(
    "insideusertype"
  );
  //------------
  //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>
