<template>
  <div class="popup-overlay">
    <div class="popup-content">
      <div class="card">
        <div class="card-body">
          <h2 class="card-title">공통코드 목록</h2>
          <div class="sch-form-wrap">
            <div class="input-group">
              <select name="searchType" id="searchType" class="form-select" v-model="searchParams.searchType">
                <option value="">전체</option>
                <option v-for="(item, index) of searchOptions" :key="index" :value="item.key"> {{ item.label }} </option>
              </select>
              <div class="sch-input">
                <input type="text" class="form-control" v-model="searchParams.searchText" @keyup.enter="handleSearch" placeholder="검색어를 입력하세요">
                <button class="ico-sch" @click="handleSearch" type="button">
                  <SearchOutlined />
                </button>
              </div>
            </div>
          </div>
          <div class="tbl-wrap">
            <table class="tbl data">
              <colgroup>
                <col style="width: 23%;">
                <col style="width: 23%;">
                <col style="width: 23%;">
                <col style="width: 23%;">
                <col style="width: 8%;">
              </colgroup>
              <thead>
                <tr>
                  <th>상위코드</th>
                  <th>상위코드명</th>
                  <th>코드</th>
                  <th>코드명</th>
                  <th>선택</th>
                </tr>
              </thead>
              <tbody>
                <template v-if="codeList.length > 0">
                  <tr v-for="(item, index) in codeList" :key="index">
                    <td>{{ item.upperCode || '-' }}</td>
                    <td>{{ item.upperCodeNm || '-' }}</td>
                    <td>{{ item.code }}</td>
                    <td>{{ item.codeNm }}</td>
                    <td>
                      <button type="button" class="btn sm secondary" @click="handleCodeSelect(item)"> 선택 </button>
                    </td>
                  </tr>
                </template>
                <tr v-else>
                  <td colspan="5" class="text-center">검색 결과가 없습니다.</td>
                </tr>
              </tbody>
            </table>
          </div>
          <Pagination :search="searchParams" @onChange="handlePageChange" />
        </div>
      </div>
      <button @click="handleModalClose" class="close-btn" type="button">
        <CloseCircleFilled />
      </button>
    </div>
  </div>
</template>
<script>
import { SearchOutlined, CloseCircleFilled } from '@ant-design/icons-vue';
import Pagination from "../Pagination.vue";
// API
import { findCodesProc } from "../../../resources/api/code";

export default {
  name: 'CodeSelectorModal',

  components: {
    SearchOutlined,
    CloseCircleFilled,
    Pagination,
  },

  props: {
    currentCodeId: {
      type: String,
      default: null
    },
  },

  emits: ['select', 'close'],

  data() {
    return {
      codeList: [],

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

      searchParams: {
        searchType: '',
        searchText: '',
        recordSize: 5,
        pageSize: 5,
        currentPage: 1,
        currentCodeId: this.currentCodeId, // 백엔드에서 제외할 코드ID
      }
    }
  },

  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);
      }
    },

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

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

    // 코드 선택
    handleCodeSelect(selectedCode) {
      this.$emit('select', selectedCode);
    },

    // 모달 닫기
    handleModalClose() {
      this.$emit('close');
    },

    // 에러 처리
    handleError(error) {
      const message = error.response?.data?.message || "에러가 발생했습니다.";
      alert(message);
      console.error(error.message);
    },
  },
}
</script>
<style scoped>
.popup-content {
  width: 50%;
}
</style>