<template>
  <div>
    <gz-report-selector ref="reportSelector"></gz-report-selector>
    <gz-extensions
      :aya-type="$ay.ayt().TaskGroup"
      :selected-items="selectedItems"
      ref="extensions"
    >
    </gz-extensions>
    <gz-data-table
      ref="gzdatatable"
      form-key="svc-task-group"
      data-list-key="TaskGroupDataList"
      :show-select="rights.read"
      :reload="reload"
      @selection-change="handleSelected"
      data-cy="taskGroupTable"
    >
    </gz-data-table>
  </div>
</template>

<script>
const FORM_KEY = "svc-task-group";
export default {
  created() {
    this.rights = window.$gz.role.getRights(window.$gz.type.TaskGroup);
    window.$gz.eventBus.$on("menu-click", clickHandler);
    generateMenu(this);
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      rights: window.$gz.role.defaultRightsObject(),
      selectedItems: [],
      reload: false
    };
  },
  methods: {
    handleSelected(selected) {
      this.selectedItems = selected;
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "new":
        m.vm.$router.push({
          name: "svc-task-group",
          params: { recordid: 0 }
        });
        break;
      case "extensions":
        let res = await m.vm.$refs.extensions.open(
          m.vm.$refs.gzdatatable.getDataListSelection(
            window.$gz.type.WorkOrderStatus
          )
        );
        if (res && res.refresh == true) {
          m.vm.reload = !m.vm.reload;
        }
        break;

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

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiTasks",
    title: "TaskGroupList",
    helpUrl: "svc-task-groups",
    menuItems: [],
    formData: {
      ayaType: window.$gz.type.TaskGroup
    }
  };

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

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