<!--
  Program: menu management
  Author: SDL
  Brief: menu management page
-->
<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.menu.label.menuList') }}</h4>
          <div class="float-end">
            <button type="button" class="btn btn-secondary btn-sm" @click="deleteMenuBtn">
              {{ $t('sdl.common.label.delete') }}
            </button>
            <button type="button" class="btn btn-secondary btn-sm" @click="addMenuBtn">
              {{ $t('sdl.common.label.add') }}
            </button>
          </div>
        </div>
        <!-- menu tree -->
        <div class="ui--box-tree">
          <sdl-tree
            ref="tree"
            :data="treeData"
            :before-item-click="beforeTreeItemClick"
            :multiple="false"
            text-field-name="localeLabel"
            whole-row
            :draggable="true"
            @item-drag-start="treeItemDragStart"
            @item-drop="treeItemDrop"
            @item-click="treeItemClick"
            drag-over-background-color="#e9ecef"
          />
        </div>
      </div>
      <div class="col-8">
        <!-- menu information -->
        <div class="ui--form-heading clearfix mb-3">
          <h4 class="d-inline-block">{{ $t('sdl.menu.label.basicInfo') }}</h4>
          <div class="float-end">
            <button type="button" class="btn btn-primary btn-sm" @click="saveMenu">
              {{ $t('sdl.common.label.save') }}
            </button>
          </div>
        </div>
        <form class="needs-validation" novalidate @submit.prevent>
          <div class="row">
            <div class="col-6 mb-3">
              <label for="menuDefault">
                {{ $t('sdl.menu.menuDefault') }}
                <span class="ui--text-required">&#42;</span>
              </label>
              <input type="text" class="form-control" id="menuDefault" v-model="selectedMenu.label" :readonly="selectedMenu.label === undefined" v-validation="{ groupId: 'menu' }" errorMessage="sdl.samsung.validate.required" />
              <div class="invalid-feedback">Writer is required.</div>
            </div>
            <div class="col-6 mb-3" v-for="locale in $i18n.availableLocales" :key="locale">
              <label :for="'menu' + locale">
                {{ $t('sdl.menu.menuNameLang', [locale]) }}
              </label>
              <input v-if="selectedMenu.labelJson" type="text" class="form-control" :id="'menu' + locale" v-model="selectedMenu.labelJson[locale]" :readonly="selectedMenu.label === undefined" />
              <input v-else type="text" class="form-control" :id="'menu' + locale" :readonly="selectedMenu.label === undefined" />
              <div class="invalid-feedback">Writer is required.</div>
            </div>
          </div>

          <hr class="mb-4" />

          <div class="row">
            <div class="col-6 mb-3">
              <label>{{ $t('sdl.menu.label.menuUsed') }}</label>
              <div class="d-block w-100">
                <div class="form-check form-check-inline">
                  <input id="useY" class="form-check-input" type="radio" name="useYn" :value="true" v-model="selectedMenu.used" :disabled="selectedMenu.used === undefined" />
                  <label for="useY" class="form-check-label">{{ $t('sdl.common.label.use') }}</label>
                </div>
                <div class="form-check form-check-inline">
                  <input id="useN" class="form-check-input" type="radio" name="useYn" :value="false" v-model="selectedMenu.used" :disabled="selectedMenu.used === undefined" />
                  <label for="useN" class="form-check-label">{{ $t('sdl.common.label.nonUse') }}</label>
                </div>
              </div>
            </div>
            <!-- 차후 개선사항에 들어갈 예정 -->
            <div class="col-6 mb-3" v-if="false && selectedMenu.menuLevel === 2">
              <label>2레벨 메뉴아이콘</label>
              <div class="d-block w-100">
                <div class="form-check form-check-inline">
                  <input class="form-check-input" type="radio" id="iconUse" :value="true" />
                  <label class="form-check-label" for="iconUse">{{ $t('sdl.common.label.use') }}</label>
                </div>
                <div class="form-check form-check-inline">
                  <input class="form-check-input" type="radio" id="iconNonUse" :value="false" />
                  <label class="form-check-label" for="iconNonUse">{{ $t('sdl.common.label.nonUse') }}</label>
                </div>
                <div class="form-check-inline">
                  <button class="btn btn-outline-secondary ui--btn-xs" @click.prevent="showMenuIconLayer = !showMenuIconLayer">메뉴아이콘 선택</button>
                </div>
                <em class="icon-grid"></em>
                <div class="select-icons clearfix" v-show="showMenuIconLayer">
                  <h5>
                    메뉴아이콘 선택
                    <button type="button" class="btn-close" @click="showMenuIconLayer = false">
                      <i class="bi bi-x"></i>
                    </button>
                  </h5>
                  <div class="icon-layout">
                    <button class="btn" title="Home"><em class="icon-home"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="List"><em class="icon-list"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="User"><em class="icon-user"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="People"><em class="icon-people"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Settings"><em class="icon-settings"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Phone"><em class="icon-phone"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Map"><em class="icon-map"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Plus"><em class="icon-plus"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Check"><em class="icon-check"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Ban"><em class="icon-ban"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Clock"><em class="icon-clock"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Hourglass"><em class="icon-hourglass"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Cup"><em class="icon-cup"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Smartphone"><em class="icon-screen-smartphone"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Desktop"><em class="icon-screen-desktop"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Tablet"><em class="icon-screen-tablet"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn active" title="Grid"><em class="icon-grid"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Layers"><em class="icon-layers"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Frame"><em class="icon-frame"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Info"><em class="icon-info"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Chemistry"><em class="icon-chemistry"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Chart"><em class="icon-chart"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Pie-chart"><em class="icon-pie-chart"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Graph"><em class="icon-graph"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Speedometer"><em class="icon-speedometer"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Pencil"><em class="icon-pencil"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Note"><em class="icon-note"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Folder"><em class="icon-folder"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Picture"><em class="icon-picture"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Document"><em class="icon-doc"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Documents"><em class="icon-docs"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Notebook"><em class="icon-notebook"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Printer"><em class="icon-printer"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Bubble"><em class="icon-bubble"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Bubbles"><em class="icon-bubbles"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Speech"><em class="icon-speech"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Book-open"><em class="icon-book-open"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Share-alt"><em class="icon-share-alt"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Envelope"><em class="icon-envelope"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Question"><em class="icon-question"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Magnifier"><i class="bi bi-search"></i></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Calendar"><em class="icon-calendar"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Calculator"><em class="icon-calculator"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Cursor"><em class="icon-cursor"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Cursor-move"><em class="icon-cursor-move"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Anchor"><em class="icon-anchor"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Tag"><em class="icon-tag"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Pin"><em class="icon-pin"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Location-pin"><em class="icon-location-pin"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Direction"><em class="icon-direction"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Compass"><em class="icon-compass"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Globe"><em class="icon-globe"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Bell"><em class="icon-bell"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Microphone"><em class="icon-microphone"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Earphones"><em class="icon-earphones"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Volume"><em class="icon-volume-1"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Basket"><em class="icon-basket"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Briefcase"><em class="icon-briefcase"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Wallet"><em class="icon-wallet"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Credit Card"><em class="icon-credit-card"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Cloud-download"><em class="icon-cloud-download"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Cloud-upload"><em class="icon-cloud-upload"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Disc"><em class="icon-disc"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Drawer"><em class="icon-drawer"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Heart"><em class="icon-heart"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Star"><em class="icon-star"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Energy"><em class="icon-energy"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Fire"><em class="icon-fire"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Bulb"><em class="icon-bulb"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Rocket"><em class="icon-rocket"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Link"><em class="icon-link"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Paper Clip"><em class="icon-paper-clip"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Target"><em class="icon-target"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Lock"><em class="icon-lock"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Shield"><em class="icon-shield"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Trophy"><em class="icon-trophy"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Diamond"><em class="icon-diamond"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Plane"><em class="icon-plane"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Puzzle"><em class="icon-puzzle"></em></button>
                  </div>
                  <div class="icon-layout">
                    <button class="btn" title="Present"><em class="icon-present"></em></button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-6 mb-3">
              <label for="menuLevel">{{ $t('sdl.menu.menuLevel') }}</label>
              <input type="text" class="form-control" id="menuLevel" readonly v-model="selectedMenu.menuLevel" />
            </div>
            <div class="col-6 mb-3">
              <label for="menuSequence">{{ $t('sdl.commonCode.label.order') }}</label>
              <input type="number" class="form-control" id="menuSequence" min="0" v-model.number="selectedMenu.menuSequence" :readonly="selectedMenu.menuSequence === undefined" />
            </div>
            <div class="col-6 mb-3">
              <label for="menuTypeCodeId">{{ $t('sdl.menu.menuType') }}</label>
              <select class="form-select" id="menuTypeCodeId" v-model="selectedMenu.menuTypeCodeId" :disabled="selectedMenu.menuTypeCodeId === undefined">
                <option v-for="code in menuTypeCodeList" :key="code.codeId" :value="code.codeId">
                  {{ getLabel(code) }}
                </option>
              </select>
            </div>
            <div class="col-6 mb-3">
              <label for="menuUsePeriodCode">{{ $t('sdl.menu.menuUsePeriod') }}</label>
              <select class="form-select" id="menuUsePeriodCode" v-model="selectedMenu.menuUsePeriodCode" :disabled="selectedMenu.menuUsePeriodCode === undefined">
                <option v-for="code in menuUsePeriodList" :key="code.menuUsePeriodCode" :value="code.menuUsePeriodCode">{{ code.menuUsePeriodName }}</option>
              </select>
            </div>
            <div class="col-6 mb-3">
              <label>
                {{ $t('sdl.menu.label.externalUrlUsed') }}
                <span class="ui--text-required" v-show="selectedMenu.externalUrlUsed === true">&#42;</span>
              </label>
              <div class="d-block w-100">
                <div class="form-check form-check-inline">
                  <input
                    id="externalY"
                    class="form-check-input"
                    type="radio"
                    name="externalYn"
                    :value="true"
                    v-model="selectedMenu.externalUrlUsed"
                    :disabled="selectedMenu.externalUrlUsed === undefined"
                    v-validation="{ groupId: 'menu' }"
                  />
                  <label for="externalY" class="form-check-label">{{ $t('sdl.common.label.use') }}</label>
                </div>
                <div class="form-check form-check-inline">
                  <input
                    id="externalN"
                    class="form-check-input"
                    type="radio"
                    name="externalYn"
                    :value="false"
                    v-model="selectedMenu.externalUrlUsed"
                    :disabled="selectedMenu.externalUrlUsed === undefined"
                    v-validation="{ groupId: 'menu' }"
                  />
                  <label for="externalN" class="form-check-label">{{ $t('sdl.common.label.nonUse') }}</label>
                </div>
              </div>
              <!-- 사용 선택시 -->
              <div class="mt-1 bg-light rounded p-3 fade show" style="display: block">
                <div class="input-group">
                  <span class="input-group-text">URL</span>
                  <input type="text" class="form-control" v-model="selectedMenu.externalUrl" :readonly="selectedMenu.externalUrlUsed !== true" v-validation="{ groupId: 'menu' }" errorMessage="sdl.samsung.validate.required" />
                </div>
              </div>
              <!-- //사용 선택시 -->
            </div>
          </div>

          <div class="row" v-show="false">
            <div class="col-12 mb-3">
              <label for="menu-url">{{ $t('sdl.menu.label.externalUrl') }}</label>
              <input type="text" class="form-control" id="menu-url" v-model="selectedMenu.externalUrl" :readonly="selectedMenu.externalUrlUsed !== true" />
            </div>
          </div>
        </form>
      </div>
    </div>

    <hr class="mb-4" />

    <div class="ui--form-heading clearfix mb-3" v-if="selectedMenu.menuId !== undefined && selectedMenu.externalUrlUsed !== true && selectedMenu.menuLevel > 1">
      <h4 class="d-inline-block">{{ $t('sdl.menu.label.linkList') }}</h4>
      <div class="float-end">
        <button type="button" class="btn btn-secondary btn-sm" @click="openBoardPopup('user')">
          {{ $t('sdl.menu.label.userBoard') }}
        </button>
        <button type="button" class="btn btn-secondary btn-sm" @click="openBoardPopup('admin')">
          {{ $t('sdl.menu.label.adminBoard') }}
        </button>
      </div>
    </div>
    <!-- Header & buttons -->
    <div class="ui--form-heading clearfix" v-if="selectedMenu.menuId !== undefined && selectedMenu.externalUrlUsed !== true && selectedMenu.menuLevel > 1">
      <h5 class="d-inline-block">{{ $t('sdl.menu.label.pageList') }}</h5>
      <div class="float-end">
        <button type="button" class="btn btn-secondary btn-sm" @click="addPage()">
          {{ $t('sdl.common.label.add') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="savePage()">
          {{ $t('sdl.common.label.save') }}
        </button>
      </div>
    </div>
    <!-- TABLE  Area-->
    <table class="table table-bordered ui--table" v-if="selectedMenu.menuId !== undefined && selectedMenu.externalUrlUsed !== true && selectedMenu.menuLevel > 1">
      <colgroup>
        <col style="width: 8%" />
        <col style="width: 14%" />
        <col style="width: 15%" />
        <col style="width: 25%" />
        <col style="width: 25%" />
        <col style="width: 8%" />
        <col style="width: 5%" />
      </colgroup>
      <thead>
        <tr>
          <!-- <th scope="col"></th> -->
          <th scope="col">Default</th>
          <th scope="col">Type</th>
          <th scope="col">
            {{ $t('sdl.menu.label.name') }}
            <span class="ui--text-required">&#42;</span>
          </th>
          <th scope="col">
            Path
            <span class="ui--text-required">&#42;</span>
          </th>
          <th scope="col">
            Component Name
            <span class="ui--text-required">&#42;</span>
          </th>
          <th scope="col">{{ $t('sdl.common.label.used') }}</th>
          <th scope="col">{{ $t('sdl.common.label.delete') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(page, index) in pageList" :key="page.pageId" :class="{ alert: page.duplicate }">
          <td class="text-center">
            <input type="radio" name="defaulted" v-model="page.defaulted" :value="true" @click="changeDefault(page)" @change="page.isEdited = true" />
          </td>
          <td>
            <select class="form-select" v-model="page.authorizationType" @change="page.isEdited = true">
              <option value="READ">READ</option>
              <option value="UPDATE">UPDATE</option>
              <option value="EXECUTE">EXECUTE</option>
              <option value="DOWNLOAD">DOWNLOAD</option>
            </select>
          </td>
          <td>
            <input type="text" class="form-control" v-model.trim="page.pageName" @keyup="page.isEdited = true" v-validation="{ groupId: 'page' }" errorMessage="sdl.samsung.validate.required" />
          </td>
          <td>
            <input type="text" class="form-control" v-model.trim="page.pagePath" @keyup="(page.isEdited = true), checkDuplication('page')" v-validation="{ groupId: 'page' }" errorMessage="sdl.samsung.validate.required" />
          </td>
          <td>
            <input type="text" class="form-control" v-model.trim="page.componentName" @keyup="page.isEdited = true" v-validation="{ groupId: 'page' }" errorMessage="sdl.samsung.validate.required" />
          </td>
          <td>
            <select class="form-select" v-model="page.used" @change="page.isEdited = true">
              <option :value="true">Y</option>
              <option :value="false">N</option>
            </select>
          </td>
          <td class="text-center">
            <button class="btn btn-outline-secondary ui--btn-xs" @click="deletePage(page, index)">
              {{ $t('sdl.common.label.delete') }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- Header & buttons -->
    <div class="ui--form-heading clearfix mt-4" v-if="selectedMenu.menuId !== undefined && selectedMenu.externalUrlUsed !== true && selectedMenu.menuLevel > 1">
      <h5 class="d-inline-block">{{ $t('sdl.menu.label.apiList') }}</h5>
      <div class="float-end">
        <button type="button" class="btn btn-secondary btn-sm" @click="addApi()">
          {{ $t('sdl.common.label.add') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="saveApi()">
          {{ $t('sdl.common.label.save') }}
        </button>
      </div>
    </div>
    <table class="table table-bordered ui--table" v-if="selectedMenu.menuId !== undefined && selectedMenu.externalUrlUsed !== true && selectedMenu.menuLevel > 1">
      <colgroup>
        <col style="width: 12%" />
        <col style="width: 15%" />
        <col style="width: 15%" />
        <col style="width: 15%" />
        <col style="width: 25%" />
        <col style="width: 8%" />
        <col style="width: 5%" />
      </colgroup>
      <thead>
        <tr>
          <th scope="col">Type</th>
          <th scope="col">
            {{ $t('sdl.menu.label.name') }}
            <span class="ui--text-required">&#42;</span>
          </th>
          <th scope="col">HTTP Method</th>
          <th scope="col">
            {{ $t('sdl.menu.label.serverName') }}
            <span class="ui--text-required">&#42;</span>
          </th>
          <th scope="col">
            URL
            <span class="ui--text-required">&#42;</span>
          </th>
          <th scope="col">{{ $t('sdl.common.label.used') }}</th>
          <th scope="col">{{ $t('sdl.common.label.delete') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(api, index) in apiList" :key="api.pageId" :class="{ alert: api.duplicate }">
          <td>
            <select class="form-select" v-model="api.authorizationType" @change="api.isEdited = true">
              <option value="READ">READ</option>
              <option value="UPDATE">UPDATE</option>
              <option value="EXECUTE">EXECUTE</option>
              <option value="DOWNLOAD">DOWNLOAD</option>
            </select>
          </td>
          <td>
            <input type="text" class="form-control" v-model.trim="api.apiName" @keyup="api.isEdited = true" v-validation="{ groupId: 'api' }" errorMessage="sdl.samsung.validate.required" />
          </td>
          <td>
            <select class="form-select" v-model="api.httpMethod" @change="(api.isEdited = true), checkDuplication('api')">
              <option value="GET">GET</option>
              <option value="POST">POST</option>
              <option value="PUT">PUT</option>
              <option value="PATCH">PATCH</option>
              <option value="DELETE">DELETE</option>
            </select>
          </td>
          <td>
            <select class="form-select" v-model="api.serverId" @change="api.isEdited = true">
              <option :value="server.codeId" v-for="server in apiServerList" :key="server.codeId">
                {{ getLabel(server) }}
              </option>
            </select>
          </td>
          <td>
            <input type="text" class="form-control" v-model.trim="api.apiUrl" @keyup="(api.isEdited = true), checkDuplication('api')" v-validation="{ groupId: 'api' }" errorMessage="sdl.samsung.validate.required" />
          </td>
          <td>
            <select class="form-select" v-model="api.used" @change="api.isEdited = true">
              <option :value="true">Y</option>
              <option :value="false">N</option>
            </select>
          </td>
          <td class="text-center">
            <button class="btn btn-outline-secondary ui--btn-xs" @click="deleteApi(api, index)">
              {{ $t('sdl.common.label.delete') }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!--//Contents Area -->
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import axios from 'axios';
import _ from 'lodash';
import SelectBoardPopup from './SelectBoardPopup.vue';
import SDLUtil from '@/utils/SDLUtil';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  mixins: [SDLLocale],
  data() {
    return {
      menuTypeCodeList: [],
      menuUsePeriodList: [],
      apiServerList: [],
      treeData: [],
      treeDraggable: true,
      menuRawData: [], // parentId를 찾기 위한 용도
      selectedMenu: {}, // detail용
      selectedMenuItem: {}, // tree용
      pageList: [],
      apiList: [],
      showMenuIconLayer: false,
    };
  },
  created() {
    // menu type
    this.menuTypeCodeList = SDLUtil.getCommCodeList({ commCodeTypeId: 'MENUTYPE' });
    // menu use period
    axios.get(`${SDLUtil.API_URL}/commcode/menu-use-period`).then(({ data }) => {
      this.menuUsePeriodList = data;
    });
    // common codes
    axios.get(`${SDLUtil.API_URL}/commcode/groupcodes/SERVER/commcodes`).then(({ data }) => {
      this.apiServerList = data;
    });

    // menu information call
    SDLUtil.showLoadingBar(true);
    this.getTreeMenuService().then(() => SDLUtil.showLoadingBar(false));
  },
  methods: {
    ...mapActions(['getMenus', 'getMyMenus', 'clearCache']),
    getTreeMenuService() {
      return axios.get(`${SDLUtil.API_URL}/auth/menus/menu-mgmt/level`).then(({ data }) => {
        this.makeTreeData(data);
        this.menuRawData = data;
        this.treeDraggable = true; // drag unlocking
      });
    },
    makeTreeData(data) {
      const menus = data.map(menu => ({
        ...menu,
        id: menu.menuId,
      }));
      // Set Locale Label
      menus.map(m => {
        m.localeLabel = this.getLabel(m);
        return m;
      });
      // Finding the Top Menu
      const root = menus.find(menu => menu.menuLevel === 0);
      root.opened = true;
      root.dragDisabled = true;

      const getChildren = parentId => {
        let children = menus.filter(menu => menu.upperSysResourceId === parentId);
        children = _.sortBy(children, ['menuSequence']);
        children.forEach(m => {
          m.dragDisabled = false;
          // If there is a child node
          if (_.find(menus, ['upperSysResourceId', m.menuId])) {
            m.opened = false;
            m.children = getChildren(m.menuId);
          } else {
            // If no child node exists, icon can be changed
            // m.icon = 'tree-node';
            // delete m.opened;
          }
        });
        return children;
      };
      root.children = getChildren(root.menuId);
      this.treeData = [root];
      this.$refs.tree.initializeData(this.treeData);
    },
    removeTreeId(nodeId, isExactly = true) {
      const removeTreeFunc = arr => {
        for (let i = 0; i < arr.length; i += 1) {
          const node = arr[i];
          if ((isExactly && node.id === nodeId) || (!isExactly && _.startsWith(node.id, nodeId))) {
            arr.splice(i, 1);
            break;
          } else {
            removeTreeFunc(node.children);
          }
        }
      };

      removeTreeFunc(this.treeData);
    },
    beforeTreeItemClick(item) {
      // console.info('beforeTreeItemClick', item);
      const flag = _.startsWith(this.selectedMenu.menuId, 'NEW_');
      if (flag) {
        if (item.menuId === this.selectedMenu.menuId) {
          return false;
        }
        SDLUtil.alert('sdl.menu.message.valid.save');
      }
      return !flag;
    },
    treeItemClick(item) {
      // clear validation
      SDLUtil.clearAllIsInvalidCss();

      const prevId = this.selectedMenuItem.id;
      // console.info(`${prevId} => ${item.model.id}`);
      if (_.startsWith(prevId, 'NEW_')) {
        // Remove the existing unsaved 'NEW _'
        this.removeTreeId(prevId);
      }

      this.selectedMenuItem = item.model;
      this.showMenuIconLayer = false;

      // If you click on a new menu that has not been saved, do not communicate
      if (_.startsWith(item.model.id, 'NEW_')) {
        this.selectedMenu = this.selectedMenuItem.value;
        this.pageList = [];
        this.apiList = [];
        // console.info('this.selectedMenu', this.selectedMenu);
        return;
      }

      SDLUtil.showLoadingBar(true);
      axios
        .all([axios.get(`${SDLUtil.API_URL}/auth/menus/${item.model.id}`), axios.get(`${SDLUtil.API_URL}/auth/menus/${item.model.id}/pages`), axios.get(`${SDLUtil.API_URL}/auth/menus/${item.model.id}/apis`)])
        .then(
          axios.spread((menuRes, pageRes, apiRes) => {
            this.selectedMenu = menuRes.data;
            this.selectedMenu = {
              ...menuRes.data,
              parentId: this.selectedMenuItem.upperSysResourceId,
            };

            this.originMenuLabelKey = this.selectedMenu.menuLabelKey;

            this.pageList = pageRes.data.map(page => ({
              ...page,
              isEdited: false,
              duplicate: false,
            }));
            this.apiList = apiRes.data.map(api => ({
              ...api,
              isEdited: false,
              duplicate: false,
            }));
            SDLUtil.showLoadingBar(false);
          }),
        )
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
          this.selectedMenu = {};
          this.pageList = [];
          this.apiList = [];
        });
    },
    treeItemDragStart() {
      // console.info('treeItemDragStart', node, item, e);

      // #1 Policy - Block drag drops when creating a new menu.
      if (this.selectedMenu && this.selectedMenu.menuId && this.selectedMenu.menuId.startsWith('NEW_')) {
        SDLUtil.alert('sdl.menu.message.valid.save');
      }

      // #2 Policy - Delete the new menu being created and proceed with the drag.
      // if (this.selectedMenu && this.selectedMenu.menuId && this.selectedMenu.menuId.startsWith('NEW_')) {
      //   this.selectedMenu = {};
      // }
      // this.removeTreeId('NEW_', false);
    },
    treeItemDrop(node, item, draggedItem) {
      // item - transfer folder, draggedItem - dragging target
      // console.info('해당항목 아래 들어감 => ', item.localeLabel);
      // console.info('드래그를 한 항목 => ', draggedItem.localeLabel);
      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((menu, index) => ({
              parentMenuId: item.menuId,
              parentMenuLevel: item.menuLevel,
              menuId: menu.menuId,
              moveToMenuSequence: index + 1,
              isDifferent: menu.menuSequence !== index + 1 || draggedItem.menuId === menu.menuId,
            }))
            .filter(menu => menu.isDifferent === true)
            .map(menu => {
              delete menu.isDifferent;
              return menu;
            });

          this.saveMoveMenu(params);
        },
        onCancelEvt: () => {
          this.getTreeMenuService().then(() => {
            // Reselect items in the existing tree
            const openId = this.selectedMenu.menuId;
            this.openTreeItemById(openId, true);
          });
        },
      });
    },
    saveMoveMenu(params) {
      const fetchURL = param => axios.put(`${SDLUtil.API_URL}/auth/menus/move-menu`, param);
      SDLUtil.showLoadingBar(true);
      Promise.all(params.map(fetchURL))
        .then(() => {
          console.info('update success');
          // If the menu name is changed, GNB and LNB labeling is processed.
          this.clearCache();
          this.getMenus(true);
          // The label name may have been changed in the tree, so apply
          this.getTreeMenuService().then(() => {
            // Reselect items in the existing tree
            const openId = this.selectedMenu.menuId;
            this.openTreeItemById(openId, true);
          });
          SDLUtil.showLoadingBar(false);
          // SDLUtil.alert('sdl.common.message.saved');
        })
        .catch(err => {
          console.error(err);
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },

    saveMenu() {
      if (this.selectedMenu.menuId) {
        // validation
        if (SDLUtil.onSubmitValidation('menu')) return;

        if (this.selectedMenu.label.trim() === '' || (this.selectedMenu.externalUrlUsed === true && (this.selectedMenu.externalUrl === undefined || this.selectedMenu.externalUrl.trim() === ''))) {
          SDLUtil.alert('sdl.commonCode.message.valid.mandatory');
          return;
        }

        SDLUtil.confirm({
          msg: 'sdl.common.message.doSave',
          title: 'sdl.common.label.save',
          okLabel: 'sdl.common.label.confirm',
          cancelLabel: 'sdl.common.label.cancel',
          onOkEvt: () => this.saveMenuService(),
          onCancelEvt: () => console.log('cancel'),
        });
      }
    },
    saveMenuService() {
      if (this.selectedMenu.menuId && this.selectedMenu.isNew !== true) {
        // update
        axios
          .put(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}`, this.selectedMenu)
          .then(() => {
            // console.info('update success');
            // If the menu name is changed, GNB and LNB labeling is processed.
            this.clearCache();
            this.getMenus(true);
            this.getMyMenus();
            // The label name may have been changed in the tree, so apply
            this.getTreeMenuService().then(() => {
              // Reselect items in the existing tree
              const openId = this.selectedMenu.menuId;
              this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, node => {
                if (node.model && node.model.id === openId) {
                  node.model.opened = true;
                  node.model.selected = true;
                  let parentNode = node.$parent;
                  while (parentNode && parentNode.data) {
                    parentNode.data.opened = true;
                    parentNode = parentNode.$parent;
                  }
                }
              });
            });
            // SDLUtil.alert('sdl.common.message.saved');
          })
          .catch(err => {
            console.info('fail', err);
            SDLUtil.errorAlert(err);
          });
      } else {
        // new
        // console.info('신규 메뉴 저장', this.selectedMenu);

        const existMenuIds = this.menuRawData.map(m => m.menuId);

        const tempMenuId = this.selectedMenu.menuId;
        const param = {
          ...this.selectedMenu,
        };
        delete param.menuId;
        delete param.isNew;

        axios
          .post(`${SDLUtil.API_URL}/auth/menus`, param)
          .then(() => {
            // If the menu name is changed, GNB and LNB labeling is processed.
            this.clearCache();
            this.getMenus(true);
            this.getTreeMenuService().then(() => {
              // Select from the generated data tree
              const newItem = this.menuRawData.find(m => existMenuIds.indexOf(m.menuId) === -1);

              // parent item open
              // console.info('부모아이템', this.selectedMenu.parentId);
              this.openTreeItemById(this.selectedMenu.parentId, false);

              // Reselect items in the existing tree
              const openId = newItem.menuId;
              this.openTreeItemById(openId);
            });
          })
          .catch(err => {
            console.error(err);
            SDLUtil.errorAlert(err);
            this.selectedMenu.menuId = tempMenuId;
          });
      }
    },
    addMenuBtn() {
      if (!this.selectedMenu.menuId) {
        // No menu selected
        SDLUtil.alert('sdl.common.message.selectRow');
        return;
      }

      if (_.startsWith(this.selectedMenu.menuId, 'NEW_')) {
        SDLUtil.alert('sdl.menu.message.valid.save');
        return;
      }

      const menuSequence = Math.max(...this.selectedMenuItem.children.map(childMenu => childMenu.menuSequence), 0);

      const newLabelJson = this.$i18n.availableLocales.reduce((target, key) => {
        target[key] = '';
        return target;
      }, {});
      const newTreeItem = {
        isNew: true, // 신규 트리 노드
        dragDisabled: true,
        menuId: `NEW_${new Date().getTime()}`,
        sysId: 'SYSTEM',
        sysResourceTypeCodeId: this.selectedMenuItem.menuId,
        parentId: this.selectedMenuItem.menuId,
        label: '',
        labelJson: newLabelJson,
        menuSequence: menuSequence + 1,
        menuLevel: this.selectedMenuItem.menuLevel + 1,
        externalUrl: '',
        externalUrlUsed: false,
        menuTypeCodeId: this.menuTypeCodeList.length > 0 ? this.menuTypeCodeList[0].codeId : '',
        menuUsePeriodCode: this.menuUsePeriodList.length > 0 ? this.menuUsePeriodList[0].menuUsePeriodCode : '',
        used: true,
      };
      const newTreeItemNode = {
        ...newTreeItem,
        id: newTreeItem.menuId,
        localeLabel: 'New Menu',
        value: newTreeItem,
      };
      this.selectedMenuItem.addChild(newTreeItemNode);
      this.$refs.tree.initializeData(this.treeData);

      // Then choose
      const newItem = _.last(this.selectedMenuItem.children);
      newItem.selected = true;
      this.selectedMenuItem.selected = false;
      // console.info('this.selectedMenuItem', this.selectedMenuItem);
      // this.treeItemClick(newTreeItemNode);
      // this.selectedMenu = newTreeItem;
      this.pageList = [];
      this.apiList = [];

      this.openTreeItemById(newTreeItem.menuId);
      // Stop dragging if a new menu is registered
      this.treeDraggable = false;
    },
    openTreeItemById(treeId, isSelected = true) {
      setTimeout(() => {
        this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, node => {
          if (node.model && node.model.id === treeId) {
            node.model.opened = true;
            const parentId = node.model.upperSysResourceId || node.model.parentId;
            if (parentId) {
              this.openTreeItemById(parentId, false);
            }
            node.model.selected = isSelected;
            if (isSelected) {
              this.treeItemClick(node);
            }
          }
        });
      });
    },
    initSelected() {
      this.selectedMenu = {};
      this.selectedMenuItem = {};
      this.pageList = [];
      this.apiList = [];
      this.showMenuIconLayer = false;
      // clear validation
      SDLUtil.clearAllIsInvalidCss();
    },
    deleteMenuBtn() {
      if (this.selectedMenu.menuId) {
        SDLUtil.confirm({
          msg: 'sdl.common.message.doDelete',
          title: 'sdl.common.label.delete',
          okLabel: 'sdl.common.label.delete',
          cancelLabel: 'sdl.common.label.cancel',
          onOkEvt: () => {
            if (_.startsWith(this.selectedMenu.menuId, 'NEW_')) {
              this.getTreeMenuService().then(() => {
                if (this.selectedMenu.parentId) {
                  this.openTreeItemById(this.selectedMenu.parentId, false);
                }
                this.initSelected();
              });
            } else {
              axios
                .delete(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}`)
                .then(() => {
                  // If the menu name is changed, GNB and LNB labeling is processed.
                  this.clearCache();
                  this.getMenus(true);
                  this.getMyMenus();
                  this.getTreeMenuService().then(() => {
                    if (this.selectedMenu.parentId) {
                      // console.info('this.selectedMenu.parentId', this.selectedMenu.parentId);
                      this.openTreeItemById(this.selectedMenu.parentId, false);
                    }
                    this.initSelected();
                    // SDLUtil.alert('sdl.common.message.deleted');
                  });
                })
                .catch(err => {
                  console.error(err);
                  SDLUtil.errorAlert(err);
                });
            }
          },
          onCancelEvt: () => console.log('cancel'),
        });
      } else {
        // this.noSelectMenuAlert();
      }
    },
    // page list
    savePage() {
      // validation
      if (SDLUtil.onSubmitValidation('page')) {
        return;
      }
      if (this.pageList.length > 0 && !this.pageList.find(page => page.defaulted && page.used)) {
        SDLUtil.alert('sdl.menu.message.valid.default');
        return;
      }
      if (_.find(this.pageList, ['duplicate', true])) {
        SDLUtil.alert('sdl.menu.message.valid.duplicate');
        return;
      }

      // const editedItems = this.pageList.filter(page => page.isEdited);
      // if (editedItems.length > 0 || this.pageList.length === 0) {
      // validation
      const flag = this.pageList.find(page => page.pageName === undefined || page.pagePath === undefined || page.componentName === undefined || page.pageName.trim() === '' || page.pagePath.trim() === '' || page.componentName.trim() === '');
      if (flag) {
        SDLUtil.alert('sdl.commonCode.message.valid.mandatory');
        return;
      }

      SDLUtil.confirm({
        msg: 'sdl.common.message.doSave',
        title: 'sdl.common.label.save',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => {
          // update 목록
          // const updateItems = editedItems.filter(page => page.pageId);
          // new 목록
          // const newItems = editedItems.filter(page => page.pageId === undefined);

          // console.info('save page params', JSON.stringify(this.pageList));
          SDLUtil.showLoadingBar(true);
          axios
            .all([this.insertPageService(this.pageList)])
            // .all([this.updatePageService(updateItems), this.insertPageService(newItems)])
            .then(
              axios.spread(() => {
                // SDLUtil.alert('sdl.common.message.saved');
                // Import page list again
                axios.get(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}/pages`).then(({ data }) => {
                  this.pageList = data.map(page => ({
                    ...page,
                    isEdited: false,
                  }));
                });
                this.clearCache();
                SDLUtil.showLoadingBar(false);
              }),
            )
            .catch(err => {
              SDLUtil.showLoadingBar(false);
              SDLUtil.errorAlert(err);
              console.error(err);
            });
        },
      });
      // }
    },
    updatePageService(updateItems) {
      if (updateItems.length === 0) return Promise.resolve();
      return axios.put(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}/pages`, updateItems);
    },
    insertPageService(newItems) {
      // if (newItems.length === 0) return Promise.resolve();
      return axios.post(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}/pages`, newItems);
    },
    addPage(item) {
      if (_.startsWith(this.selectedMenu.menuId, 'NEW_')) {
        SDLUtil.alert('sdl.menu.message.valid.noneSave');
        return;
      }
      this.pageList = [
        ...this.pageList,
        {
          sysId: 'SYSTEM',
          authorizationType: 'READ',
          defaulted: this.pageList.length === 0,
          pageName: '',
          pagePath: '',
          used: true,
          isEdited: true,
          duplicate: false,
          ...item,
        },
      ];
      // console.info('this.pageList', this.pageList);
    },
    deletePage(page, index) {
      this.pageList.splice(index, 1);
      SDLUtil.clearAllIsInvalidCss();

      // TODO 삭제시 default check
      // if (this.pageList.length > 0 && !_.find(this.pageList, ['defaulted', true])) {
      //   SDLUtil.alert('Please select the default page.');
      //   return;
      // }
      // SDLUtil.confirm({
      //   msg: 'sdl.common.message.doDelete',
      //   title: 'sdl.common.label.delete',
      //   okLabel: 'sdl.common.label.confirm',
      //   cancelLabel: 'sdl.common.label.cancel',
      //   onOkEvt: () => {
      //     // 삭제로직
      //     if (page.pageId) {
      //       SDLUtil.showLoadingBar(true);
      //       axios
      //         .delete(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}/pages/${page.pageId}`)
      //         .then(() => {
      //           this.pageList.splice(index, 1);
      //           // SDLUtil.alert('sdl.common.message.deleted');
      //           this.clearCache();
      //           this.checkDuplication('page');
      //           SDLUtil.showLoadingBar(false);
      //         })
      //         .catch(err => {
      //           console.error(err);
      //         });
      //     } else {
      //       // remove
      //       this.pageList.splice(index, 1);
      //       this.checkDuplication('page');
      //     }
      //   },
      // });
    },
    changeDefault(page) {
      // Modify other default items and process defaulted false
      const otherDefaultItem = this.pageList.find(p => p !== page && p.defaulted === true);
      if (otherDefaultItem) {
        otherDefaultItem.isEdited = true;
        otherDefaultItem.defaulted = false;
      }
    },
    // api list
    saveApi() {
      // const editedItems = this.apiList.filter(api => api.isEdited);
      // validation
      if (SDLUtil.onSubmitValidation('api')) return;
      const flag = this.apiList.find(api => api.apiName.trim() === '' || api.apiUrl.trim() === '');
      if (flag) {
        SDLUtil.alert('sdl.commonCode.message.valid.mandatory');
        return;
      }

      if (_.find(this.apiList, ['duplicate', true])) {
        SDLUtil.alert('sdl.menu.message.valid.duplicate');
        return;
      }

      SDLUtil.confirm({
        msg: 'sdl.common.message.doSave',
        title: 'sdl.common.label.save',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => {
          // update 목록
          // const updateItems = editedItems.filter(api => api.apiId);
          // new 목록
          // const newItems = editedItems.filter(api => api.apiId === undefined);

          SDLUtil.showLoadingBar(true);
          axios
            .all([this.insertApiService(this.apiList)])
            // .all([this.updateApiService(updateItems), this.insertApiService(newItems)])
            .then(
              axios.spread(() => {
                // SDLUtil.alert('sdl.common.message.saved');
                // api 목록 다시 가져오기
                axios.get(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}/apis`).then(({ data }) => {
                  this.apiList = data.map(api => ({
                    ...api,
                    isEdited: false,
                  }));
                });
                this.clearCache();
                SDLUtil.showLoadingBar(false);
              }),
            )
            .catch(err => {
              SDLUtil.showLoadingBar(false);
              console.error(err);
              SDLUtil.errorAlert(err);
            });
        },
      });
    },
    updateApiService(updateItems) {
      if (updateItems.length === 0) return Promise.resolve();
      return axios.put(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}/apis`, updateItems);
    },
    insertApiService(newItems) {
      // if (newItems.length === 0) return Promise.resolve();
      return axios.post(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}/apis`, newItems);
    },
    addApi(item) {
      if (_.startsWith(this.selectedMenu.menuId, 'NEW_')) {
        SDLUtil.alert('sdl.menu.message.valid.noneSave');
        return;
      }
      this.apiList = [
        ...this.apiList,
        {
          sysId: 'SYSTEM',
          authorizationType: 'READ',
          httpMethod: 'GET',
          apiName: '',
          apiUrl: '',
          serverId: this.apiServerList.length > 0 ? this.apiServerList[0].codeId : '',
          used: true,
          isEdited: true,
          ...item,
        },
      ];
    },
    deleteApi(api, index) {
      this.apiList.splice(index, 1);
      SDLUtil.clearAllIsInvalidCss();
      // SDLUtil.confirm({
      //   msg: 'sdl.common.message.doDelete',
      //   title: 'sdl.common.label.delete',
      //   okLabel: 'sdl.common.label.confirm',
      //   cancelLabel: 'sdl.common.label.cancel',
      //   onOkEvt: () => {
      //     // 삭제로직
      //     if (api.apiId) {
      //       SDLUtil.showLoadingBar(true);
      //       axios
      //         .delete(`${SDLUtil.API_URL}/auth/menus/${this.selectedMenu.menuId}/apis/${api.apiId}`)
      //         .then(() => {
      //           // 삭제완료
      //           this.apiList.splice(index, 1);
      //           // SDLUtil.alert('sdl.common.message.deleted');
      //           this.clearCache();
      //           SDLUtil.showLoadingBar(false);
      //         })
      //         .catch(err => {
      //           console.error(err);
      //           SDLUtil.showLoadingBar(false);
      //         });
      //     } else {
      //       // remove
      //       this.apiList.splice(index, 1);
      //     }
      //   },
      // });
    },
    openBoardPopup(type = 'user') {
      if (_.startsWith(this.selectedMenu.menuId, 'NEW_')) {
        SDLUtil.alert('sdl.menu.message.valid.noneSave');
        return;
      }
      SDLUtil.show(
        SelectBoardPopup,
        {
          popupType: type,
          confirmFunc: (boardId, boardType) => {
            const { page, api } = SDLUtil.getBoardPageApiList(boardId, boardType, type);
            if (type === 'admin') {
              page
                // .map(item => {
                //   item.pagePath = `/admin${item.pagePath}`;
                //   return item;
                // })
                .forEach(item => this.addPage(item));
            } else if (type === 'user') {
              page.forEach(item => this.addPage(item));
            }

            api.forEach(item => this.addApi(item));

            this.checkDuplication('page');
            this.checkDuplication('api');
          },
        },
        {
          width: 500,
          height: 'auto',
        },
      );
    },
    checkDuplication(type) {
      if (type === 'page') {
        // Unique key generation
        const pages = this.pageList.filter(page => page.pagePath.trim() !== '').map(page => page.pagePath);
        this.pageList
          .filter(page => page.pagePath.trim() !== '')
          .forEach((page, idx) => {
            page.duplicate = _.findIndex(pages, item => item === page.pagePath) !== _.findLastIndex(pages, item => item === page.pagePath, idx);
          });
      } else if (type === 'api') {
        // Unique key generation
        const apis = this.apiList.filter(api => api.apiUrl.trim() !== '').map(api => api.httpMethod + api.apiUrl.trim());
        this.apiList
          .filter(api => api.apiUrl.trim() !== '')
          .forEach((api, idx) => {
            api.duplicate = _.findIndex(apis, item => item === api.httpMethod + api.apiUrl.trim()) !== _.findLastIndex(apis, item => item === api.httpMethod + api.apiUrl.trim(), idx);
          });
      }
    },
  },
  watch: {
    locale() {
      const changeTreeLocale = treeItem => {
        treeItem.localeLabel = this.getLabel(treeItem);
        treeItem.children.forEach(child => changeTreeLocale(child));
      };
      changeTreeLocale(this.treeData[0]);
    },
    // selectedMenu() {
    //   console.info('watch', this.selectedMenu, this.selectedMenuItem);
    // },
  },
};
</script>

<style>
/* Tree Item Selection Class */
.tree-selected {
  background-color: #e9ecef !important;
}
</style>
