<template>
  <div class="card">
    <div class="card-body">
      <h2 class="card-title">공통코드 상세</h2>
      <p class="require">* 필수입력</p>
      <div class="tbl-wrap">
        <table class="tbl data radius-table">
          <colgroup>
            <col style="width: 25%;">
            <col style="width: 25%;">
            <col style="width: 25%;">
            <col style="width: 25%;">
          </colgroup>
          <tbody>
            <tr>
              <th>상위코드</th>
              <td>{{ codeDetail.upperCode }}</td>
              <th>상위코드 명</th>
              <td>{{ codeDetail.upperCodeNm }}</td>
            </tr>
            <tr>
              <th>코드</th>
              <td>{{ codeDetail.code }}</td>
              <th>코드명</th>
              <td>{{ codeDetail.codeNm }}</td>
            </tr>
            <tr>
              <th>코드 설정값</th>
              <td colspan="3">{{ codeDetail.codeValue }}</td>
            </tr>
            <tr>
              <th>설명</th>
              <td colspan="3">
                <p>{{ codeDetail.dc }}</p>
              </td>
            </tr>
            <tr>
              <th>사용여부</th>
              <td colspan="3">{{ getActiveStatusText(codeDetail.useAt) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="buttons">
        <button type="button" class="btn sm secondary" v-if="codeDetail.useAt === 'Y'" @click="handleStatusUpdate('N')"> 삭제 </button>
        <button type="button" class="btn sm secondary" v-if="codeDetail.useAt === 'N'" @click="handleStatusUpdate('Y')"> 복구 </button>
        <button type="button" class="btn sm primary" @click="handleNavigation('edit', pageId)"> 수정 </button>
        <button type="button" class="btn sm tertiary" @click="handleNavigation('list')"> 목록 </button>
      </div>
    </div>
  </div>
</template>
<script>
// API
import { findCodeProc, updateCodeProc } from "../../../../resources/api/code";

export default {
  name: 'CodeDetailPage',

  data() {
    return {
      pageId: null,

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

  created() {
    this.pageId = this.$route.query.id;
    if (this.$isEmpty(this.pageId)) {
      alert("게시물이 존재하지 않습니다.");
      this.handleNavigation('list');
    }
  },

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

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

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

    // 사용상태 업데이트 (삭제/복구)
    async handleStatusUpdate(status) {
      try {
        if (status === "N") {
          const isConfirmed = confirm("삭제하시겠습니까?");
          if (!isConfirmed) return;
        }

        const updateData = {
          codeNm: this.codeDetail.codeNm,
          useAt: status,
        };

        const response = await updateCodeProc(this.pageId, updateData);
        const result = response.data.data;

        this.codeDetail = result.code;
        const message = status === "Y" ? "복구에 성공했습니다." : "삭제에 성공했습니다.";
        alert(message);

        this.fetchCodeDetail();
      } catch (error) {
        this.handleError(error);
      }
    },

    // 사용여부 텍스트 반환
    getActiveStatusText(useAt) {
      return useAt === 'Y' ? "사용중" : "미사용";
    },

    // 페이지 이동
    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>