<template>
    <div class="card">
      <div class="card-body">
        <h2 class="card-title">공통코드 관리</h2>
        <div>
          <div class="search-wrap mb20">
              <select name="searchType" id="searchType" class="form-select sm" v-model="searchParams.searchType">
                <option value="">전체</option>
                <option v-for="(item, index) of searchOptions" :key="index" :value="item.key"> {{ item.label }} </option>
              </select>
                <input type="text" class="form-control sm" v-model="searchParams.searchText" @keyup.enter="handleSearch" placeholder="검색어를 입력하세요">
                <button class="btn-ico md ico-sch" @click="handleSearch"></button>
            </div>
          <div class="tbl-wrap">
            <table id="codeTable" class="tbl data">
              <colgroup>
                <col style="width: 18%;">
                <col style="width: 18%;">
                <col style="width: 18%;">
                <col style="width: 18%;">
                <col style="width: 18%;">
                <col style="width: 10%;">
              </colgroup>
              <thead>
                <tr>
                  <th style="border-radius: 1rem 0 0 0;">상위코드</th>
                  <th>상위코드명</th>
                  <th>코드</th>
                  <th>코드명</th>
                  <th>등록일</th>
                  <th style="border-radius: 0 1rem 0 0;">사용여부</th>
                </tr>
              </thead>
              <tbody>
                <template v-if="codeList.length > 0">
                  <tr v-for="(code, index) in codeList" :key="index" :class="{ expired: code.useAt === 'N' }" @click="handleNavigation('view', code.code)">
                    <td>{{ code.upperCode }}</td>
                    <td>{{ code.upperCodeNm }}</td>
                    <td>{{ code.code }}</td>
                    <td>{{ code.codeNm }}</td>
                    <td>{{ formatDate(code.rgsde) }}</td>
                    <td>{{ getActiveStatusText(code.useAt) }}</td>
                  </tr>
                </template>
                <tr v-else>
                  <td colspan="6" class="text-center" style="border-radius: 0  0 1rem 1rem;">등록된 코드가 없습니다.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <div class="d-flex justify-between align-center">
          <div></div>
          <Pagination :search="searchParams" @onChange="handlePageChange" />
          <button class="btn sm primary" @click="handleNavigation('edit')">등록</button>
    </div>
</template>
<script>
import Pagination from "../../../component/Pagination.vue";
// API
import { findCodesProc } from "../../../../resources/api/code";

export default {
  name: 'CodeListPage',

  components: {
    Pagination,
  },

  data() {
    return {
      codeList: [], // 코드 목록

      searchOptions: [
        { key: "UPPER_CODE", label: "상위코드" },
        { key: "UPPERCODE_NAME", label: "상위코드 이름" },
        { key: "CODE", label: "코드" },
        { key: "CODE_NAME", label: "코드 이름" },
      ],

      searchParams: {
        searchType: '',
        searchText: '',
        currentPage: 1,
      }
    }
  },

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

  methods: {
    // 코드 목록 조회
    async fetchCodeList() {
      try {
        const response = await findCodesProc(this.searchParams);
        const result = response.data.data;

        this.codeList = result.codes;
        this.searchParams = result.search;
      } catch (error) {
        this.handleError(error);
      }
    },

    // 날짜 포맷팅
    formatDate(dateString) {
      return dateString ? dateString.split(' ')[0] : '-';
    },

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

    // 검색 실행
    handleSearch() {
      this.searchParams.currentPage = 1;
      this.fetchCodeList();
    },

    // 페이지 변경
    handlePageChange(currentPage) {
      this.searchParams.currentPage = Number(currentPage);
      this.$nextTick(() => {
        this.fetchCodeList();
      });
    },

    // 페이지 이동
    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>
<style scoped>
tr {
  cursor: pointer;
}
</style>