<!--
 Program: DeptList.vue
 Author: SDL
 Description: Page that enables users to randomly register, modify, and delete departments
-->
<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 class="float-end">
            <button type="button" class="btn btn-secondary btn-sm" @click="deleteDeptBtn" v-authorization="'update'">
              {{ $t('sdl.common.label.delete') }}
            </button>
            <button type="button" class="btn btn-secondary btn-sm" @click="addDeptBtn" v-authorization="'execute'">
              {{ $t('sdl.common.label.add') }}
            </button>
          </div>
        </div>
        <!-- dept tree -->
        <div class="ui--box-tree" style="height:380px">
          <sdl-tree
            ref="tree"
            :data="treeData"
            :before-item-click="beforeTreeItemClick"
            :multiple="false"
            text-field-name="selfDeptName"
            whole-row
            :draggable="treeDraggable"
            @item-drag-start="treeItemDragStart"
            @item-drop="treeItemDrop"
            @item-click="treeItemClick"
            drag-over-background-color="#e9ecef"
          />
        </div>
      </div>
      <div class="col-8">
        <!-- Department Information Header & button -->
        <div class="ui--form-heading clearfix mb-3">
          <h4 class="d-inline-block">{{ $t('sdl.department.label.departmentInformation') }}</h4>
          <div class="float-end">
            <button
              type="button"
              class="btn btn-primary btn-sm"
              @click="saveDeptBtn"
              v-authorization="['update', 'execute']"
            >
              {{ $t('sdl.common.label.save') }}
            </button>
          </div>
        </div>
        <!-- Department Information Header & button -->
        <!-- Department Information Form -->
        <table class="table table-bordered ui--table-form ui--table-form-view mb-4">
          <colgroup>
            <col style="width:15%" />
            <col style="width:35%" />
            <col style="width:15%" />
            <col style="width:35%" />
          </colgroup>
          <tbody>
            <tr>
              <th scope="row">
                {{ $t('sdl.department.label.divisionCode') }} <span class="ui--text-required">&#42;</span>
              </th>
              <td>
                <input
                  type="text"
                  :readonly="inputStatus !== 'insert'"
                  :class="[inputStatus === 'select' ? 'form-control-plaintext' : 'form-control']"
                  v-model.trim="selectedDept.selfDeptCode"
                  v-validation="{
                    groupId: 'dept',
                    valids: [
                      {
                        validFuncs: () => {
                          return selectedDept.selfDeptCode.length <= 20;
                        },
                        errorMessage: 'sdl.department.message.departmentCode20Characters',
                      },
                    ],
                  }"
                  errorMessage="sdl.department.message.requiredValue"
                />
              </td>
              <th scope="row">
                {{ $t('sdl.department.label.departmentName') }} <span class="ui--text-required">&#42;</span>
              </th>
              <td>
                <input
                  type="text"
                  :readonly="inputStatus === 'init'"
                  class="form-control"
                  v-model.trim="selectedDept.selfDeptName"
                  v-validation="{
                    groupId: 'dept',
                    valids: [
                      {
                        validFuncs: () => {
                          return selectedDept.selfDeptName.length <= 500;
                        },
                        errorMessage: 'sdl.department.message.departmentName500Characters',
                      },
                    ],
                  }"
                  errorMessage="sdl.department.message.requiredValue"
                />
              </td>
            </tr>
            <tr>
              <th scope="row">{{ $t('sdl.department.label.departmentLevel') }}</th>
              <td>
                <input type="text" readonly class="form-control-plaintext" v-model="selectedDept.deptLevel" />
              </td>
              <th class="text-nowrap" scope="row">{{ $t('sdl.commonCode.label.order') }}</th>
              <td>
                <input type="number" class="form-control" v-model.number="selectedDept.deptSequence" />
              </td>
            </tr>
            <tr></tr>
            <tr>
              <th scope="row">{{ $t('sdl.commonCode.label.description') }} <span class="ui--text-required">&#42;</span></th>
              <td colspan="3">
                <input
                  type="text"
                  :readonly="inputStatus === 'init'"
                  class="form-control"
                  v-model.trim="selectedDept.description"
                  v-validation="{
                    groupId: 'dept',
                    valids: [
                      {
                        validFuncs: () => {
                          return selectedDept.description.length <= 2000;
                        },
                        errorMessage: 'sdl.department.message.description2000Characters',
                      },
                    ],
                  }"
                  errorMessage="sdl.department.message.requiredValue"
                />
              </td>
            </tr>
          </tbody>
        </table>
        <!-- Department Information Form -->
        <!-- Department Mapping Header & button -->
        <div class="ui--form-heading clearfix mb-2">
          <h5 class="d-inline-block">{{ $t('sdl.department.label.departmentMapping') }}</h5>
          <div class="float-end">
            <button type="button" class="btn btn-secondary btn-sm" @click="openDeptPopUp" v-authorization="'execute'">
              {{ $t('sdl.common.label.add') }}
            </button>
            <button
              type="button"
              class="btn btn-primary btn-sm"
              @click="saveMappingDeptBtn"
              v-authorization="['update', 'execute']"
            >
              {{ $t('sdl.common.label.save') }}
            </button>
          </div>
        </div>
        <!-- Department Mapping Header & button -->
        <!-- Department Mapping Grid -->
        <table class="table table-bordered ui--table">
          <colgroup>
            <col style="width:40%" />
            <col style="width:40%" />
            <col style="width:20%" />
          </colgroup>
          <thead>
            <tr>
              <th scope="col">{{ $t('sdl.department.label.divisionCode') }}</th>
              <th scope="col">{{ $t('sdl.department.label.departmentName') }}</th>
              <th scope="col">{{ $t('sdl.common.label.delete') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="dept in deptMappingList" :key="dept.deptCode">
              <td class="text-center">{{ dept.deptCode }}</td>
              <td>{{ dept.deptName }}</td>
              <td class="text-center">
                <button class="btn btn-outline-secondary ui--btn-xs" @click="executeDelMappingDept(dept.deptCode)">
                  <!-- 버튼 권한 처리에 대해 협의 후 진행 - 김민석 D -->
                  {{ $t('sdl.common.label.delete') }}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
        <!-- Department Mapping Grid -->
      </div>
    </div>
  </div>
  <!-- SUB Contents -->
</template>
<script>
import { mapActions } from 'vuex';
import axios from 'axios';
import _ from 'lodash';
import { SDLUtil, StringUtil } from '@/utils';
import DeptPopup from '@/components/common/popup/DeptListPopup.vue';

export default {
  data() {
    return {
      treeDraggable: true,
      treeData: [],
      selectedDept: {},
      selectedDeptItem: {},
      existDeptList: [],
      deptMappingList: [],
      tempDeptMappingList: [],
      inputStatus: '',
    };
  },
  methods: {
    ...mapActions(['clearCache']),
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Query department information to create a tree structure
     */
    getTreeDeptList() {
      /**
       * Create a tree structure after invoking an API that retrieves user-created department information
       */
      return axios.get(`${SDLUtil.API_URL}/admin/department/custom`).then(({ data }) => {
        // Create Tree Structure
        this.makeTreeData(data);

        this.existDeptList = data;
        // Enable drag in tree structure
        this.treeDraggable = true;
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Create Tree Structure
     */
    makeTreeData(data) {
      const depts = data.map(dept => ({
        ...dept,
        code: dept.selfDeptCode,
      }));

      /**
       * Top menu settings (menu settings that do not exist in DB)
       */
      const root = {
        selfDeptCode: 'DEPT',
        selfDeptName: 'Department',
        deptLevel: 0,
        opened: true,
        dragDisabled: true,
        isNew: false,
      };
      this.treeData.push(root);

      // Submenu Settings
      const getChildren = parentCode => {
        let children = depts.filter(dept => dept.upperSelfDeptCode === parentCode);
        children = _.sortBy(children, ['deptSequence']);
        children.forEach(d => {
          d.dragDisabled = false;
          d.isNew = false;

          if (_.find(depts, ['upperSelfDeptCode', d.selfDeptCode])) {
            d.opened = false;
            d.children = getChildren(d.selfDeptCode);
          } else {
            // d.disabled = false;
          }
        });
        return children;
      };
      root.children = getChildren(root.selfDeptCode);
      this.treeData = [root];
      this.$refs.tree.initializeData(this.treeData);
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Add department information
     */
    addDeptBtn() {
      /**
       * If added, return.
       */
      if (this.selectedDeptItem.isNew) {
        SDLUtil.alert('sdl.department.message.unSavedDepartment');
        return;
      }

      /**
       * If there is no department code for the selected department, return.
       */
      if (!this.selectedDeptItem.selfDeptCode) {
        SDLUtil.alert('sdl.department.message.selectDepartment');
        return;
      }

      // Extract the maximum value of the sort order of the sub-department for the selected department
      const deptSequence = Math.max(...this.selectedDeptItem.children.map(childDept => childDept.deptSequence), 0);

      /**
       * Set up the department information to be added and apply it to the department tree structure
       */
      const newTreeItem = {
        isNew: true,
        dragDisabled: true,
        upperSelfDeptCode: this.selectedDeptItem.selfDeptCode,
        parentDeptCode: this.selectedDeptItem.selfDeptCode,
        deptSequence: deptSequence + 1,
        deptLevel: this.selectedDeptItem.deptLevel + 1,
        used: true,
      };
      const newTreeItemNode = {
        ...newTreeItem,
        code: newTreeItem.selfDeptCode,
        selfDeptName: 'New Department',
        value: newTreeItem,
      };
      this.selectedDeptItem.addChild(newTreeItemNode);
      this.$refs.tree.initializeData(this.treeData);

      const newItem = _.last(this.selectedDeptItem.children);
      newItem.selected = true;
      this.selectedDeptItem.selected = false;

      this.tempDeptMappingList = [];
      this.deptMappingList = [];

      this.openTreeItemById(newTreeItem.selfDeptCode);
      // Stop dragging if a new menu is registered
      this.treeDraggable = false;

      this.inputStatus = 'insert';
    },
    /**
     * param: string, boolean
     * return: nothing
     * exception: nothing
     * description: Open the specified code in the tree structure
     */
    openTreeItemById(treeCd, isSelected = true) {
      setTimeout(() => {
        this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, node => {
          if (node.model && node.model.code === treeCd) {
            node.model.opened = true;
            const parentDeptCd = node.model.upperSelfDeptCode || node.model.parentDeptCd;
            if (parentDeptCd) {
              this.openTreeItemById(parentDeptCd, false);
            }
            node.model.selected = isSelected;
            if (isSelected) {
              this.treeItemClick(node);
            }
          }
        });
      });
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Open the specified code in the tree structure
     */
    openTreeItemByCode(treeCd) {
      this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, node => {
        if (node.model && node.model.selfDeptCode === treeCd) {
          node.model.opened = true;
          node.model.selected = true;
          let parentNode = node.$parent;
          while (parentNode && parentNode.data) {
            parentNode.data.opened = true;
            parentNode = parentNode.$parent;
          }
        }
      });
    },
    /**
     * param: string, boolean
     * return: nothing
     * exception: nothing
     * description: Delete Department
     */
    removeTreeDeptCd(nodeDeptCd, isExactly = true) {
      const removeTreeFunc = arr => {
        for (let i = 0; i < arr.length; i += 1) {
          const node = arr[i];
          if ((isExactly && node.selfDeptCode === nodeDeptCd)
            || (!isExactly && _.startsWith(node.selfDeptCode, nodeDeptCd))) {
            arr.splice(i, 1);
            break;
          } else {
            removeTreeFunc(node.children);
          }
        }
      };
      removeTreeFunc(this.treeData);
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Calling up a function that deletes a department when there is a target to delete
     */
    deleteDeptBtn() {
      if (this.selectedDept.selfDeptCode) {
        SDLUtil.confirm({
          msg: 'sdl.common.message.doDelete',
          title: 'sdl.common.label.delete',
          okLabel: 'sdl.common.label.delete',
          cancelLabel: 'sdl.common.label.cancel',
          onOkEvt: () => {
            if (this.selectedDept.isNew) {
              // Delete Department from Tree Structure
              this.getTreeDeptList().then(() => {
                if (this.selectedDept.parentDeptCode) {
                  this.openTreeItemById(this.selectedDept.parentDeptCode, false);
                }
                this.initSelected();
              });
            } else {
              /**
               * Department Delete API Callout
               */
              axios
                .delete(`${SDLUtil.API_URL}/admin/department/custom/${this.selectedDept.selfDeptCode}`)
                .then(() => {
                  // Delete Department from Tree Structure
                  this.getTreeDeptList().then(() => {
                    if (this.selectedDept.parentDeptCode) {
                      this.openTreeItemById(this.selectedDept.parentDeptCode, false);
                    }
                    this.initSelected();
                    // SDLUtil.alert('sdl.common.message.deleted');
                  });
                })
                .catch(err => {
                  // Call error alert
                  SDLUtil.errorAlert(err);
                });
            }
          },
          onCancelEvt: () => console.log('cancel'),
        });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Invoke department information registration function after checking the required value input of department information
     */
    saveDeptBtn() {
      /**
       * Validity check for department information
       */
      if (this.inputStatus !== 'init') {
        // validation
        if (SDLUtil.onSubmitValidation('dept')) return;

        /**
         * Call Department Information Registration Functions
         */
        SDLUtil.confirm({
          title: 'sdl.common.label.save',
          msg: 'sdl.common.message.doSave',
          okLabel: 'sdl.common.label.confirm',
          cancelLabel: 'sdl.common.label.cancel',
          onOkEvt: () => this.saveDept(),
          onCancelEvt: () => console.log('cancel'),
        });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Save department
     */
    async saveDept() {
      let check = false;

      const params = {
        ...this.selectedDept,
      };

      // Check registration or modification status values
      if (this.inputStatus === 'insert') {
        const isExistDeptCode = this.existDeptList.map(dept => dept.selfDeptCode);

        // Check if any of the added department information has duplicate department information
        if (isExistDeptCode.indexOf(this.selectedDept.selfDeptCode) > -1) {
          SDLUtil.alert('sdl.department.message.duplicateDepartmentCode');
          return;
        }

        /**
         * Department Information Registration API Callout
         */
        await axios
          .post(`${SDLUtil.API_URL}/admin/department/custom`, params, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              this.getTreeDeptList().then(() => {
                // Select created department information from the data tree that you created that is not in the existing department information
                const newItem = this.existDeptList.find(dept => isExistDeptCode.indexOf(dept.selfDeptCode) === -1);
                // parent item open
                this.openTreeItemById(this.selectedDept.parentDeptCode, false);

                // Reselect items in the existing tree
                const openDeptCode = newItem.selfDeptCode;
                this.openTreeItemById(openDeptCode);
              });
              check = true;
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      } else if (this.inputStatus === 'select') {
        // Department information modification API call
        await axios
          .put(`${SDLUtil.API_URL}//admin/department/custom/${this.selectedDept.selfDeptCode}`, params, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              this.getTreeDeptList().then(() => {
                // Reselect items in the existing tree
                this.openTreeItemByCode(this.selectedDeptItem.selfDeptCode);
              });
              check = true;
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
            check = false;
          });
      }

      // Recall when saving normally
      if (check) {
        // SDLUtil.alert('sdl.common.message.saved');
      }
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: Call before Tree Structure selection
     */
    beforeTreeItemClick(item) {
      const flag = this.selectedDept.isNew;
      if (flag) {
        if (item.selfDeptCode === this.selectedDept.selfDeptCode) {
          return false;
        }
        SDLUtil.alert('sdl.department.message.unSavedDepartment');
      }
      return !flag;
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: Calling up when selecting the tree structure
     */
    treeItemClick(item) {
      const prevDeptCd = this.selectedDeptItem.selfDeptCode;

      // Delete if old department information is added
      if (this.selectedDeptItem.isNew) {
        this.removeTreeDeptCd(prevDeptCd);
      }

      this.selectedDeptItem = item.model;

      // If the selected department information is added, reset and return
      if (item.model.isNew) {
        this.selectedDept = this.selectedDeptItem.value;
        this.tempDeptMappingList = [];
        this.deptMappingList = [];
        return;
      }

      // Return if top department
      if (this.selectedDeptItem.selfDeptCode === 'DEPT') {
        return;
      }

      const params = {
        selfDeptCode: this.selectedDeptItem.selfDeptCode,
      };

      /**
       * Department Detail Query API Callout
       */
      axios
        .get(`${SDLUtil.API_URL}/admin/department/custom/dept-infos?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          this.selectedDept = data;
          this.selectedDept.parentDeptCd = this.selectedDeptItem.upperSelfDeptCode;

          // Call mapped LDAP department lookup function
          this.getMappingDeptList();

          this.inputStatus = 'select';
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
          this.selectedDept = {};
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call before performing drag-and-drop functions
     */
    treeItemDragStart() {
      /**
       * Check for new departments
       */
      const isNewDeptCode = this.treeData.filter(dept => dept.isNew === true);

      if (isNewDeptCode.length > 0) {
        SDLUtil.alert('sdl.department.message.unSavedDepartment');
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call on Drag and Drop
     */
    treeItemDrop(node, item, draggedItem) {
      SDLUtil.confirm({
        msg: 'sdl.common.message.doSave',
        title: 'sdl.common.label.save',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => {
          const params = item.children
            .map((dept, index) => ({
              targetId: dept.selfDeptCode,
              newParentDeptLevel: item.deptLevel,
              moveToDeptSequence: index + 1,
              newParentId: item.selfDeptCode,
              isDifferent: dept.deptSequence !== index + 1 || draggedItem.selfDeptCode === dept.selfDeptCode,
            }))
            .filter(dept => dept.isDifferent === true)
            .map(dept => {
              delete dept.isDifferent;
              return dept;
            });
          // Move Department
          this.saveMoveDept(params);
        },
        onCancelEvt: () => {
          this.getTreeDeptList().then(() => {
            // Reselect items in the existing tree
            this.openTreeItemByCode(draggedItem.selfDeptCode);
          });
        },
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Move Department
     */
    saveMoveDept(params) {
      const fetchURL = param => axios.put(`${SDLUtil.API_URL}/admin/department/custom`, param);
      // Launch Loading bar
      SDLUtil.showLoadingBar(true);
      Promise.all(params.map(fetchURL))
        .then(() => {
          // If the menu name is changed, GNB and LNB labeling is processed.
          this.clearCache();
          this.getTreeDeptList().then(() => {
            // Reselect items in the existing tree
            const openDeptCode = this.selectedDept.selfDeptCode;
            this.openTreeItemByCode(openDeptCode);
          });
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Mapping LDAP Department Lookup for Selected Departments
     */
    getMappingDeptList() {
      axios
        .get(`${SDLUtil.API_URL}/admin/department/custom/mappings/${this.selectedDeptItem.selfDeptCode}`)
        .then(({ data }) => {
          this.deptMappingList = data;
          // Initialize LDAP Mapping departments for selected temporarily saved departments
          this.tempDeptMappingList = [];
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call LDAP Department List Popup
     */
    openDeptPopUp() {
      SDLUtil.show(
        DeptPopup,
        {
          rtnFunc: args => {
            this.checkDeptList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Compare target list with list of existing or added LDAP departments and add them to list of existing and temporarily stored LDAP departments
     */
    checkDeptList(deptPopupList) {
      for (let i = 0; i < deptPopupList.length; i += 1) {
        const deptPopupItem = deptPopupList[i];

        /**
         * Check existing or stored department mapping list or added (unstored) department mapping list
         */
        if (
          !(
            this.deptMappingList.find(deptItem => deptItem.deptCode === deptPopupItem.deptCode)
            || this.tempDeptMappingList.find(tempDeptListItem => tempDeptListItem.deptCode === deptPopupItem.deptCode)
          )
        ) {
          this.tempDeptMappingList.push({
            deptCode: deptPopupItem.deptCode,
            deptName: deptPopupItem.deptName,
          });
          this.deptMappingList.push({
            deptCode: deptPopupItem.deptCode,
            deptName: deptPopupItem.deptName,
          });
        }
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call LDAP Department Mapping Storage function after verifying that department is selected
     */
    saveMappingDeptBtn() {
      if (this.selectedDeptItem.selfDeptCode === undefined) {
        SDLUtil.alert('sdl.department.message.selectSavedDepartment');
        return;
      }

      SDLUtil.confirm({
        title: 'sdl.common.label.save',
        msg: 'sdl.common.message.doSave',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.saveMappingDept(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Save LDAP Mapping Department for Selected Departments
     */
    saveMappingDept() {
      if (this.tempDeptMappingList.length > 0) {
        // The top-level department that becomes root is returned
        if (this.selectedDept.selfDeptCode === 'DEPT') {
          SDLUtil.alert('sdl.department.message.selectDepartment');
          return;
        }

        /**
         * Invoke LDAP Mapping Department Enrollment API for selected departments
         */
        axios
          .post(
            `${SDLUtil.API_URL}/admin/department/custom/mappings/${this.selectedDept.selfDeptCode}`,
            this.tempDeptMappingList,
            {
              headers: { 'Content-Type': 'application/json' },
            },
          )
          .then(response => {
            if (response.status === 200) {
              // Invoke LDAP Mapping Department lookup function for selected department
              this.getMappingDeptList();
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }
    },
    /**
     * param: string
     * return: nothing
     * exception: nothing
     * description: Calling up functions to delete a Mapped LDAP department
     */
    executeDelMappingDept(deptCode) {
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteMappingDept(deptCode),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Delete Mapped LDAP Department
     */
    deleteMappingDept(deptCode) {
      let tmpDeptChk = false;

      // Verify Added (Stored) LDAP Department
      const tempDeptListIndex = this.tempDeptMappingList.findIndex(deptItem => deptItem.deptCode === deptCode);

      if (tempDeptListIndex > -1) {
        tmpDeptChk = true;
        this.tempDeptMappingList.splice(tempDeptListIndex, 1);
        this.deptMappingList.splice(this.deptMappingList.findIndex(deptItem => deptItem.deptCode === deptCode), 1);
      }

      if (!tmpDeptChk) {
        /**
         * Calling up the Mapped LDAP Department Delete API for Mapped LDAP departments stored in DB
         */
        axios
          .delete(`${SDLUtil.API_URL}/admin/department/custom/mappings/${this.selectedDept.selfDeptCode}/${deptCode}`)
          .then(response => {
            if (response.status === 200) {
              // Invoke LDAP Mapping Department lookup function for selected department
              this.getMappingDeptList();
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Initialization
     */
    initSelected() {
      this.selectedDept = {};
      this.selectedDeptItem = {};
      this.deptMappingList = [];
      this.tempDeptMappingList = [];
      SDLUtil.clearAllIsInvalidCss();
    },
  },
  created() {
    SDLUtil.showLoadingBar(true);
    this.getTreeDeptList().then(() => SDLUtil.showLoadingBar(false));

    this.inputStatus = 'init';
  },
};
</script>
<style>
/* Tree Item Selection Class */
.tree-selected {
  background-color: #e9ecef !important;
}
</style>
