<template>
  <div class="content admin-style">
    <div class="admin-page-title  mb30">
      <p>공통코드관리</p>
    </div>
    <div class="full-page">
      <div class="flex content">
        <div class="gd-3 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.mdfcnAuthrtYn == '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-9 pr0 content  overflow-y">
          <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=" mb10">상위코드</label>
                    <input type="text" class="full-input" disabled v-model="viewCode.upCdId" />
                  </div>
                </td>
                <td>
                  <div class="gd-12 pr0">
                    <label for="" class=" mb10">상위코드명</label>
                    <input type="text" class="full-input" disabled v-model="viewCode.upCdIdNm" />
                  </div>
                </td>
              </tr>
              <tr>
                <td>
                  <div class="gd-12 pl0">
                    <label for="" class="form-title  mb10">코드</label>
                    <input type="text" class="full-input" :disabled="isFormDisabled" v-model="viewCode.cdId" />
                  </div>
                </td>
                <td>
                  <div class="gd-12 pr0">
                    <label for="" class="form-title  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=" 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  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">
                    <label for="" class=" mb10">코드설명</label>
                    <textarea :disabled="isFormDisabled" v-model="viewCode.cdCn" style="height: 2rem;"></textarea>
                  </div>
                </td>
              </tr>
            </table>
            <div class="flex justify-end pt15">
              <div class="gd-1 pr0">
                <button :class="{
                  'large-btn': true,
                  'gray-btn': isFormDisabled,
                  'red-border-btn': !isFormDisabled,
                }" :disabled="isFormDisabled" @click="fnDel" v-if="pageAuth.delAuthrtYn == 'Y'">
                  삭제
                </button>
              </div>
              <div class="gd-1 pr0" v-if="originCode == null">
                <button class="large-btn blue-btn" :disabled="isFormDisabled" @click="fnSave"
                  v-if="pageAuth.wrAuthrtYn == 'Y'">
                  등록
                </button>
              </div>
              <div class="gd-1 pr0" v-else>
                <button class="large-btn blue-btn" :disabled="isFormDisabled" @click="fnSave"
                  v-if="pageAuth.mdfcnAuthrtYn == '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 { mdiConsoleNetwork, 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, // 변경전 코드
    };
  },
  created() {
    this.findAll();
  },
  methods: {
    // 목록 조회
    async findAll() {
      try {
        this.$setLoading(true);
        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);
      } finally {
        this.$setLoading(false);
      }
    },
    fnViewDetail(cd) {
      this.selectedCd = cd;
      this.findByCd();
    },
    // 상세 조회
    async findByCd() {
      if (this.selectedCd == null) return;
      try {
        //  this.$setLoading(true);
        const params = { cdId: this.selectedCd };
        const res = await findByCd(params);
        if (res.status == 200) {
          this.viewCode = res.data.data.code;
          this.originCode = this.viewCode.cdId;
        }
      } catch (error) {
        alert(error.response.data.message);
      } finally {
        //   this.$setLoading(false);
      }
    },
    // 저장
    async fnSave() {
      // 유효성 검사
      if (!this.validation()) return;
      this.viewCode.originCd = this.originCode;
      // 신규 등록 및 수정 설정
      const action = this.viewCode.originCd ? update : save;
      try {
        this.$setLoading(true);
        const res = await action(this.viewCode);
        if (res.status == 200) {
          alert(res.data.message);
          this.findAll();
        }
      } catch (error) {
        alert(error.response.data.message);
      } finally {
        this.$setLoading(false);
      }
    },
    // 삭제
    async fnDel() {
      if (Object.keys(this.viewCode).length === 0) {
        alert("삭제 대상을 지정해주세요.");
        return false;
      }
      if (!confirm(this.$getCmmnMessage("cnf016"))) {
        return false;
      }

      try {
        this.$setLoading(true);
        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);
      } finally {
        this.$setLoading(false);
      }

    },
    // 최상위 신규 객체 생성
    topAdd() {
      this.viewCode = JSON.parse(JSON.stringify(this.newCode));
      this.originCode = this.viewCode.cdId;
    },
    // 하위 신규 객체 생성
    subAdd() {
      if (Object.keys(this.viewCode).length === 0) {
        alert("상위 코드를 지정해주세요.");
        return;
      }
      const upCdId = this.viewCode.cdId;
      const upCdIdNm = this.viewCode.cdNm;

      this.viewCode = JSON.parse(JSON.stringify(this.newCode));
      this.viewCode.upCdId = upCdId;
      this.viewCode.upCdIdNm = upCdIdNm;
      this.originCode = null;
    },
    validation() {
      if (
        this.viewCode.cdId == null ||
        this.viewCode.cdId == "" ||
        this.viewCode.cdId == undefined
      ) {
        alert("코드를 입력해주세요.");
        return false;
      }
      if (
        this.viewCode.cdNm == null ||
        this.viewCode.cdNm == "" ||
        this.viewCode.cdNm == undefined
      ) {
        alert("코드명을 입력해주세요.");
        return false;
      }

      //코드값이 존재하는 경우
      if (this.viewCode.cdVl){
        //코드값의 길이 검사
        if(this.viewCode.cdVl.length >= 50){
          alert("코드값은 50자까지 입력할 수 있습니다.")
          return false;
        }
      }

      return true;
    },

    // 드래그앤드롭
    // axios: 목록 수정
    async fnListUpdate() {
      try {
        this.$setLoading(true);
        const res = await updateListProc(this.codeList);
        alert(res.data.message);
        if (res.status == 200) {
          this.findAll();
        }
      } catch (error) {
        alert(error.res.data.message);
      } finally {
        this.$setLoading(false);
      }
    },
  },
  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>