<!--
 Program: MenuListPopup.vue
 Author: SDL
 Description: a popup page where you can view and select a menu list.
-->
<template>
  <div class="modal-dialog modal-dialog-centered  modal-dialog-scrollable modal-lg">
    <div class="modal-content" style="height:744px;">
      <!-- contents -->
      <div class="modal-header">
        <h5 class="modal-title h4">{{ $t('sdl.menu.label.menuList') }}</h5>
        <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" @click="$emit('close')"></button>
      </div>
      <div class="modal-body">
        <!-- menu tree -->
        <div class="ui--box-tree">
          <sdl-tree
            ref="tree"
            class="ui--tree"
            :data="treeData"
            :showCheckbox="true"
            :multiple="true"
            :allowBatch="true"
            text-field-name="localeLabel"
            whole-row
            drag-over-background-color="#e9ecef"
          />
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="$emit('close')">
          {{ $t('sdl.common.label.cancel') }}
        </button>
        <button type="button" class="btn btn-primary" @click="rtnData">{{ $t('sdl.common.label.confirm') }}</button>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios';
import _ from 'lodash';
import SDLUtil from '@/utils/SDLUtil';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  data() {
    return {
      treeData: [],
      selectedMenuList: [],
      menuFullPath: '',
    };
  },
  mixins: [SDLLocale],
  props: {
    userId: {
      required: false,
      type: String,
    },
    workgroupId: {
      required: false,
      type: String,
    },
    rtnFunc: {
      type: Function,
    },
  },
  methods: {
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: To query and create a menu list as a tree structure
     */
    getTreeMenuService() {
      let ApiUrl = '';

      // Set user-menu lookup API
      if (this.userId !== null && this.userId !== undefined) {
        ApiUrl = `${SDLUtil.API_URL}/auth/menus/${this.userId}/user-menu-popup`;
      }

      // Set task group-menu lookup API
      if (this.workgroupId !== null && this.workgroupId !== undefined) {
        ApiUrl = `${SDLUtil.API_URL}/auth/menus/${this.workgroupId}/workgroup-menu-popup`;
      }

      // Call up menu lookup API and create as a tree structure
      return axios.get(ApiUrl).then(({ data }) => {
        this.makeTreeData(data);
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Create as a Tree Structure
     */
    makeTreeData(data) {
      const menus = data.map(menu => ({
        ...menu,
        id: menu.menuId,
        value: menu,
      }));
      // Set Locale Label
      menus.map(m => {
        m.localeLabel = this.getLabel(m);
        return m;
      });
      /**
       * Find Top-Level
       */
      const root = menus.find(menu => menu.menuLevel === 0);
      root.opened = true;
      root.selected = false;
      root.disabled = true;
      root.dragDisabled = true;
      this.treeData.push(root);

      /**
       * Set the submenu of the top menu to Tree structure, then return
       */
      const getChildren = parentId => {
        let children = menus.filter(menu => menu.parentId === parentId);
        children = _.sortBy(children, ['menuSequence']);
        children.forEach(m => {
          m.dragDisabled = true;
          m.selected = false;
          // Check if the menu is registered and disable
          if (m.checked) {
            m.disabled = true;
          } else {
            m.disabled = false;
          }
          // Check if child nodes exist, call recursive function
          if (_.find(menus, ['parentId', m.menuId])) {
            m.opened = false;
            m.children = getChildren(m.menuId);
          } else {
            // m.disabled = false;
          }
        });
        return children;
      };
      // Invoke the recursive function of the submenu of the top menu to apply the returned value
      root.children = getChildren(root.menuId);
      // Apply menu objects set to Tree structure
      this.treeData = [root];
      this.$refs.tree.initializeData(this.treeData);
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Save the Menu Full Path for the specified menu id
     */
    getMenuFullPathTreeItemById(treeId) {
      this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, node => {
        if (node.model && node.model.id === treeId) {
          const parentId = node.model.parentId || node.model.parentId;
          if (parentId) {
            this.menuFullPath = `${node.model.label} > ${this.menuFullPath}`;
            this.getMenuFullPathTreeItemById(parentId);
          }
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Forward selected list to call page via function
     */
    rtnData() {
      // Save the selected Menu in object format to the temporary storage array
      this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, nodeItem => {
        if (nodeItem.model && nodeItem.model.selected) {
          this.selectedMenuList.push(nodeItem.model);
        }
      });

      // Save menu full path in temporary storage array
      this.selectedMenuList.forEach(selectItem => {
        this.menuFullPath = selectItem.label;
        this.getMenuFullPathTreeItemById(selectItem.parentId);
        selectItem.menuFullPath = this.menuFullPath;
      });

      // Call up the popup screen by applying a list to pass on the function of the page.
      this.rtnFunc(this.selectedMenuList);
      this.$emit('close');
    },
  },
  created() {
    // Launch Loading bar
    SDLUtil.showLoadingBar(true);
    // Call up menu list lookup and tree structure generation functions
    this.getTreeMenuService().then(() => SDLUtil.showLoadingBar(false));
  },
};
</script>
<style></style>
