<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">
        <template v-if="!composing">
          <v-row>
            <v-col cols="12" class="mb-16">
              <p>
                <span class="text-h6">{{ $ay.t("MemoSent") }}<br /></span
                >{{ $ay.dt(obj.sent) }}
              </p>
              <p>
                <span class="text-h6">{{ $ay.t("MemoFromID") }}<br /></span
                >{{ obj.fromName }}
              </p>
              <p>
                <span class="text-h6">{{ $ay.t("MemoSubject") }}<br /></span
                >{{ obj.name }}
              </p>

              <p>
                <span class="text-h6">{{ $ay.t("MemoMessage") }}<br /></span>
              </p>
              <div style="white-space: pre-wrap;">{{ obj.notes }}</div>
            </v-col>

            <v-col v-if="form().showMe(this, 'Tags')" cols="12">
              <gz-tag-picker v-model="obj.tags" readonly></gz-tag-picker>
            </v-col>

            <v-col cols="12">
              <gz-custom-fields
                v-model="obj.customFields"
                :form-key="formCustomTemplateKey"
                readonly
                :parent-v-m="this"
              ></gz-custom-fields>
            </v-col>

            <v-col v-if="form().showMe(this, 'Wiki')" cols="12">
              <gz-wiki
                v-model="obj.wiki"
                :aya-type="ayaType"
                :aya-id="obj.id"
                readonly
              ></gz-wiki
            ></v-col>
          </v-row>
        </template>
        <template v-else>
          <v-row>
            <v-col v-if="!replyMode" cols="12">
              <gz-pick-list
                ref="userPickList"
                v-model="pickListSelectedUserId"
                :allow-no-selection="false"
                :can-clear="false"
                :aya-type="ayaTypes().User"
                :variant="'inside'"
                :show-edit-icon="false"
                :label="$ay.t('MemoToID')"
                data-cy="pickListSelectedUserId"
                @input="addSelected()"
              ></gz-pick-list>

              <template v-for="item in toUsers">
                <v-chip
                  :key="item.id"
                  color="primary"
                  outlined
                  class="ma-1"
                  close
                  @click:close="closeChip(item)"
                >
                  {{ item.name }}
                </v-chip>
              </template>
            </v-col>
            <v-col v-if="replyMode" cols="12">
              <p>
                <span class="text-caption">{{ $ay.t("MemoToID") }}<br /></span
                >{{ obj.fromName }}
              </p>
            </v-col>
            <v-col cols="12">
              <v-text-field
                ref="name"
                v-model="obj.name"
                :readonly="formState.readOnly"
                :label="$ay.t('MemoSubject')"
                :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">
              <v-textarea
                id="notes"
                ref="notes"
                v-model="obj.notes"
                :readonly="formState.readOnly"
                :label="$ay.t('MemoMessage')"
                :rules="[form().required(this, 'notes')]"
                :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-row>
        </template>
      </v-form>
    </div>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
  </div>
</template>
<script>
const FORM_KEY = "memo-edit";
const API_BASE_URL = "memo/";
const FORM_CUSTOM_TEMPLATE_KEY = "Memo";
export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      obj: {
        id: 0,
        concurrency: 0,
        name: null,
        notes: null,
        wiki: null,
        customFields: "{}",
        tags: [],
        viewed: false,
        replied: false,
        fromId: 1,
        toId: 1,
        sent: null,
        fromName: null
      },
      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.Memo,
      composing: false,
      replyMode: false,
      pickListSelectedUserId: null,
      items: [],
      toUsers: []
    };
  },
  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");
        }

        if (!val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":new");
        } else {
          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.Memo);
      vm.formState.readOnly = false; //can always do things with your own memos
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid != 0) {
        vm.composing = false;
        //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;
          window.$gz.form.setFormState({
            vm: vm,
            loading: false
          });
        } else {
          await vm.getDataFromApi(vm.$route.params.recordid);
        }
      } else {
        //NEW MEMO, set defaults
        vm.composing = true;
        vm.obj.fromId = window.$gz.store.state.userId;
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        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 || LEAVE_OK) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    userSelected(e) {
      const vm = this;
      if (!e) {
        return;
      }
      const user = vm.$refs.userid.getFullSelectionValue();
      if (vm.selectedUsers.find(z => z.id == user.id)) {
        return;
      }
      vm.selectedUsers.push(user);
    },
    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;
      }
      //already in the list?
      if (this.toUsers.find(z => z.id == selected.id)) {
        return;
      }
      this.toUsers.push(selected);
      this.pickListSelectedUserId = null;
      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 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;
      const userIdList = [];
      if (vm.toUsers.length > 0) {
        vm.toUsers.forEach(z => {
          userIdList.push(z.id);
        });
      } else {
        throw new Error("No users selected");
      }
      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        vm.obj.sent = window.$gz.locale.nowUTC8601String();
        const res = await window.$gz.api.post(API_BASE_URL, {
          users: userIdList,
          memo: vm.obj
        });
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          LEAVE_OK = true;
          vm.$router.go(-1);
        }
      } 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) {
          LEAVE_OK = 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 {
            LEAVE_OK = true;
            this.$router.go(-1);
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    },
    replyForward(forward) {
      const vm = this;
      if (!forward) {
        //REPLY MODE
        vm.obj.toId = vm.obj.fromId;
        vm.replyMode = true;
        vm.toUsers.push({ id: vm.obj.fromId });
      }
      const header = `${vm.$ay.t("MemoSent")} ${vm.$ay.dt(
        vm.obj.sent
      )}\n${vm.$ay.t("MemoFromID")} ${vm.obj.fromName}\n${vm.$ay.t(
        "MemoSubject"
      )} ${vm.obj.name}\n`;
      vm.obj.name = `${vm.$ay.t("MemoRe")} ${vm.obj.name}`;
      vm.obj.notes = `\n\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n${header}\n\n${vm.obj.notes}`;
      vm.obj.id = 0;
      vm.composing = true;
      generateMenu(vm);
      window.$gz.form.setFormState({
        vm: vm,
        dirty: true,
        valid: true,
        loading: false
      });
      vm.updateSave();
      this.$nextTick(() => {
        const el = document.getElementById("notes");
        el.focus();
        el.setSelectionRange(0, 0);
      });
    }
  }
};

/////////////////////////////
//
//
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: "memo-edit",
          params: { recordid: 0 }
        });
        break;
      case "report":
        {
          const res = await m.vm.$refs.reportSelector.open(
            {
              AType: window.$gz.type.Memo,
              selectedRowIds: [m.vm.obj.id]
            },
            m.id
          );
          if (res == null) {
            return;
          }
          window.$gz.form.setLastReportMenuItem(FORM_KEY, res, m.vm);
        }
        break;
      case "reply":
        m.vm.replyForward(false);
        break;
      case "forward":
        m.vm.replyForward(true);
        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: "$ayiInbox",
    title: "Memo",
    helpUrl: "home-memos",
    formData: {
      ayaType: window.$gz.type.Memo,
      recordId: vm.$route.params.recordid,
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY
    },
    menuItems: []
  };

  if (vm.composing) {
    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.composing) {
    menuOptions.menuItems.push({
      title: "MemoReply",
      icon: "$ayiReply",
      key: FORM_KEY + ":reply",
      vm: vm
    });
  }
  if (vm.rights.change && !vm.composing) {
    menuOptions.menuItems.push({
      title: "MemoForward",
      icon: "$ayiShare",
      key: FORM_KEY + ":forward",
      vm: vm
    });
  }
  if (!vm.composing) {
    menuOptions.menuItems.push({
      title: "Delete",
      icon: "$ayiTrashAlt",
      surface: false,
      key: FORM_KEY + ":delete",
      vm: vm
    });
  }

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

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

let LEAVE_OK = false;

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY, vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "Memo",
    "MemoSubject",
    "MemoMessage",
    "MemoToID",
    "User",
    "MemoFromID",
    "MemoSent",
    "MemoForward",
    "MemoReply",
    "MemoRe",
    "MemoCustom1",
    "MemoCustom2",
    "MemoCustom3",
    "MemoCustom4",
    "MemoCustom5",
    "MemoCustom6",
    "MemoCustom7",
    "MemoCustom8",
    "MemoCustom9",
    "MemoCustom10",
    "MemoCustom11",
    "MemoCustom12",
    "MemoCustom13",
    "MemoCustom14",
    "MemoCustom15",
    "MemoCustom16"
  ]);
} /*

  /// <summary>
  /// Generate a new memo as a Reply or Forward based on this fetched read only memo
  /// </summary>
  /// <param name="bForward">If true, this is a forward reply to don't set the toID just yet</param>
  /// <returns>A memo object with fields filled in ready for typing reply/forward text</returns>
  public Memo ReplyForward(bool bForward)
  {
   Memo m=Memo.NewItem();
   if(!bForward)
    m.ToID=this.FromID;
   
   m.Subject=LocalizedTextTable.GetLocalizedTextDirect("Memo.Label.Re")+ " " + this.Subject;
   m.Message="\r\n\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r\n" + this.Header + "\r\n\r\n" + this.Message;
   
   return m;
  }
 */
</script>
