<template>
  <v-row v-if="formState.ready" dense>
    <v-col>
      <v-form ref="form">
        <v-row dense>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
          <v-col cols="12">
            <gz-pick-list
              ref="userPickList"
              v-model="pickListSelectedUserId"
              :allow-no-selection="false"
              :can-clear="false"
              :aya-type="ayaTypes().User"
              :show-edit-icon="false"
              :label="$ay.t('UserList')"
              data-cy="pickListSelectedUserId"
              @input="addSelected()"
            ></gz-pick-list>
            <template v-for="item in toUsers">
              <v-chip
                :key="item.id"
                dense
                color="primary"
                outlined
                class="ma-2"
                close
                @click:close="closeChip(item)"
              >
                {{ item.name }}
              </v-chip>
            </template>
          </v-col>

          <v-col cols="12">
            <v-textarea
              ref="message"
              v-model="message"
              dense
              :label="$ay.t('MemoMessage')"
              :rules="[form().required(this, 'message')]"
              auto-grow
              @input="fieldValueChanged('message')"
            ></v-textarea>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "notify-direct";
export default {
  components: {},
  data() {
    return {
      pickListSelectedUserId: null,
      items: [],
      toUsers: [],
      message: null,
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.fullRightsObject()
    };
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        const hasSelection = this.toUsers.length > 0;
        if (val.dirty && val.valid && !val.readOnly && hasSelection) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
      },
      deep: true
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.fullRightsObject();
      generateMenu(vm);
      vm.formState.ready = true;
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        valid: true,
        loading: false,
        readOnly: false
      });
      window.$gz.eventBus.$on("menu-click", clickHandler);
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    updateSave: function() {
      const hasSelection = this.toUsers.length > 0;
      if (
        this.formState.dirty &&
        this.formState.valid &&
        !this.formState.readOnly &&
        hasSelection
      ) {
        window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
      } else {
        window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
      }
    },
    closeChip(item) {
      const i = this.toUsers.findIndex(z => z.id == item.id);
      if (i != -1) {
        this.toUsers.splice(i, 1);
      }
      this.updateSave();
    },
    addSelected() {
      const selected = this.$refs.userPickList.getFullSelectionValue();
      if (selected == null) {
        return;
      }
      if (this.toUsers.find(z => z.id == selected.id)) {
        return;
      }
      this.toUsers.push(selected);
      this.pickListSelectedUserId = 0;
      this.updateSave();
    },
    ayaTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (
        this.formState.ready &&
        !this.formState.loading &&
        !this.formState.readOnly
      ) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async submit() {
      this.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(this);
      try {
        const userIdList = [];
        if (this.toUsers.length > 0) {
          this.toUsers.forEach(z => {
            userIdList.push(z.id);
          });
        } else {
          userIdList.push(this.pickListSelectedUserId);
        }
        const res = await window.$gz.api.upsert("notify/direct-message", {
          users: userIdList,
          message: this.message
        });
        if (res.error) {
          this.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(this);
        } else {
          this.pickListSelectedUserId = null;
          this.items = [];
          this.toUsers = [];
          this.message = null;
          //Only a post, no data returned
          window.$gz.form.setFormState({
            vm: this,
            dirty: false
          });
          this.updateSave();
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        this.loading = false;
      }
    }
  }
};

/////////////////////////////
//
//
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;

      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: true,
    icon: "$ayiCommentAlt",
    title: "DirectNotification",
    helpUrl: "home-notify-direct",
    menuItems: []
  };
  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText();
  if (vm.$route.params.userIdList != undefined) {
    await preFillSelection(vm);
  }
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "DirectNotification",
    "UserList",
    "MemoMessage",
    "MemoToID"
  ]);
}

//////////////////////////////////////////////////////////
//
// Pre fill if pre-selected users
//
async function preFillSelection(vm) {
  var idParam = vm.$route.params.userIdList;
  let l = [];
  if (typeof idParam == "string" && idParam.includes(",")) {
    //just a random list of user ids seperated by commas
    l = idParam.split(",").map(z => parseInt(z, 10));
  } else {
    //single value
    l.push(parseInt(idParam, 10));
  }
  const res = await window.$gz.api.post("pick-list/list", {
    ayaType: window.$gz.type.User,
    inactive: false,
    preselectedIds: l
  });
  if (res.data && res.data.length > 0) {
    res.data.forEach(x => {
      vm.toUsers.push(x);
    });
  }
}
</script>
