<script setup>
import { defineProps, ref, onMounted, onBeforeUnmount } from 'vue'
import * as bootstrap from 'bootstrap'
import * as XSLX from 'xlsx'

const props = defineProps({
  modalId: String,
  dto: Object,
})

const modalEl = ref(null)
let bsModal = null
let dataList = ref([])
let columnList = ref([])

onMounted(() => {
  if (modalEl.value) {
    // 인스턴스가 있으면 재사용, 없으면 생성
    bsModal = bootstrap.Modal.getOrCreateInstance(modalEl.value, {
      backdrop: 'static', // 바깥 클릭으로 닫히지 않게
      keyboard: false, // ESC로 닫히지 않게 (원하시면 true 로)
    })
  }
})

onBeforeUnmount(() => {
  if (!bsModal) return
  const instance = bsModal
  const el = instance._element || modalEl.value
  if (el) {
    el.addEventListener(
      'hidden.bs.modal',
      () => {
        if (typeof instance.dispose === 'function') {
          instance.dispose()
        }
      },
      { once: true },
    )
    instance.hide()
  }
  bsModal = null
})

function open() {
  if (bsModal) {
    if (props.dto.messageData) {
      dataList.value = JSON.parse(props.dto.messageData)
      columnList.value = Object.keys(dataList.value[0])
    }
    bsModal.show()
  }
}

function close() {
  if (bsModal) {
    bsModal.hide()
    dataList.value = []
    columnList.value = []
  }
}

function excelExport() {
  const table = document.getElementById(props.modalId + 'Table')
  if (!table) {
    return
  }
  const workbook = XSLX.utils.book_new()
  const sheet = XSLX.utils.table_to_sheet(table, { raw: true })
  XSLX.utils.book_append_sheet(workbook, sheet, 'data')
  const fileName = (props.dto && props.dto.senderPostmanId ? props.dto.senderPostmanId : 'interface-messages') + '.xlsx'
  XSLX.writeFile(workbook, fileName)
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <!-- Modal -->
  <div class="modal fade" :id="props.modalId" ref="modalEl" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" :aria-labelledby="props.modalId + 'Label'" aria-hidden="true">
    <div class="modal-dialog modal-xl data-modal-dialog">
      <div class="modal-content data-modal-content">
        <div class="modal-header justify-content-between">
          <h1 class="modal-title fs-5 pt-0" :id="props.modalId + 'Label'">{{ props.dto.senderAgentId }} <i class="bi bi-arrow-right"></i> {{ props.dto.recipientAgentId }}</h1>
          <div class="d-flex align-items-center gap-2">
            <button type="button" class="btn btn-success btn-sm" @click="excelExport">EXCEL</button>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
        </div>
        <div class="modal-body data-modal-body">
          <div class="data-table-wrapper table-responsive">
            <table class="table table-striped table-bordered table-hover table-sm align-middle fs-7 data-table" :id="props.modalId + 'Table'">
              <thead>
                <tr>
                  <th scope="col" class="text-center" v-if="columnList.length > 0" v-for="columnName in columnList">{{ columnName }}</th>
                  <th scope="col" class="text-center" v-else>no datas.</th>
                </tr>
              </thead>
              <tbody class="table-group-divider">
                <tr v-if="dataList.length > 0" v-for="dataMap in dataList">
                  <td class="text-center" v-for="columnName in columnList">{{ dataMap[columnName] }}</td>
                </tr>
                <tr v-else>
                  <td scope="row" class="text-center">no datas.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 모달이 화면을 거의 꽉 채우게 */
.data-modal-dialog {
  max-width: calc(100% - 4vh); /* 좌우 95% */
  margin: 2vh auto; /* 위아래 여백 조금 */
}

/* 모달 전체 높이를 화면의 95% 정도로 */
.data-modal-content {
  height: 95vh;
  display: flex;
  flex-direction: column;
}

/* 헤더/푸터 빼고 나머지 영역을 테이블 영역으로 */
.data-modal-body {
  flex: 1 1 auto;
  overflow: hidden; /* 여기서는 스크롤 안 하고 */
  padding: 0.5rem;
}

/* 실제 스크롤이 일어나는 영역 */
.data-table-wrapper {
  height: 100%;
  overflow: auto; /* 세로/가로 스크롤 모두 */
}

/* 컬럼이 많을 때 한 줄에 계속 붙게(가로 스크롤) */
.data-table {
  white-space: nowrap;
  border-collapse: separate;
  border-spacing: 0;
}

/* 헤더 전체를 sticky 처리 */
.data-table thead {
  position: sticky;
  top: 0;
  z-index: 2;
}

/* 헤더 배경/글자 색 지정 */
.data-table thead th {
  background-color: #343a40;
  color: #fff;
}

/* 모달 header 패딩 조정 */
.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  /* 상·하 4px, 좌·우는 기존처럼 16px */
  padding: 0.5rem 1rem;
}
</style>
