<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">
        <div v-if="obj.aType" class="mb-6">
          <v-icon large @click="navToTarget()">{{ iconForType }}</v-icon
          ><span class="text-h5" @click="navToTarget()"> {{ name }}</span>
        </div>
        <v-row dense>
          <v-col v-if="currentUserIsASupervisor" cols="12" sm="6" lg="4" xl="3">
            <gz-pick-list
              ref="userId"
              v-model="obj.userId"
              :aya-type="sockTypes().User"
              :variant="'inside'"
              show-edit-icon
              :allow-no-selection="false"
              :can-clear="false"
              :readonly="formState.readOnly"
              :label="$sock.t('ReviewUserId')"
              :rules="[form().required(this, 'userId')]"
              data-cy="userId"
              :error-messages="form().serverErrors(this, 'userId')"
              @input="fieldValueChanged('userId')"
            ></gz-pick-list>
          </v-col>

          <v-col v-if="currentUserIsASupervisor" cols="12" sm="6" lg="4" xl="3">
            <gz-pick-list
              ref="assignedByUserId"
              v-model="obj.assignedByUserId"
              :aya-type="sockTypes().User"
              :variant="'inside'"
              show-edit-icon
              readonly
              :label="$sock.t('ReviewAssignedByUserId')"
              :rules="[form().required(this, 'assignedByUserId')]"
              data-cy="assignedByUserId"
              :error-messages="form().serverErrors(this, 'assignedByUserId')"
              @input="fieldValueChanged('assignedByUserId')"
            ></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 ||
                  (!selfAssigned && !currentUserIsASupervisor)
              "
              :label="$sock.t('ReviewName')"
              :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-date-time-picker
              ref="reviewDate"
              v-model="obj.reviewDate"
              :label="$sock.t('ReviewDate')"
              :rules="[form().required(this, 'reviewDate')]"
              :readonly="
                formState.readOnly ||
                  (!selfAssigned && !currentUserIsASupervisor)
              "
              data-cy="reviewDate"
              :error-messages="form().serverErrors(this, 'reviewDate')"
              @input="fieldValueChanged('reviewDate')"
            ></gz-date-time-picker>
          </v-col>
          <v-col cols="12">
            <v-textarea
              ref="notes"
              v-model="obj.notes"
              dense
              :readonly="
                formState.readOnly ||
                  (!selfAssigned && !currentUserIsASupervisor)
              "
              :label="$sock.t('ReviewNotes')"
              :error-messages="form().serverErrors(this, 'notes')"
              data-cy="notes"
              auto-grow
              @input="fieldValueChanged('notes')"
            ></v-textarea>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-date-time-picker
              ref="completedDate"
              v-model="obj.completedDate"
              :label="$sock.t('ReviewCompletedDate')"
              :error-messages="form().serverErrors(this, 'completedDate')"
              :readonly="formState.readOnly"
              data-cy="completedDate"
              @input="fieldValueChanged('completedDate')"
            ></gz-date-time-picker>
          </v-col>

          <v-col cols="12">
            <v-textarea
              ref="completionNotes"
              v-model="obj.completionNotes"
              dense
              :readonly="formState.readOnly"
              :label="$sock.t('ReviewCompletionNotes')"
              :error-messages="form().serverErrors(this, 'completionNotes')"
              data-cy="completionNotes"
              auto-grow
              @input="fieldValueChanged('completionNotes')"
            ></v-textarea>
          </v-col>

          <!-- --------------------------------- -->

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

          <v-col cols="12">
            <gz-custom-fields
              ref="customFields"
              v-model="obj.customFields"
              :form-key="formCustomTemplateKey"
              :readonly="formState.readOnly"
              :parent-v-m="this"
              data-cy="customFields"
              :error-messages="form().serverErrors(this, 'customFields')"
              @input="fieldValueChanged('customFields')"
            ></gz-custom-fields>
          </v-col>

          <v-col v-if="form().showMe(this, 'Wiki')" cols="12">
            <gz-wiki
              ref="wiki"
              v-model="obj.wiki"
              :aya-type="sockType"
              :aya-id="obj.id"
              :readonly="formState.readOnly"
              @input="fieldValueChanged('wiki')"
            ></gz-wiki
          ></v-col>

          <v-col v-if="form().showMe(this, 'Attachments') && obj.id" cols="12">
            <gz-attachments
              :readonly="formState.readOnly"
              :aya-type="sockType"
              :aya-id="obj.id"
            ></gz-attachments
          ></v-col>
        </v-row>
      </v-form>
    </div>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
  </div>
</template>
<script>
const FORM_KEY = "review-edit";
const API_BASE_URL = "review/";
const FORM_CUSTOM_TEMPLATE_KEY = "Review";

export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      obj: {
        id: 0,
        concurrency: 0,
        name: null,
        notes: null,
        wiki: null,
        customFields: "{}",
        tags: [],
        reviewDate: null,
        completedDate: null,
        completionNotes: null,
        userId: window.$gz.store.state.userId,
        assignedByUserId: window.$gz.store.state.userId,
        objectId: null,
        aType: null,
        overDue: false
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      sockType: window.$gz.type.Review,
      currentUserIsASupervisor: window.$gz.role.hasRole([
        window.$gz.role.AUTHORIZATION_ROLES.BizAdmin,
        window.$gz.role.AUTHORIZATION_ROLES.Service,
        window.$gz.role.AUTHORIZATION_ROLES.Inventory,
        window.$gz.role.AUTHORIZATION_ROLES.Sales,
        window.$gz.role.AUTHORIZATION_ROLES.Accounting
      ]),
      name: null
    };
  },
  computed: {
    selfAssigned: function() {
      return this.obj.userId == this.obj.assignedByUserId;
    },

    iconForType() {
      return window.$gz.util.iconForType(this.obj.aType);
    },
    hasSupervisorRole: function() {
      return window.$gz.role.hasRole([
        window.$gz.role.AUTHORIZATION_ROLES.BizAdmin,
        window.$gz.role.AUTHORIZATION_ROLES.Service,
        window.$gz.role.AUTHORIZATION_ROLES.Inventory,
        window.$gz.role.AUTHORIZATION_ROLES.Sales,
        window.$gz.role.AUTHORIZATION_ROLES.Accounting
      ]);
    }
  },
  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;
    if (vm.$route.params.name) {
      vm.name = vm.$route.params.name;
    }
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(window.$gz.type.Review);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      let setDirty = false;
      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid != 0) {
        //is there already an obj from a prior operation?
        if (this.$route.params.obj) {
          //yes, no need to fetch it
          this.obj = this.$route.params.obj;
        } else {
          await vm.getDataFromApi(vm.$route.params.recordid);
        }
      } else {
        //Might be a duplicate and contain another record
        if (this.$route.params.obj) {
          this.obj = this.$route.params.obj;
          this.obj.concurrency = undefined;
          this.obj.id = 0;
          this.obj.name = `${this.obj.name} - ${window.$gz.translation.get(
            "Copy"
          )}`;
          setDirty = true;
        } else {
          //New record so there has to be a object type and objectId in route
          // path: "/home-reviews/:recordid/:aType?/:objectId?",
          vm.obj.objectId = window.$gz.util.stringToIntOrNull(
            vm.$route.params.objectId
          );
          vm.obj.aType = window.$gz.util.stringToIntOrNull(
            vm.$route.params.aType
          );
          if (!vm.obj.objectId || !vm.obj.aType) {
            throw "SockType and ObjectId are required to create a review";
          }
        }
      }
      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: {
    navToTarget: function() {
      window.$gz.eventBus.$emit("openobject", {
        type: this.obj.aType,
        id: this.obj.objectId
      });
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: function() {
      return this.formState.valid && !this.formState.dirty;
    },
    sockTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (
        this.formState.ready &&
        !this.formState.loading &&
        !this.formState.readOnly
      ) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi(recordId) {
      const vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.get(API_BASE_URL + recordId);
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          vm.name = res.data.reviewObjectViz;
          generateMenu(vm);
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async submit() {
      const vm = this;
      if (vm.canSave == false) {
        return;
      }
      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.upsert(API_BASE_URL, vm.obj);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data.id) {
            //POST
            vm.obj = res.data;
            this.$router.replace({
              name: "review-edit",
              params: {
                recordid: res.data.id,
                obj: res.data,
                name: res.data.reviewObjectViz
              }
            });
          } else {
            //PUT
            vm.obj.concurrency = res.data.concurrency;
            vm.name = res.data.reviewObjectViz;
          }
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true
          });
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async remove() {
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
        window.$gz.form.setFormState({
          vm: this,
          loading: true
        });
        if (this.$route.params.recordid == 0) {
          JUST_DELETED = true;
          this.$router.go(-1);
        } else {
          window.$gz.form.deleteAllErrorBoxErrors(this);
          const res = await window.$gz.api.remove(
            API_BASE_URL + this.$route.params.recordid
          );
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            JUST_DELETED = true;
            this.$router.go(-1);
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    },
    duplicate() {
      this.$router.push({
        name: "review-edit",
        params: {
          recordid: 0,
          obj: this.obj
        }
      });
    }
  }
};

/////////////////////////////
//
//
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: "review-edit",
          params: {
            recordid: 0,
            aType: m.vm.obj.aType,
            objectId: m.vm.obj.objectId,
            name: m.vm.name
          }
        });
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      case "report":
        {
          const res = await m.vm.$refs.reportSelector.open(
            {
              SockType: window.$gz.type.Review,
              selectedRowIds: [m.vm.obj.id]
            },
            m.id
          );
          if (res == null) {
            return;
          }
          window.$gz.form.setLastReportMenuItem(FORM_KEY, res, m.vm);
        }
        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: "$sockiCalendarCheck",
    title: "Review",
    helpUrl: "home-reviews",
    formData: {
      sockType: window.$gz.type.Review,
      recordId: vm.$route.params.recordid,
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$sockiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

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

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

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

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

  if (vm.rights.delete && vm.$route.params.recordid != 0) {
    if (vm.selfAssigned || vm.hasSupervisorRole) {
      menuOptions.menuItems.push({
        title: "Delete",
        icon: "$sockiTrashAlt",
        surface: false,
        key: FORM_KEY + ":delete",
        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);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "Review",
    "ReviewName",
    "ReviewNotes",
    "ReviewDate",
    "ReviewCompletedDate",
    "ReviewCompletionNotes",
    "ReviewUserId",
    "ReviewAssignedByUserId",
    "ReviewCustom1",
    "ReviewCustom2",
    "ReviewCustom3",
    "ReviewCustom4",
    "ReviewCustom5",
    "ReviewCustom6",
    "ReviewCustom7",
    "ReviewCustom8",
    "ReviewCustom9",
    "ReviewCustom10",
    "ReviewCustom11",
    "ReviewCustom12",
    "ReviewCustom13",
    "ReviewCustom14",
    "ReviewCustom15",
    "ReviewCustom16"
  ]);
}
</script>
