<!--
 Program: LdapDeptList.vue
 Author: SDL
 Description: Page to view Knox department information
-->
<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!--Contents Area -->
    <div class="row">
      <div class="col-4">
        <!-- Header & buttons -->
        <div class="ui--form-heading clearfix mb-3">
          <h4 class="d-inline-block">
            {{ $t('sdl.department.label.departmentList') }}
          </h4>
        </div>
        <!-- dept tree -->
        <div class="ui--box-tree">
          <sdl-tree
            ref="tree"
            :data="treeData"
            :multiple="false"
            text-field-name="name"
            whole-row
            @item-toggle="treeItemToggle"
            @item-click="treeItemClick"
            drag-over-background-color="#e9ecef"
            style="max-height:535px;"
          />
        </div>
      </div>
      <div class="col-8">
        <!-- dept information -->
        <div class="ui--form-heading clearfix mb-3">
          <h4 class="d-inline-block">
            {{ $t('sdl.department.label.departmentInformation') }}
          </h4>
        </div>
        <table class="table table-bordered ui--table-form ui--table-form-view mb-5">
          <colgroup>
            <col style="width:12.5%" />
            <col style="width:35.5%" />
            <col style="width:12.5%" />
            <col style="width:35.5%" />
          </colgroup>
          <tbody>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.divisionCode') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.deptCode" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.department') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.deptName" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.compCode') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.companyCode" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.user.label.compName') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.companyName" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.departmentChief') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.deptBossName" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.divisionCode') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.opertDivCode" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.division') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.operDivName" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.BizAreaCode') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.bizPlaceCode" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.BizArea') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.bizPlaceName" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.regionCode') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.regionCode" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.region') }}</th>
              <td colspan="3"><input type="text" readonly class="form-control" v-model="deptInfo.regionName" /></td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.department.label.departmentLevel') }}</th>
              <td colspan="3">
                <input type="text" readonly class="form-control-plaintext" v-model="deptInfo.deptLevel" />
              </td>
            </tr>
            <tr>
              <th class="text-nowrap" scope="row">{{ $t('sdl.commonCode.label.order') }}</th>
              <td colspan="3">
                <input type="text" readonly class="form-control-plaintext" v-model="deptInfo.deptSequence" />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <!-- SUB Contents -->
</template>
<script>
import axios from 'axios';
import _ from 'lodash';
import SDLUtil from '@/utils/SDLUtil';

export default {
  data() {
    return {
      deptInfo: {},
      treeData: [],
      selectedDeptItem: {},
    };
  },
  methods: {
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Query department information to create a tree structure(0,1 Depth Department)
     */
    getTopDepthTreeDeptList() {
      /**
       * Create a tree structure after invoking an API that retrieves Knox department information
       */
      // 1 depth Knox department
      return axios.get(`${SDLUtil.API_URL}/admin/knox-department`).then(({ data }) => {
        // Create Tree Structure
        if (data.length !== 0) {
          this.makeTreeData_TopDepth(data);
        }
      });
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: Use the toggle trigger to prevent calls multiple times and call once
     */
    // eslint-disable-next-line func-names
    debouncedItemToggle: _.debounce(function (model) {
      if (model.existSubDepartment) {
        SDLUtil.showLoadingBar(true);
        // Query Knox department, and delete loading bar
        this.getBottomDepthTreeDeptList(model.deptCode).then(() => SDLUtil.showLoadingBar(false));
      }
    }, 10),
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: The toggle function is performed in the tree structure.
     */
    treeItemToggle(oriNode, oriItem) {
      this.debouncedItemToggle(oriItem);
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Query department information to create a tree structure(2 Depth Department)
     */
    getBottomDepthTreeDeptList(deptCode) {
      // Bottom depth Knox department
      return axios.get(`${SDLUtil.API_URL}/admin/knox-department/${deptCode}`).then(({ data }) => {
        // Create Tree Structure
        this.makeTreeData_BottomDepth(deptCode, data);
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Create Tree Structure(0,1 Depth Department)
     */
    makeTreeData_TopDepth(data) {
      const depts = data.map(dept => ({
        ...dept,
        id: dept.deptCode,
        name: dept.deptName,
      }));
      // Find Top Menu
      const root = depts.find(dept => dept.deptLevel === 0);

      root.opened = true;
      root.dragDisabled = true;
      root.name = 'Knox Department';
      // this.treeData.push(root);

      // Top & 1 Depth Department Settings
      let children = depts.filter(dept => dept.upperDeptCode === root.deptCode);
      children = _.sortBy(children, ['deptSequence']);
      children.forEach(d => {
        d.dragDisabled = true;
        d.isFolder = d.existSubDepartment;
      });

      root.children = children;
      this.treeData = [root];
      this.$refs.tree.initializeData(this.treeData);
    },
    /**
     * param: string, array
     * return: nothing
     * exception: nothing
     * description: Create Tree Structure(Bottom Depth Department)
     */
    makeTreeData_BottomDepth(deptCode, data) {
      let childDepts = data.map(dept => ({
        ...dept,
        id: dept.deptCode,
        name: dept.deptName,
      }));

      childDepts = _.sortBy(childDepts, ['deptSequence']);
      childDepts.forEach(d => {
        d.dragDisabled = true;
        d.opened = false;
        d.children = [];
        d.isFolder = d.existSubDepartment;
      });

      const addChild = (treeData, parantCode) => {
        treeData.forEach(treeItem => {
          if (treeItem.deptCode === deptCode) {
            treeItem.children = childDepts;
          } else {
            addChild(treeItem.children, parantCode);
          }
        });
      };

      addChild(this.treeData, deptCode);
      this.$refs.tree.initializeData(this.treeData);
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: Click on Tree Structure
     */
    treeItemClick(item) {
      // Save selected department information to selectedDeptItem
      this.selectedDeptItem = item.model;

      // Apply selected department information to the decInfo mapped to the department details located on the right.
      this.deptInfo = this.selectedDeptItem;
    },
  },
  created() {
    // Launch Loading bar
    SDLUtil.showLoadingBar(true);
    // Query Knox department, and delete loading bar
    this.getTopDepthTreeDeptList().then(() => SDLUtil.showLoadingBar(false));
  },
};
</script>
<style></style>
