<template>
  <div class="content-zone full-page">
    <div class="content">
      <div class="setting-box h_100">
          <div class="node-zone">
              <div class="tree">
                  <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 class="btn-zone">
                <template v-if="pageAuth.mdfcnAuthrt == 'Y'">
                      <button class="btn top sm secondary" @click="topAdd">
                        TOP+
                      </button>
                      <button class="btn sub sm secondary" @click="subAdd">
                        SUB+
                      </button>
                    <button class="btn save sm" @click="fnListUpdate">
                      저장
                    </button>
                </template>
              </div>
          </div>
          <div class="setting-zone">
            <div class="form-box sch-full">
              <div class="form-box-title">
                <p>공통코드정보</p>
              </div>
              <div class="form-content" style="grid-template-rows: auto auto auto 1fr;">
                <div class="layout">
                  <label for="" class="form-title">상위코드</label>
                  <input type="text" class="form-control sm" disabled v-model="viewCode.upCd" />
                </div>
                <div class="layout">
                  <label for="" class="form-title">상위코드명</label>
                  <input type="text" class="form-control sm" disabled v-model="viewCode.upCdNm" />
                </div>
                <div class="layout">
                  <label for="" class="form-title">코드</label>
                  <input type="text" class="form-control sm" :disabled="isFormDisabled || !submitStts"
                    v-model="viewCode.cd" placeholder="코드를 입력해주세요"/>
                </div>
                <div class="layout">
                  <label for="" class="form-title">코드명</label>
                  <input type="text" class="form-control sm" :disabled="isFormDisabled" v-model="viewCode.cdNm" placeholder="코드명을 입력해주세요"/>
                </div>
                <div class="layout">
                  <label for="" class="form-title">코드값</label>
                  <input type="text" class="form-control sm" :disabled="isFormDisabled" v-model="viewCode.cdVl" placeholder="코드값을 입력해주세요"/>
                </div>
                <div class="border-bottom layout">
                  <label for="" class="form-title">사용여부</label>
                  <div class="check-area">
                    <div class="form-check">
                      <input type="radio" name="code" id="y"  value="Y" :disabled="isFormDisabled"
                        v-model="viewCode.useYn" />
                      <label for="y">사용</label>
                    </div>
                    <div class="form-check">
                      <input type="radio" name="code" id="n"  value="N" :disabled="isFormDisabled"
                        v-model="viewCode.useYn" />
                      <label for="n">미사용</label>
                    </div>
                  </div>
                </div>
                <div class="grid-column layout">
                  <label for="textarea" class="form-title" style="vertical-align: top;">코드설명</label>
                  <textarea class="form-control sm" id="textarea" :disabled="isFormDisabled" v-model="viewCode.cdExpln" style="height: 100%;" placeholder="코드설명을 입력해주세요"></textarea>
                </div>
              </div>
            </div>
            <div class="btn-wrap">
                <button class="btn sm main" :disabled="isFormDisabled" @click="fnSave"
                  v-if="pageAuth.regAuthrt == 'Y'">
                  <span v-if="submitStts">등록</span>
                  <span v-else>수정</span>
                </button>
                <button :class="{
                  'btn sm': true,
                  'red': !isFormDisabled,
                }" :disabled="isFormDisabled" @click="fnDel" v-if="pageAuth.delAuthrt == 'Y'">
                  삭제
                </button>
            </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";

export default {
  components: {
    draggable: draggable,
    Hierachy: Hierachy,
  },
  data() {
    return {
      // 페이지 권한 객체
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,

      codeList: [], // 코드 목록
      iconPath: 'ico_folder_3d',
      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() {
      if (this.selectedCd != null) {
        if (!confirm("작성 중인 공통코드정보는 저장되지 않습니다.\n계속 하시겠습니까?")) {
          return;
        }
      }
      this.selectedCd = null; // 선택된 코드 초기화
      this.viewCode = JSON.parse(JSON.stringify(this.newCode));
      this.originCode = this.viewCode.cd;
      this.submitStts = true;
    },
    // 하위 신규 객체 생성
    subAdd() {
      // if (Object.keys(this.viewCode).length === 0) {
      if (this.selectedCd == null) {
        alert("상위 코드를 지정해주세요.");
        return;
      } else {
        if (!confirm("작성 중인 공통코드정보는 저장되지 않습니다.\n계속 하시겠습니까?")) {
          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 {
        if (!confirm("공통코드 목록을 저장하시겠습니까?\n 작성 중인 공통코드정보는 저장되지 않습니다.")) {
          return;
        }
        const res = await updateListProc(this.codeList);
        alert(res.data.message);
        if (res.status == 200) {
          this.findAll();
          this.findByCd();
        }
      } 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>