<template>
  <div class="content admin-style">
    <div class="admin-page-title point-font2 mb30">
      <p>공통코드관리</p>
    </div>
    <div class="full-page">
      <div class="flex content">
        <div class="gd-2 pl0 content">
          <div class="tree-zone content pd15">
            <div class="tree">
              <div class="content overflow-y">
                <draggable tag="ul" class="tree-node" :list="codeList" :group="{ name: 'menu' }" item-key="id"
                  handle=".handle" ghost-class="ghost">
                  <template #item="{ element }">
                    <Hierachy :tasks="element" :icon="iconPath" :selectedNode="selectedCd"
                      @changeSelected="fnViewDetail" />
                  </template>
                </draggable>
              </div>
            </div>
            <div class="btn-zone pt15">
              <template v-if="pageAuth.mdfcnAuthrt == 'Y'">
                <div class="flex">
                  <div class="gd-6 pl0">
                    <button class="large-btn blue-border-btn" @click="topAdd">
                      TOP+
                    </button>
                  </div>
                  <div class="gd-6 pr0">
                    <button class="large-btn blue-border-btn" @click="subAdd">
                      SUB+
                    </button>
                  </div>
                </div>
                <div class="pt15">
                  <button class="large-btn blue-border-btn" @click="fnListUpdate">
                    메뉴 저장
                  </button>
                </div>
              </template>
            </div>
          </div>
        </div>
        <div class="gd-10 pr0">
          <div class="content">
            <table class="form-table">
              <colgroup>
                <col width="50%" />
                <col width="50%" />
              </colgroup>
              <tr>
                <td>
                  <div class="gd-12 pl0">
                    <label for="" class="point-font2 mb10">상위코드</label>
                    <input type="text" class="full-input" disabled v-model="viewCode.upCd" />
                  </div>
                </td>
                <td>
                  <div class="gd-12 pr0">
                    <label for="" class="point-font2 mb10">상위코드명</label>
                    <input type="text" class="full-input" disabled v-model="viewCode.upCdNm" />
                  </div>
                </td>
              </tr>
              <tr>
                <td>
                  <div class="gd-12 pl0">
                    <label for="" class="form-title point-font2 mb10">
                      코드
                    </label>
                    <input type="text" class="full-input" :disabled="isFormDisabled || !submitStts"
                      v-model="viewCode.cd" />
                  </div>
                </td>
                <td>
                  <div class="gd-12 pr0">
                    <label for="" class="form-title point-font2 mb10">
                      코드명
                    </label>
                    <input type="text" class="full-input" :disabled="isFormDisabled" v-model="viewCode.cdNm" />
                  </div>
                </td>
              </tr>
              <tr>
                <td>
                  <div class="gd-12 pl0">
                    <label for="" class="point-font2 mb10">코드값</label>
                    <input type="text" class="full-input" :disabled="isFormDisabled" v-model="viewCode.cdVl" />
                  </div>
                </td>
                <td>
                  <div class="gd-12 pr0">
                    <label for="" class="form-title point-font2 mb10">사용여부</label>
                    <div class="flex align-center no-gutters">
                      <div class="gd-4">
                        <input type="radio" name="code" id="y" class="mr5" value="Y" :disabled="isFormDisabled"
                          v-model="viewCode.useYn" />
                        <label for="y">사용</label>
                      </div>
                      <div class="gd-4">
                        <input type="radio" name="code" id="n" class="mr5" value="N" :disabled="isFormDisabled"
                          v-model="viewCode.useYn" />
                        <label for="n">미사용</label>
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <td colspan="2">
                  <div class="gd-12 pl0 pr0">
                    <label for="" class="point-font2 mb10">코드설명</label>
                    <textarea name="" id="" :disabled="isFormDisabled" v-model="viewCode.cdExpln"></textarea>
                  </div>
                </td>
              </tr>
            </table>
            <div class="flex justify-end pt15">
              <div class="gd-1">
                <button class="large-btn blue-btn" :disabled="isFormDisabled" @click="fnSave"
                  v-if="pageAuth.regAuthrt == 'Y'">
                  <span v-if="submitStts">등록</span>
                  <span v-else>수정</span>
                </button>
              </div>
              <div class="gd-1">
                <button :class="{
                  'large-btn': true,
                  'gray-btn': isFormDisabled,
                  'red-border-btn': !isFormDisabled,
                }" :disabled="isFormDisabled" @click="fnDel" v-if="pageAuth.delAuthrt == 'Y'">
                  삭제
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import Hierachy from "../../../../component/hierachy/HierachyDraggable.vue";
import {
  findAll,
  findByCd,
  save,
  update,
  del,
  updateListProc,
} from "../../../../../resources/api/codeManage";
import { mdiFileCode } from "@mdi/js";
export default {
  components: {
    draggable: draggable,
    Hierachy: Hierachy,
  },
  data() {
    return {
      // 페이지 권한 객체
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,

      codeList: [], // 코드 목록
      iconPath: mdiFileCode,
      selectedCd: null, // 선택된 코드
      newCode: {}, // 신규 코드 등록
      viewCode: {}, // 사용자에게 보여질 코드
      originCode: null, // 변경전 코드

      submitStts: true,
    };
  },
  created() {
    this.findAll();
  },
  methods: {
    // 목록 조회
    async findAll() {
      try {
        const res = await findAll();
        if (res.status == 200) {
          this.codeList = res.data.data.hierachyList;
          this.newCode = res.data.data.newCode;
          this.newCode.useYn = "Y";
        }
      } catch (error) {
        alert(error.response.data.message);
      }
    },
    fnViewDetail(cd) {
      this.selectedCd = cd;
      this.findByCd();
    },
    // 상세 조회
    async findByCd() {
      if (this.selectedCd == null) return;
      try {
        const params = { cd: this.selectedCd };
        const res = await findByCd(params);
        if (res.status == 200) {
          this.viewCode = res.data.data.code;
          this.originCode = this.viewCode.cd;
          this.submitStts = false;
        }
      } catch (error) {
        alert(error.response.data.message);
      }
    },
    // 저장
    async fnSave() {
      // 유효성 검사
      if (this.validation() == false) {
        return false;
      }
      this.viewCode.originCd = this.originCode;
      // 신규 등록 및 수정 설정
      const action = this.viewCode.originCd ? update : save;
      try {
        const res = await action(this.viewCode);
        alert(res.data.message);
        if (res.status == 200) {
          this.findAll();
        }
      } catch (error) {
        alert(error.response.data.message);
      }
    },
    // 삭제
    async fnDel() {
      if (Object.keys(this.viewCode).length === 0) {
        alert("삭제 대상을 지정해주세요.");
        return false;
      }
      if (
        !confirm(
          "해당 코드를 삭제하시겠습니까?\n삭제시 하위코드도 모두 삭제됩니다."
        )
      )
        return false;
      try {
        const res = await del(this.viewCode);
        if (res.status == 200) {
          alert(res.data.message);
          this.viewCode = {};
          this.findAll();
        }
      } catch (error) {
        alert(error.response.data.message);
      }
    },
    // 최상위 신규 객체 생성
    topAdd() {
      this.viewCode = JSON.parse(JSON.stringify(this.newCode));
      this.originCode = this.viewCode.cd;
      this.submitStts = true;
    },
    // 하위 신규 객체 생성
    subAdd() {
      if (Object.keys(this.viewCode).length === 0) {
        alert("상위 코드를 지정해주세요.");
        return;
      }
      const upCd = this.viewCode.cd;
      const upCdNm = this.viewCode.cdNm;
      this.viewCode = JSON.parse(JSON.stringify(this.newCode));
      this.viewCode.upCd = upCd;
      this.viewCode.upCdNm = upCdNm;
      this.originCode = null;
      this.submitStts = true;
    },
    validation() {
      if (
        this.viewCode.cd == null ||
        this.viewCode.cd == "" ||
        this.viewCode.cd == undefined
      ) {
        alert("코드를 입력해주세요.");
        return false;
      }
      const alpha = /^[a-zA-Z_-]*$/;
      if (!alpha.test(this.viewCode.cd)) {
        alert("권한코드는 영문(대문자)과 언더바(_)만 사용하여 작성해주세요.");
        return false;
      }
      if (
        this.viewCode.cdNm == null ||
        this.viewCode.cdNm == "" ||
        this.viewCode.cdNm == undefined
      ) {
        alert("코드명을 입력해주세요.");
        return false;
      }
      return true;
    },

    // 드래그앤드롭
    // axios: 목록 수정
    async fnListUpdate() {
      try {
        const res = await updateListProc(this.codeList);
        alert(res.data.message);
        if (res.status == 200) {
          this.findAll();
        }
      } catch (error) {
        alert(error.res.data.message);
      }
    },
  },
  watch: {},
  computed: {
    isFormDisabled() {
      if (!this.viewCode) return true;
      return Object.keys(this.viewCode).length === 0;
    },
  },
  mounted() { },
};
</script>

<style scoped>
.ghost {
  height: 15px;
  color: transparent;
  border: 1px dashed var(--blue);
}

.ghost * {
  display: none;
}
</style>