<template>
  <div class="card">
    <div class="card-body">
      <h2 class="card-title">공통코드 {{ isEditMode ? '수정' : '등록' }}</h2>
      <p class="require">* 필수입력</p>
      <div class="tbl-wrap needs-validation detail">
        <table class="tbl data radius-table">
          <colgroup>
            <col style="width: 25%;">
            <col style="width: 75%;">
          </colgroup>
          <tbody>
            <tr>
              <th>상위코드</th>
              <td>
                <input type="text" id="parentCode" v-model="formData.upperCode" readonly />
                <button type="button" class="btn sm primary" @click="handleModalOpen"> 검색 </button>
              </td>
            </tr>
            <tr>
              <th>상위코드 명</th>
              <td>
                <input type="text" id="parentCodeName" v-model="formData.upperCodeNm" readonly />
              </td>
            </tr>
            <tr>
              <th>코드 *</th>
              <td>
                <input type="text" id="code" v-model="formData.code" :disabled="isEditMode" />
              </td>
            </tr>
            <tr>
              <th>코드명 *</th>
              <td>
                <input type="text" id="codeName" v-model="formData.codeNm" />
              </td>
            </tr>
            <tr>
              <th>코드 설정값</th>
              <td>
                <input type="text" id="codeValue" v-model="formData.codeValue" />
              </td>
            </tr>
            <tr>
              <th>설명</th>
              <td>
                <textarea name="description" id="description" v-model="formData.dc"></textarea>
              </td>
            </tr>
            <tr>
              <th>사용여부 *</th>
              <td>
                <div class="chk-area">
                  <div class="form-check">
                    <input type="radio" name="isActive" id="activeTrue" value="Y" v-model="formData.useAt" disabled>
                    <label for="activeTrue">사용</label>
                  </div>
                  <div class="form-check">
                    <input type="radio" name="isActive" id="activeFalse" value="N" v-model="formData.useAt" disabled>
                    <label for="activeFalse">미사용</label>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="buttons">
        <template v-if="!isEditMode">
          <button type="button" class="btn sm primary" @click="handleCreate">등록</button>
          <button type="button" class="btn sm tertiary" @click="handleNavigation('list')">취소</button>
        </template>
        <template v-else>
          <button type="button" class="btn sm primary" @click="handleUpdate">수정</button>
          <button type="button" class="btn sm tertiary" @click="handleNavigation('view', codeId)">취소</button>
        </template>
      </div>
    </div>
  </div>
  <CodeSelectorModal v-if="isModalVisible" :current-code-id="codeId" @select="handleCodeSelect" @close="handleModalClose" />
</template>
<script>
import CodeSelectorModal from "../../../component/Popup/CodeSelectorModal.vue";
import { saveCodeProc, findCodeProc, updateCodeProc } from "../../../../resources/api/code";

export default {
  name: 'CodeFormPage',

  components: {
    CodeSelectorModal
  },

  data() {
    return {
      codeId: null,
      isModalVisible: false,

      formData: {
        code: null,
        codeNm: null,
        upperCode: null,
        upperCodeNm: null,
        dc: null,
        useAt: 'Y',
        codeValue: null,
      }
    }
  },

  computed: {
    isEditMode() {
      return !this.$isEmpty(this.codeId);
    }
  },

  created() {
    this.codeId = this.$route.query.id;
  },

  mounted() {
    if (this.isEditMode) {
      this.fetchCodeDetail();
    }
  },

  methods: {
    // 상세 정보 조회
    async fetchCodeDetail() {
      try {
        const response = await findCodeProc(this.codeId);
        const result = response.data.data;

        this.formData = result.code;
      } catch (error) {
        this.handleError(error);
      }
    },

    // 신규 등록
    async handleCreate() {
      try {
        if (!this.validateForm()) return;

        const requestData = {
          code: this.formData.code,
          codeNm: this.formData.codeNm,
          upperCode: this.formData.upperCode,
          dc: this.formData.dc,
          codeValue: this.formData.codeValue,
        };

        await saveCodeProc(requestData);
        alert('등록되었습니다.');
        this.handleNavigation('list');
      } catch (error) {
        this.handleError(error);
      }
    },

    // 수정
    async handleUpdate() {
      try {
        if (!this.validateForm()) return;

        const requestData = {
          codeNm: this.formData.codeNm,
          upperCode: this.formData.upperCode,
          dc: this.formData.dc,
          useAt: this.formData.useAt,
          codeValue: this.formData.codeValue,
        };

        await updateCodeProc(this.codeId, requestData);
        alert('수정되었습니다.');
        this.handleNavigation('view', this.codeId);
      } catch (error) {
        this.handleError(error);
      }
    },

    // 폼 유효성 검사
    validateForm() {
      if (!this.formData.code?.trim()) {
        alert('코드를 입력해주세요.');
        return false;
      }
      if (!this.formData.codeNm?.trim()) {
        alert('코드명을 입력해주세요.');
        return false;
      }
      return true;
    },

    // 모달 열기
    handleModalOpen() {
      this.isModalVisible = true;
    },

    // 모달 닫기
    handleModalClose() {
      this.isModalVisible = false;
    },

    // 상위 코드 선택
    handleCodeSelect(selectedCode) {
      this.formData.upperCode = selectedCode.code;
      this.formData.upperCodeNm = selectedCode.codeNm;
      this.handleModalClose();
    },

    // 페이지 이동
    handleNavigation(type, id) {
      const routeMap = {
        'list': { name: 'CodeManagementListPage' },
        'view': { name: 'CodeManagementViewPage', query: { id } },
        'edit': { name: 'CodeManagementInsertPage', query: this.$isEmpty(id) ? {} : { id } },
      };

      const route = routeMap[type];
      if (route) {
        this.$router.push(route);
      } else {
        this.handleNavigationError(type);
      }
    },

    // 네비게이션 에러 처리
    handleNavigationError(type) {
      console.warn(`유효하지 않은 라우트 타입: ${type}`);
      alert("올바르지 않은 경로를 요청하여 목록으로 이동합니다.");
      this.$router.push({ name: 'CodeManagementListPage' });
    },

    // 에러 처리
    handleError(error) {
      const message = error.response?.data?.message || "에러가 발생했습니다.";
      alert(message);
      console.error(error.message);
    }
  }
}
</script>