// modal/modal.js
const BulkModal = (() => {
    let cols = [];
    let saveCallback;
  
    // 1) 헤더 생성
    function renderHeader() {
      const $tr = $('#bulk-thead').empty();
      $tr.append('<th style="width:120px; text-align:center;">행추가/삭제/복사</th>');
      cols.forEach(c => {
        const w     = c.width || 220;
        const align = 'center';         
        const label = c.label || c.id.replace(/_bulk$/, '');
        $tr.append(`
          <th style="
            width:${w}px;
            text-align:${align};
          ">${label}</th>
        `);
      });
    }
  
    // 2) <tr> 생성
    function createRow(item) {
      const $tr = $('<tr>');
      // 조작 버튼
      $tr.append(`
        <td class="text-center">
          <button type="button" class="btn btn-sm btn-outline-primary add-row me-1">+</button>
          <button type="button" class="btn btn-sm btn-outline-danger remove-row me-1">-</button>
          <button type="button" class="btn btn-sm btn-outline-secondary copy-row">
            <i class="bi bi-files"></i>
          </button>
        </td>
      `);
  
      // 입력 셀
      cols.forEach(c => {
        const name  = `${c.id}[]`;
        const type  = c.type    || 'text';
        const align = c.align   || 'left';
        const $input = $(`
          <input
            type="${type}"
            id="${c.id}"
            name="${name}"
            class="form-control form-control-sm bulk-input noborder-input"
            style="text-align:${align};"
            autocomplete="off"
          />
        `);
  
        // item이 있으면 value 세팅
        if (item && item.hasOwnProperty(c.id)) {
          $input.val(item[c.id]);
          // value가 고정이라면 readonly 처리
          if (c.value !== undefined) {
            $input.prop('readonly', true);
          }
        } else if (c.value !== undefined) {
          // static value
          $input.val(c.value).prop('readonly', true);
        }
  
        // 포맷 함수
        if (typeof c.function === 'function') {
          $input.on('keyup', () => c.function($input[0]));
        }
  
        $tr.append($('<td>').append($input));
      });
  
      return $tr;
    }
  
    // 3) 행 추가
    function addRow($afterRow, item) {
      const $row = createRow(item);
      if ($afterRow && $afterRow.length) {
        $afterRow.after($row);
      } else {
        $('#bulkEntryTable tbody').append($row);
      }
    }
  
    // 4) 이벤트 바인딩
    function bindEvents() {
      $('.bulk-close-btn').off('click').on('click', close);
  
      $('#bulkEntryTable')
        .off('click', '.add-row').on('click', '.add-row', function() {
          addRow($(this).closest('tr'));
        })
        .off('click', '.remove-row').on('click', '.remove-row', function() {
          if ($('#bulkEntryTable tbody tr').length > 1) {
            $(this).closest('tr').remove();
          }
        })
        .off('click', '.copy-row').on('click', '.copy-row', function() {
          $(this).closest('tr').clone(true).insertAfter($(this).closest('tr'));
        });
  
      $('#saveBulkBtn').off('click').on('click', () => {
        const data = $('#bulkEntryTable tbody tr').map(function() {
          const row = {};
          $(this).find('input.bulk-input').each(function(i) {
            const key = cols[i].id.replace(/_bulk$/, '');
            row[key] = $(this).val();
          });
          return row;
        }).get();
  
        saveCallback(data);
        close();
      });
    }
  
    // 5) 모달 열기
    //    options: { width, maxWidth, margin }
    //    initialData: [{ registDate_bulk: '2025-06-20', ... }, ...]
    function open(columnDefs, onSave, options = {}, initialData = []) {
      cols         = columnDefs;
      saveCallback = onSave;
  
      // 스타일 옵션 적용
      const $modalContent = $('#bulkEntryModal > div');
      if (options.width)    $modalContent.css('width', options.width + 'px');
      if (options.maxWidth) $modalContent.css('max-width', options.maxWidth);
      if (options.margin)   $modalContent.css('margin', options.margin);
  
      renderHeader();
      $('#bulkEntryTable tbody').empty();
  
      // initialData가 있으면 그만큼 행 추가
      if (initialData.length) {
        initialData.forEach((item, idx) => {
          addRow(idx === 0 ? null : $('#bulkEntryTable tbody tr').last(), item);
        });
      } else {
        addRow(); // 기본 한 행
      }
  
      bindEvents();
      $('#bulkEntryModal').show();
    }
  
    // 6) 모달 닫기
    function close() {
      $('#bulkEntryModal').hide();
    }
  
    return { open, close };
  })();
  