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

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

const modalEl = ref(null)
let bsModal = null
const activeTab = ref('general')
const agentConfig = reactive({
  description: '',
  myHostId: '',
  myHostName: '',
  myListenPort: 0,
  knownAgentList: [],
  statusChecker: {
    cron: '',
    consoleHostName: '',
    consoleListenPort: 0,
    consoleSslEnabled: false,
  },
  dataSourceConfig: [],
  sqlMapperLocations: [],
  logging: {
    logDirectory: '',
    logFileName: '',
    logName: '',
    maxHistory: 30,
    logPattern: '',
    rootLogLevel: 'INFO',
    packages: [],
  },
  dropBoxConfig: {
    receivedMessageStorageRoot: '',
    processedMessageStorageRoot: '',
    failureMessageStorageRoot: '',
    manualMessageStorageRoot: '',
    threadPoolSize: 0,
    retentionDaysOfProcessedMessage: 0,
    dropBoxList: [],
  },
  postmanConfig: {
    threadPoolSize: 0,
    postmanList: [],
  },
})
let originalDtoString = ''
const agentConfigDeleted = {
  knownAgentList: [],
  dataSourceConfig: [],
  logging: {
    packages: [],
  },
  dropBoxConfig: {
    dropBoxList: [],
  },
  postmanConfig: {
    postmanList: [],
  },
}

window.debugData = agentConfig

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

// 부모 컴포넌트에서 AgentConfigView 팝업 호출(defineExpose에 추가됨)
function open() {
  if (bsModal) {
    if (props.dto) {
      originalDtoString = JSON.stringify(props.dto)
      Object.assign(agentConfig, props.dto)
    }
    bsModal.show()
  }
}

// 부모 컴포넌트에서 AgentConfigView 팝업 닫기(defineExpose에 추가됨)
function close() {
  if (bsModal) {
    bsModal.hide()
  }
}

// props.dto 기준으로 agentConfig reload
function configReload() {
  Object.assign(agentConfig, JSON.parse(originalDtoString))
}

// agentConfig의 내용을 json 파일로 다운로드
function configExport() {
  const configCopy = JSON.parse(JSON.stringify(agentConfig))
  if (Array.isArray(configCopy.knownAgentList)) {
    configCopy.knownAgentList.forEach((item) => {
      delete item.selected
      delete item.added
    })
  }
  if (Array.isArray(configCopy.dataSourceConfig)) {
    configCopy.dataSourceConfig.forEach((item) => {
      delete item.selected
      delete item.added
    })
  }
  if (configCopy.dropBoxConfig && Array.isArray(configCopy.dropBoxConfig.dropBoxList)) {
    configCopy.dropBoxConfig.dropBoxList.forEach((item) => {
      delete item.selected
      delete item.added
    })
  }
  if (configCopy.postmanConfig && Array.isArray(configCopy.postmanConfig.postmanList)) {
    configCopy.postmanConfig.postmanList.forEach((item) => {
      delete item.selected
      delete item.added
    })
  }
  const configString = JSON.stringify(configCopy, null, 2)
  const blob = new Blob([configString], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'settings.json'
  document.body.append(a)
  a.click()
  URL.revokeObjectURL(url)
}

// agentConfig의 내용을 서버에 전송하여 저장
function configSave() {}

// knownAgent 한 줄 추가
function addKnownAgent() {
  const knownAgent = {
    hostId: '',
    hostName: '',
    listenPort: '',
    dropBoxIdList: [],
    routingHostIdList: [],
    added: true,
  }
  agentConfig.knownAgentList.push(knownAgent)
}

// 선택된 knownAgent 삭제
function deleteKnownAgent() {
  for (let i = agentConfig.knownAgentList.length - 1; i >= 0; i--) {
    if (agentConfig.knownAgentList[i].selected) {
      let splicedList = agentConfig.knownAgentList.splice(i, 1)
      if (Object.keys(splicedList[0]).indexOf('added') == -1) {
        agentConfigDeleted.knownAgentList.push(splicedList[0])
      }
    }
  }
}

// dataSource 한 줄 추가
function addDataSource() {
  const dataSource = {
    dataSourceId: '',
    driverClassName: '',
    url: '',
    username: '',
    password: '',
    initialSize: 10,
    minIdle: 10,
    maxIdle: 30,
    maxTotal: 300,
    maximumRowForTransaction: 1000,
    added: true,
  }
  agentConfig.dataSourceConfig.push(dataSource)
}

// 선택된 dataSource 삭제
function deleteDataSource() {
  for (let i = agentConfig.dataSourceConfig.length - 1; i >= 0; i--) {
    if (agentConfig.dataSourceConfig[i].selected) {
      let splicedList = agentConfig.dataSourceConfig.splice(i, 1)
      if (Object.keys(splicedList[0]).indexOf('added') == -1) {
        agentConfigDeleted.dataSourceConfig.push(splicedList[0])
      }
    }
  }
}

function addLoggingPackage() {
  agentConfig.logging.packages.push({ '': 'INFO' })
}

function deleteLoggingPackage() {
  const checkboxList = document.getElementsByClassName('agent-config-logging-packages-checkbox')
  for (let i = checkboxList.length - 1; i >= 0; i--) {
    if (checkboxList[i].checked) {
      agentConfig.logging.packages.splice(i, 1)
    }
  }
  for (let i = checkboxList.length - 1; i >= 0; i--) {
    checkboxList[i].checked = false
  }
}

function changeLoggingPackageName(loggingPackageObject, loggingPackageName, newLoggingPackageName) {
  newLoggingPackageName = newLoggingPackageName.trim()
  if (!newLoggingPackageName || loggingPackageName === newLoggingPackageName) {
    return
  }
  if (Object.prototype.hasOwnProperty.call(loggingPackageObject, newLoggingPackageName)) {
    return
  }
  loggingPackageObject[newLoggingPackageName] = loggingPackageObject[loggingPackageName]
  delete loggingPackageObject[loggingPackageName]
}

// dropBox 한 줄 추가
function addDropBox() {
  const dropBox = {
    dropBoxId: '',
    taskType: 'RECEIVE_DB_TO_DB_SAVE',
    dataSourceId: '',
    sqlId: '',
    description: '',
    added: true,
  }
  agentConfig.dropBoxConfig.dropBoxList.push(dropBox)
}

// 선택된 dropBox 삭제
function deleteDropBox() {
  for (let i = agentConfig.dropBoxConfig.dropBoxList.length - 1; i >= 0; i--) {
    if (agentConfig.dropBoxConfig.dropBoxList[i].selected) {
      let splicedList = agentConfig.dropBoxConfig.dropBoxList.splice(i, 1)
      if (Object.keys(splicedList[0]).indexOf('added') == -1) {
        agentConfigDeleted.dropBoxConfig.dropBoxList.push(splicedList[0])
      }
    }
  }
}

// postman 한 줄 추가
function addPostman() {
  const postman = {
    postmanId: '',
    taskType: '',
    action: {
      type: 'SCHEDULED',
      cron: '1 0/1 * * * *',
    },
    message: {
      messageType: 'TRANSFER_DB_TO_DB',
      dataSourceId: '',
      sqlId: '',
      postProcessingSqlId: '',
    },
    recipientHostId: '',
    recipientDropBoxId: '',
    description: '',
    added: true,
  }
  agentConfig.postmanConfig.postmanList.push(postman)
}

// 선택된 postman 삭제
function deletePostman() {
  for (let i = agentConfig.postmanConfig.postmanList.length - 1; i >= 0; i--) {
    if (agentConfig.postmanConfig.postmanList[i].selected) {
      let splicedList = agentConfig.postmanConfig.postmanList.splice(i, 1)
      if (Object.keys(splicedList[0]).indexOf('added') == -1) {
        agentConfigDeleted.postmanConfig.postmanList.push(splicedList[0])
      }
    }
  }
}

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

<template>
  <datalist id="dataSourceIdDataList">
    <option v-for="dataSource in agentConfig.dataSourceConfig" :value="dataSource.dataSourceId" :key="dataSource.dataSourceId">{{ dataSource.dataSourceId }}</option>
  </datalist>
  <!-- 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'">에이전트 설정</h1>
          <div class="d-flex align-items-center gap-2">
            <button type="button" class="btn btn-info btn-sm" @click="configReload">Reload</button>
            <button type="button" class="btn btn-success btn-sm" @click="configExport">Export</button>
            <button type="button" class="btn btn-primary btn-sm" @click="configSave">Save</button>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
        </div>
        <div class="modal-body data-modal-body">
          <ul class="nav nav-tabs mb-3" id="agentConfigTab" role="tablist">
            <li class="nav-item" role="presentation">
              <button class="nav-link active" id="general-tab" data-bs-toggle="tab" data-bs-target="#general-tab-pane" type="button" role="tab" aria-controls="general-tab-pane" aria-selected="true">일반</button>
            </li>
            <li class="nav-item" role="presentation">
              <button class="nav-link" id="dropbox-tab" data-bs-toggle="tab" data-bs-target="#dropbox-tab-pane" type="button" role="tab" aria-controls="dropbox-tab-pane" aria-selected="false">DropBox</button>
            </li>
            <li class="nav-item" role="presentation">
              <button class="nav-link" id="postman-tab" data-bs-toggle="tab" data-bs-target="#postman-tab-pane" type="button" role="tab" aria-controls="postman-tab-pane" aria-selected="false">Postman</button>
            </li>
          </ul>

          <div class="tab-content m-1" id="agentConfigTabContent">
            <div class="tab-pane fade show active tab-pane-scroll" id="general-tab-pane" role="tabpanel" aria-labelledby="general-tab" tabindex="0">
              <div class="row mb-2">
                <div class="col-md-12">
                  <h5>일반 설정(Agent General)</h5>
                </div>
              </div>
              <div class="row mb-2">
                <div class="input-group">
                  <span class="input-group-text" id="agent-config-description-label">에이전트 설명(description)</span>
                  <input type="text" class="form-control" id="agent-config-description-input" aria-describedby="agent-config-description-label agent-config-description-input" v-model="agentConfig.description" />
                </div>
              </div>
              <div class="row mb-2">
                <div class="col-md-3">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-my-host-id-label">에이전트 아이디(myHostId)</span>
                    <input type="text" class="form-control" id="agent-config-my-host-id-input" aria-describedby="agent-config-my-host-id-label agent-config-my-host-id-input" v-model="agentConfig.myHostId" readonly />
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-hecker-console-host-name-label">에이전트 호스트(myHostName)</span>
                    <input type="text" class="form-control" id="agent-config-my-host-name-input" aria-describedby="agent-config-my-host-name-label agent-config-my-host-name-input" v-model="agentConfig.myHostName" readonly />
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-my-listen-port-label">에이전트 포트(myListenPort)</span>
                    <input type="number" class="form-control" id="agent-config-my-listen-port-input" aria-describedby="agent-config-my-listen-port-label agent-config-my-listen-port-input" v-model="agentConfig.myListenPort" readonly />
                  </div>
                </div>
              </div>
              <hr />
              <div class="row m-1">
                <div class="card p-0">
                  <div class="card-header d-flex">
                    <h5 class="mb-0">상대 에이전트 목록(knownAgentList)</h5>
                    <div class="ms-auto">
                      <button type="button" class="btn btn-sm btn-success" @click.prevent="addKnownAgent">추가</button>
                      <button type="button" class="btn btn-sm btn-danger ms-2" @click.prevent="deleteKnownAgent">삭제</button>
                    </div>
                  </div>
                  <div class="card-body">
                    <table class="table table-striped table-bordered align-middle">
                      <thead>
                        <tr>
                          <th scope="col" class="text-center">선택</th>
                          <th scope="col" class="text-center">에이전트 아이디(hostId)</th>
                          <th scope="col" class="text-center">에이전트 호스트(hostName)</th>
                          <th scope="col" class="text-center">에이전트 포트(listenPort)</th>
                          <th scope="col" class="text-center">연결 경로(routingHostIdList)</th>
                        </tr>
                      </thead>
                      <tbody class="table-group-divider">
                        <tr v-if="agentConfig.knownAgentList.length > 0" v-for="(knownAgent, index) in agentConfig.knownAgentList" :key="index">
                          <td scope="row" class="text-center"><input type="checkbox" class="form-check-input" v-model="knownAgent.selected" /></td>
                          <td><input type="text" class="form-control" v-model="knownAgent.hostId" /></td>
                          <td><input type="text" class="form-control" v-model="knownAgent.hostName" /></td>
                          <td><input type="number" class="form-control" v-model="knownAgent.listenPort" /></td>
                          <td><input type="text" class="form-control" v-model="knownAgent.routingHostIdList" /></td>
                        </tr>
                        <tr v-else>
                          <td scope="row" class="text-center" colspan="5">no agent.</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
              <hr />
              <div class="row mb-2">
                <div class="col-md-12">
                  <h5>statusChecker</h5>
                </div>
              </div>
              <div class="row mb-2">
                <div class="col-md-3">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-status-checker-cron">cron</span>
                    <input type="text" class="form-control" id="agent-config-status-checker-cron-input" aria-describedby="agent-config-status-checker-cron-label agent-config-status-checker-cron-input" v-model="agentConfig.statusChecker.cron" />
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-status-checker-console-host-name-label">consoleHostName</span>
                    <input type="text" class="form-control" id="agent-config-status-checker-console-host-name-input" aria-describedby="agent-config-status-checker-console-host-name-label agent-config-status-checker-console-host-name-input" v-model="agentConfig.statusChecker.consoleHostName" />
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-status-checker-console-listen-port-label">consoleListenPort</span>
                    <input type="number" class="form-control" id="agent-config-status-checker-console-listen-port-input" aria-describedby="agent-config-status-checker-console-listen-port-label agent-config-status-checker-console-listen-port-input" v-model="agentConfig.statusChecker.consoleListenPort" />
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-status-checker-console-ssl-enabled-label">consoleSslEnabled</span>
                    <div class="form-check form-switch form-switch-lg">
                      <input class="form-check-input" type="checkbox" role="switch" id="agent-config-status-checker-console-ssl-enabled-input" v-model="agentConfig.statusChecker.consoleSslEnabled" />
                    </div>
                  </div>
                </div>
              </div>
              <hr />
              <!-- dataSource Configuration-->
              <div class="row m-1">
                <div class="card p-0">
                  <div class="card-header d-flex">
                    <h5 class="mb-0">데이터소스 설정(dataSourceConfig)</h5>
                    <div class="ms-auto">
                      <button type="button" class="btn btn-sm btn-success" @click.prevent="addDataSource">추가</button>
                      <button type="button" class="btn btn-sm btn-danger ms-2" @click.prevent="deleteDataSource">삭제</button>
                    </div>
                  </div>
                  <div class="card-body">
                    <table class="table table-striped table-bordered table-sm align-middle">
                      <thead>
                        <tr>
                          <th scope="col" class="text-center">선택</th>
                          <th scope="col" class="text-center">dataSourceId</th>
                          <th scope="col" class="text-center">driverClassName</th>
                          <th scope="col" class="text-center">url</th>
                          <th scope="col" class="text-center">username</th>
                          <th scope="col" class="text-center">password</th>
                          <th scope="col" class="text-center">initialSize</th>
                          <th scope="col" class="text-center">minIdle</th>
                          <th scope="col" class="text-center">maxIdle</th>
                          <th scope="col" class="text-center">maxTotal</th>
                          <th scope="col" class="text-center">maximumRowForTransaction</th>
                        </tr>
                      </thead>
                      <tbody class="table-group-divider">
                        <tr v-if="agentConfig.dataSourceConfig.length > 0" v-for="(dataSource, index) in agentConfig.dataSourceConfig" :key="index">
                          <td scope="row" class="text-center"><input type="checkbox" class="form-check-input" v-model="dataSource.selected" /></td>
                          <td><input type="text" class="form-control" v-model="dataSource.dataSourceId" /></td>
                          <td><input type="text" class="form-control" v-model="dataSource.driverClassName" /></td>
                          <td><input type="text" class="form-control" v-model="dataSource.url" /></td>
                          <td><input type="text" class="form-control" v-model="dataSource.username" /></td>
                          <td><input type="password" class="form-control" v-model="dataSource.password" /></td>
                          <td><input type="number" class="form-control" v-model="dataSource.initialSize" /></td>
                          <td><input type="number" class="form-control" v-model="dataSource.minIdle" /></td>
                          <td><input type="number" class="form-control" v-model="dataSource.maxIdle" /></td>
                          <td><input type="number" class="form-control" v-model="dataSource.maxTotal" /></td>
                          <td><input type="number" class="form-control" v-model="dataSource.maximumRowForTransaction" /></td>
                        </tr>
                        <tr v-else>
                          <td scope="row" class="text-center" colspan="11">no dataSource.</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
              <hr />
              <div class="row m-1">
                <div class="card p-0">
                  <div class="card-header"><h5>logging</h5></div>
                  <div class="card-body">
                    <div class="row mb-2">
                      <div class="col-md-3">
                        <div class="input-group">
                          <span class="input-group-text" id="agent-config-logging-log-directory">logDirectory</span>
                          <input type="text" class="form-control" id="agent-config-logging-log-directory-input" aria-describedby="agent-config-logging-log-directory-label agent-config-logging-log-directory-input" v-model="agentConfig.logging.logDirectory" />
                        </div>
                      </div>
                      <div class="col-md-3">
                        <div class="input-group">
                          <span class="input-group-text" id="agent-config-logging-log-file-name">logFileName</span>
                          <input type="text" class="form-control" id="agent-config-logging-log-file-name-input" aria-describedby="agent-config-logging-log-file-name-label agent-config-logging-log-file-name-input" v-model="agentConfig.logging.logFileName" />
                        </div>
                      </div>
                      <div class="col-md-3">
                        <div class="input-group">
                          <span class="input-group-text" id="agent-config-logging-log-name">logName</span>
                          <input type="text" class="form-control" id="agent-config-logging-log-name-input" aria-describedby="agent-config-logging-log-name-label agent-config-logging-log-name-input" v-model="agentConfig.logging.logName" />
                        </div>
                      </div>
                    </div>
                    <div class="row mb-2">
                      <div class="col-md-3">
                        <div class="input-group">
                          <span class="input-group-text" id="agent-config-logging-max-history">maxHistory</span>
                          <input type="number" class="form-control" id="agent-config-logging-max-history-input" aria-describedby="agent-config-logging-max-history-label agent-config-logging-max-history-input" v-model="agentConfig.logging.maxHistory" />
                        </div>
                      </div>
                      <div class="col-md-3">
                        <div class="input-group">
                          <span class="input-group-text" id="agent-config-logging-log-pattern">logPattern</span>
                          <input type="text" class="form-control" id="agent-config-logging-log-pattern-input" aria-describedby="agent-config-logging-log-pattern-label agent-config-logging-log-pattern-input" v-model="agentConfig.logging.logPattern" />
                        </div>
                      </div>
                      <div class="col-md-3">
                        <div class="input-group">
                          <span class="input-group-text" id="agent-config-logging-root-log-level">rootLogLevel</span>
                          <input type="text" class="form-control" id="agent-config-root-log-level-input" aria-describedby="agent-config-logging-root-log-level-label agent-config-logging-root-log-level-input" v-model="agentConfig.logging.rootLogLevel" />
                        </div>
                      </div>
                    </div>
                    <div class="d-flex">
                      <h6 class="mb-0">logging packages</h6>
                      <div class="ms-auto">
                        <button type="button" class="btn btn-sm btn-success" @click.prevent="addLoggingPackage">추가</button>
                        <button type="button" class="btn btn-sm btn-danger ms-2" @click.prevent="deleteLoggingPackage">삭제</button>
                      </div>
                    </div>
                    <table class="table table-striped table-bordered align-middle">
                      <thead>
                        <tr>
                          <th scope="col" class="text-center">선택</th>
                          <th scope="col" class="text-center">package</th>
                          <th scope="col" class="text-center">level</th>
                        </tr>
                      </thead>
                      <tbody class="table-group-divider">
                        <tr v-if="agentConfig.logging.packages.length > 0" v-for="(loggingPackage, rowIndex) in agentConfig.logging.packages">
                          <td scope="row" class="text-center"><input type="checkbox" class="form-check-input agent-config-logging-packages-checkbox" /></td>
                          <template v-for="(level, packageName) in loggingPackage" :key="packageName">
                            <td>
                              <input type="text" class="form-control" :value="packageName" @change="changeLoggingPackageName(loggingPackage, packageName, $event.target.value)" />
                            </td>
                            <td>
                              <select class="form-select" v-model="loggingPackage[packageName]">
                                <option value="TRACE">TRACE</option>
                                <option value="DEBUG">DEBUG</option>
                                <option value="INFO">INFO</option>
                                <option value="WARN">WARN</option>
                                <option value="ERROR">ERROR</option>
                                <option value="OFF">OFF</option>
                              </select>
                            </td>
                          </template>
                        </tr>
                        <tr v-else>
                          <td scope="row" class="text-center" colspan="3">no logging packages.</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
              <hr />
            </div>

            <div class="tab-pane fade tab-pane-scroll" id="dropbox-tab-pane" role="tabpanel" aria-labelledby="dropbox-tab" tabindex="0">
              <div class="row mb-2">
                <div class="col-md-12">
                  <h5>수신 일반(DropBox General)</h5>
                </div>
              </div>
              <div class="row mb-2">
                <div class="col-md-5">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-received-message-storage-root-label">수신 메시지 저장 경로(receivedMessageStorageRoot)</span>
                    <input type="text" class="form-control" id="agent-config-received-message-storage-root-input" aria-describedby="agent-config-received-message-storage-root-label agent-config-received-message-storage-root-input" v-model="agentConfig.dropBoxConfig.receivedMessageStorageRoot" />
                  </div>
                </div>
                <div class="col-md-5">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-processed-message-storage-root-label">처리 메시지 저장 경로(processedMessageStorageRoot)</span>
                    <input type="text" class="form-control" id="agent-config-processed-message-storage-root-input" aria-describedby="agent-config-processed-message-storage-root-label agent-config-processed-message-storage-root-input" v-model="agentConfig.dropBoxConfig.processedMessageStorageRoot" />
                  </div>
                </div>
              </div>
              <div class="row mb-2">
                <div class="col-md-5">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-failure-message-storage-root-label">실패 메시지 저장 경로(failureMessageStorageRoot)</span>
                    <input type="text" class="form-control" id="agent-config-failure-message-storage-root-input" aria-describedby="agent-config-failure-message-storage-root-label agent-config-failure-message-storage-root-input" v-model="agentConfig.dropBoxConfig.failureMessageStorageRoot" />
                  </div>
                </div>
                <div class="col-md-5">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-manual-message-storage-root-label">수동 메시지 저장 경로(manualMessageStorageRoot)</span>
                    <input type="text" class="form-control" id="agent-config-manual-message-storage-root-input" aria-describedby="agent-config-manual-message-storage-root-label agent-config-manual-message-storage-root-input" v-model="agentConfig.dropBoxConfig.manualMessageStorageRoot" />
                  </div>
                </div>
              </div>
              <div class="row mb-2">
                <div class="col-md-5">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-drop-box-thread-pool-size-label">드롭박스 처리 쓰레드풀 크기(threadPoolSize)</span>
                    <input type="number" class="form-control" id="agent-config-drop-box-thread-pool-size-input" aria-describedby="agent-config-drop-box-thread-pool-size-label agent-config-drop-box-thread-pool-size-input" v-model="agentConfig.dropBoxConfig.threadPoolSize" />
                  </div>
                </div>
                <div class="col-md-5">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-drop-box-retent-days-of-processed-message-label">메시지 파일 유지 기간(retentionDaysOfProcessedMessage)</span>
                    <input type="number" class="form-control" id="agent-config-drop-box-retent-days-of-processed-message-input" aria-describedby="agent-config-drop-box-retent-days-of-processed-message-label agent-config-drop-box-retent-days-of-processed-message-input" v-model="agentConfig.dropBoxConfig.retentionDaysOfProcessedMessage" />
                  </div>
                </div>
              </div>
              <hr />
              <div class="row m-1">
                <div class="card p-0">
                  <div class="card-header d-flex">
                    <h5 class="mb-0">수신 목록 설정(dropBoxList)</h5>
                    <div class="ms-auto">
                      <button type="button" class="btn btn-sm btn-success" @click.prevent="addDropBox">추가</button>
                      <button type="button" class="btn btn-sm btn-danger ms-2" @click.prevent="deleteDropBox">삭제</button>
                    </div>
                  </div>
                  <div class="card-body table-scroll">
                    <table class="table table-striped table-bordered table-sm align-middle table-sticky">
                      <thead>
                        <tr>
                          <th scope="col" class="text-center">선택</th>
                          <th scope="col" class="text-center">드롭박스ID (dropBoxId)</th>
                          <th scope="col" class="text-center">수신 처리 방식 (taskType)</th>
                          <th scope="col" class="text-center">데이터소스ID (dataSourceId)</th>
                          <th scope="col" class="text-center">SQL ID(sqlId)</th>
                          <th scope="col" class="text-center">설명 (description)</th>
                        </tr>
                      </thead>
                      <tbody class="table-group-divider">
                        <tr v-if="agentConfig.dropBoxConfig.dropBoxList.length > 0" v-for="(dropBox, index) in agentConfig.dropBoxConfig.dropBoxList" :key="index">
                          <td scope="row" class="text-center"><input type="checkbox" class="form-check-input" v-model="dropBox.selected" /></td>
                          <td><input type="text" class="form-control" v-model="dropBox.dropBoxId" /></td>
                          <td><input type="text" class="form-control" v-model="dropBox.taskType" /></td>
                          <td><input type="text" class="form-control" v-model="dropBox.dataSourceId" list="dataSourceIdDataList" /></td>
                          <td><input type="text" class="form-control" v-model="dropBox.sqlId" /></td>
                          <td><input type="text" class="form-control" v-model="dropBox.description" /></td>
                        </tr>
                        <tr v-else>
                          <td scope="row" class="text-center" colspan="6">no dropBox.</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
              <hr />
            </div>
            <div class="tab-pane fade" id="postman-tab-pane" role="tabpanel" aria-labelledby="postman-tab" tabindex="0">
              <div class="row mb-2">
                <div class="col-md-12">
                  <h5>전송 일반 (Postman General)</h5>
                </div>
              </div>
              <div class="row mb-2">
                <div class="col-md-5">
                  <div class="input-group">
                    <span class="input-group-text" id="agent-config-postman-thread-pool-size-label">전송 쓰레드풀 크기 (threadPoolSize)</span>
                    <input type="number" class="form-control" id="agent-config-postman-thread-pool-size-input" aria-describedby="agent-config-postman-thread-pool-size-label agent-config-postman-thread-pool-size-input" v-model="agentConfig.postmanConfig.threadPoolSize" />
                  </div>
                </div>
              </div>
              <hr />
              <div class="row m-1">
                <div class="card p-0">
                  <div class="card-header d-flex">
                    <h5 class="mb-0">전송 목록 설정(postmanList)</h5>
                    <div class="ms-auto">
                      <button type="button" class="btn btn-sm btn-success" @click.prevent="addPostman">추가</button>
                      <button type="button" class="btn btn-sm btn-danger ms-2" @click.prevent="deletePostman">삭제</button>
                    </div>
                  </div>
                  <div class="card-body table-scroll">
                    <table class="table table-striped table-bordered table-sm align-middle table-sticky">
                      <thead>
                        <tr>
                          <th scope="col" class="text-center border-top border-bottom align-middle" rowspan="2">선택</th>
                          <th scope="col" class="text-center border-top border-bottom align-middle" rowspan="2">포스트맨ID (postmanId)</th>
                          <th scope="col" class="text-center border-top border-bottom align-middle" rowspan="2">전송 처리 방식 (taskType)</th>
                          <th scope="col" class="text-center border-top border-bottom align-middle" colspan="2">동작 방식 (action)</th>
                          <th scope="col" class="text-center border-top border-bottom align-middle" colspan="4">전송 메시지 (message)</th>
                          <th scope="col" class="text-center border-top border-bottom align-middle" rowspan="2">수신 에이전트 호스트ID (recipientHostId)</th>
                          <th scope="col" class="text-center border-top border-bottom align-middle" rowspan="2">수신 에이전트 드롭박스ID (recipientDropBoxId)</th>
                          <th scope="col" class="text-center border-top border-bottom align-middle" rowspan="2">설명 (description)</th>
                        </tr>
                        <tr>
                          <th scope="col" class="text-center">방식 (type)</th>
                          <th scope="col" class="text-center">cron</th>
                          <th scope="col" class="text-center">메시지 타입 (messageType)</th>
                          <th scope="col" class="text-center">데이터소스ID (dataSourceId)</th>
                          <th scope="col" class="text-center">SQL ID (sqlId)</th>
                          <th scope="col" class="text-center">전송 완료 후 동작 SQL ID (postProcessingSqlId)</th>
                        </tr>
                      </thead>
                      <tbody class="table-group-divider">
                        <tr v-if="agentConfig.postmanConfig.postmanList.length > 0" v-for="(postman, index) in agentConfig.postmanConfig.postmanList" :key="index">
                          <td scope="row" class="text-center"><input type="checkbox" class="form-check-input" v-model="postman.selected" /></td>
                          <td><input type="text" class="form-control" v-model="postman.postmanId" /></td>
                          <td><input type="text" class="form-control" v-model="postman.taskType" /></td>
                          <td><input type="text" class="form-control" v-model="postman.action.type" /></td>
                          <td><input type="text" class="form-control" v-model="postman.action.cron" /></td>
                          <td><input type="text" class="form-control" v-model="postman.message.messageType" /></td>
                          <td><input type="text" class="form-control" v-model="postman.message.dataSourceId" list="dataSourceIdDataList" /></td>
                          <td><input type="text" class="form-control" v-model="postman.message.sqlId" /></td>
                          <td><input type="text" class="form-control" v-model="postman.message.postProcessingSqlId" /></td>
                          <td><input type="text" class="form-control" v-model="postman.recipientHostId" /></td>
                          <td><input type="text" class="form-control" v-model="postman.recipientDropBoxId" /></td>
                          <td><input type="text" class="form-control" v-model="postman.description" /></td>
                        </tr>
                        <tr v-else>
                          <td scope="row" class="text-center" colspan="12">no postman.</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
              <hr />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 모달이 화면을 거의 꽉 채우게 */
.data-modal-dialog {
  max-width: calc(100% - 4vh);
  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;
  display: flex;
  flex-direction: column;
}

/* 모달 header 패딩 조정 */
.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 1rem;
}

/* 큰 스위치용 커스텀 클래스 */
.form-switch.form-switch-lg .form-check-input {
  width: 3rem;
  height: 1.5rem;
}

.form-switch.form-switch-lg {
  padding-left: 3.5rem;
  padding-top: 0.2rem;
}

.tab-content {
  flex: 1 1 auto;
  min-height: 0;
}

.tab-pane-scroll {
  height: 100%; /* tab-content 높이에 맞추기 */
  overflow-y: auto; /* 세로 스크롤 */
  overflow-x: hidden; /* 가로 스크롤은 숨기기 */
}

/* 카드 안에서만 스크롤되는 테이블 영역 */
.table-scroll {
  max-height: 50vh; /* 필요에 따라 조절 */
  overflow: auto;
  position: relative; /* sticky 기준 컨테이너 */
  padding-top: 0;
}

/* sticky header를 쓰는 테이블 공용 스타일 */
.table-sticky {
  white-space: nowrap;
  border-collapse: separate;
  border-spacing: 0;
}

/* thead 전체를 sticky로 고정 */
.table-sticky thead {
  position: sticky;
  top: 0;
  z-index: 2;
}

/* 헤더 셀 스타일 */
.table-sticky thead th {
  background-color: #343a40; /* 덮어씌우는 느낌으로 진하게 */
  color: #fff;
}
</style>
