<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>
<style>
  th {
    font-size: 11px;
    text-align: center;
  }

  td {
    text-align: center;
  }

  #resultList tbody tr {
    cursor: pointer;
    font-size: 12px;
  }

  .blockUI {
    z-index: 1500 !important;
  }

  .ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 180px;
  }

  .card-header {
    display: flex !important;
    align-items: center;
  }

  .card-header-tab {
    justify-content: flex-start !important;
  }

  .table-scroll {
    max-height: 300px;
    overflow-y: scroll;
  }

  .swal2-cancel {
    background-color: #ff0000 !important;
    color: #fff !important;
  }
</style>

<h1>1차 재검증 매물현황</h1>

<div class="col-md-12 col-xl-12">
  <div class="main-card mb-3 card">
    <div class="card-body">
      <form id="frm_srch_info" method="get" onsubmit="return false;">
        <input type="hidden" name="m" id="m" value="M801" />
        <input type="hidden" name="todo" id="todo" value="inq" />
        <input type="hidden" name="usr_id" value="" />

        <!-- 안내 -->
        <div class="alert alert-warning py-2 mb-3">
          <small class="mb-0">
            매물번호를 입력하면 <b>다른 조건은 무시</b>됩니다.
          </small>
        </div>

        <!-- 검색 폼 -->
        <div class="row g-3">

          <!-- 매물번호 -->
          <div class="col-md-1">
            <label class="form-label mb-1">매물번호</label>
            <input type="text" name="atcl_no" class="form-control form-control-sm" placeholder="매물번호" maxlength="10"
              onkeypress="atcl_no_enter(event)">
          </div>

          <!-- 현재상태 -->
          <div class="col-md-2">
            <label class="form-label mb-1">현재상태</label>
            <select name="stat_cd" class="form-select form-select-sm">
              <option value="">-선택-</option>
              <?php foreach ($codes as $c): ?>
                <?php if ($c['category'] === "STEP_VERIFICATION"): ?>
                  <option value="<?= $c['cd'] ?>"><?= $c['cd_nm'] ?></option>
                <?php endif; ?>
              <?php endforeach; ?>
            </select>
          </div>

          <!-- 중개소 -->
          <div class="col-md-1">
            <label class="form-label mb-1">중개소</label>
            <input type="text" name="realtor_nm" class="form-control form-control-sm" placeholder="중개소">
          </div>

          <!-- 배정여부 (2개 셀렉트) -->
          <div class="col-md-3">
            <label class="form-label mb-1">배정여부</label>
            <div class="d-flex gap-2">
              <select name="charger_gbn" id="code_charger_gbn" class="form-select form-select-sm">
                <option value="1">전화/서류담당자</option>
                <option value="2">등기부등본담당자</option>
              </select>
              <select name="assign_yn" id="assign_yn" class="form-select form-select-sm">
                <option value="A">-전체-</option>
                <option value="Y">배정</option>
                <option value="N">미배정</option>
              </select>
            </div>
          </div>
        </div>
        <div class="row g-3">
          <!-- 접수기간 -->
          <div class="col-md-3">
            <label class="form-label mb-1">접수기간</label>
            <div class="input-group input-group-sm">
              <input type="date" class="form-control" name="receipt_sdate" id="receipt_sdate" placeholder="시작일">
              <span class="input-group-text">~</span>
              <input type="date" class="form-control" name="receipt_edate" id="receipt_edate" placeholder="종료일">
            </div>
          </div>

          <!-- 완료기간 -->
          <div class="col-md-3">
            <label class="form-label mb-1">완료기간</label>
            <div class="input-group input-group-sm">
              <input type="text" class="form-control" name="complete_sdate" id="complete_sdate" placeholder="시작일">
              <span class="input-group-text">~</span>
              <input type="text" class="form-control" name="complete_edate" id="complete_edate" placeholder="종료일">
            </div>
          </div>

          <!-- 지역구분 -->
          <div class="col-md-4">
            <label class="form-label mb-1">지역구분</label>
            <div class="d-flex gap-2">
              <select name="srcSido" id="srcSido" class="form-select form-select-sm">
                <option value="">-시/도-</option>
                <?php foreach ($sido as $s): ?>
                  <option value="<?= $s['region_cd'] ?>"><?= $s['region_nm'] ?></option>
                <?php endforeach; ?>
              </select>
              <select name="srcGugun" id="srcGugun" class="form-select form-select-sm">
                <option value="">-시/군/구-</option>
              </select>
              <select name="srcDong" id="srcDong" class="form-select form-select-sm">
                <option value="">-읍/면/동-</option>
              </select>
            </div>
          </div>
        </div>
        <div class="row g-3">
          <!-- 담당자 (본부/팀/담당 3셀렉트) -->
          <div class="col-md-3">
            <label class="form-label mb-1">담당자</label>
            <div class="d-flex gap-2">
              <select name="bonbu" id="bonbu" class="form-select form-select-sm">
                <option value="">-본부-</option>
                <?php foreach ($bonbu as $d): ?>
                  <option value="<?= $d['dept_sq'] ?>"><?= $d['dept_nm'] ?></option>
                <?php endforeach; ?>
              </select>
              <select name="team" id="team" class="form-select form-select-sm">
                <option value="">-팀-</option>
              </select>
              <select name="damdang" id="damdang" class="form-select form-select-sm">
                <option value="">-담당자-</option>
              </select>
            </div>
          </div>

          <!-- 검증방식 -->
          <div class="col-md-2">
            <label class="form-label mb-1">검증방식</label>
            <div class="d-flex gap-2">
              <select name="vrfcreq_way" id="vrfcreq_way" class="form-select form-select-sm">
                <option value="">-검증방식-</option>
                <?php foreach ($codes as $c): ?>
                  <?php if ($c['category'] === "VRFCREQ_WAY"): ?>
                    <option value="<?= $c['cd'] ?>"><?= $c['cd_nm'] ?></option>
                  <?php endif; ?>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

          <!-- 매체사 -->
          <div class="col-md-1">
            <label class="form-label mb-1">매체사</label>
            <select name="rcpt_cpid" class="form-select form-select-sm">
              <option value="">-전체-</option>
              <?php foreach ($codes as $c): ?>
                <?php if ($c['category'] === "CP_ID"): ?>
                  <option value="<?= $c['cd'] ?>"><?= $c['cd_nm'] ?></option>
                <?php endif; ?>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-1 d-grid">
            <label class="form-label mb-1 invisible">검색</label>
            <button type="button" class="btn btn-primary" id="btnSearch">
              <i class="pe-7s-search me-1"></i>검색
            </button>
          </div>
        </div>

      </form>
    </div>
  </div>
</div>

<div class="col-md-12 col-xl-12">
  <div class="main-card mb-3 card">
    <div class="card-header d-flex align-items-center">
      <div class="d-flex align-items-center flex-wrap" style="gap: 8px; flex: 1">

      </div>

      <div class="ml-auto">
        <button class="btn btn-sm btn-outline-success" id="excel-download">
          <i class="fa fa-fw" aria-hidden="true" title="file-excel-o"></i>
          엑셀다운로드
        </button>
      </div>
    </div>

    <div class="card-body">
      <table id="resultList" class="table table-hover table-striped table-bordered">
        <thead>
          <tr>
            <th>매물번호</th>
            <th>진행상태</th>
            <th>접수시간</th>
            <th>검증방식</th>
            <th>주소</th>
            <th>상세주소</th>
            <th>매체사</th>
            <th>중개소</th>
            <th>서류/전화<br />담당자</th>
            <th>서류/전화<br />확인완료시간</th>
            <th>등기부등본<br />담당자</th>
            <th>검증완료<br />일시</th>
          </tr>
        </thead>
        <tbody>
          <!-- 여기는 비워둠: AJAX로 채움 -->
        </tbody>
      </table>
    </div>
  </div>
</div>


<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" />
<link href="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script defer src="/architectui/assets/js/datatable.kor.js"></script>
<script type="text/javascript" src="https://oapi.map.naver.com/openapi/v3/maps.js?ncpKeyId=dtounkwjc5"></script>
<script type="text/javascript">

  const date = new Date();
  const bonbuArr = <?= json_encode($bonbu, JSON_UNESCAPED_UNICODE); ?>;
  const teamArr = <?= json_encode($team, JSON_UNESCAPED_UNICODE); ?>;
  const userArr = <?= json_encode($user, JSON_UNESCAPED_UNICODE); ?>;

  var table;

  $(function () {

    $("#bonbu").on("change", function (e) {

      const value = e.target.value

      $("#dept_sq").empty()

      var str = "<option value=''>선택</option>"
      if (teamArr != null) {

        for (var i = 0; i < teamArr.length; i++) {
          if (value === teamArr[i].pdept_sq) {
            str += "<option value='" + teamArr[i].dept_sq + "'>" + teamArr[i].dept_nm + "</option>"
          }
        }
      }

      $("#dept_sq").append(str)

    });

    $("#srcSido, #srcGugun, #srcSido2, #srcGugun2").on("change", function (e) {

      const targetId = this.id;

      const isSecond = this.id.endsWith("2");

      const params = {
        srcSido: isSecond
          ? $("#srcSido2").val()
          : $("#frm_srch_info [name=srcSido]").val(),

        srcGugun: isSecond
          ? $("#srcGugun2").val()
          : $("#frm_srch_info [name=srcGugun]").val(),
      };


      $.ajax({
        url: "/manage/areas/getAreaList",
        method: "POST",
        dataType: "json",
        data: params,
        beforeSend: function () {
          blockUI.blockPage({
            message: tpl
          })
        },
        complete: function () {
          blockUI.unblockPage()
        },
        success: function (result) {

          switch (targetId) {
            case "srcSido":
              $("#srcGugun").empty()
              var str = "";
              str += "<option value=''>시/군/구</option>";

              if ($("#srcSido").val() !== "") {
                if (result.length > 0) {
                  for (var i = 0; i < result.length; i++) {
                    str += "<option value='" + result[i]['region_cd'] + "'>" + result[i].region_nm + "</option>";
                  }
                }
              }

              $("#srcGugun").append(str);

              break;

            case "srcGugun":
              $("#srcDong").empty()
              var str = "";
              str += "<option value=''>읍/면/동</option>";

              if (result.length > 0) {
                for (var i = 0; i < result.length; i++) {
                  str += "<option value='" + result[i]['region_cd'] + "'>" + result[i].region_nm + "</option>";
                }
              }

              $("#srcDong").append(str);
              break;
          }
        }
      });
    });


    $("#bonbu, #team, #bonbu2, #team2").on("change", function (e) {
      const targetId = this.id;


      var str = "";
      if (targetId === "bonbu" || targetId === "bonbu2") {
        const dept_sq = $("#" + targetId).val();

        str += `<option value="">-팀-</option>`;
        if (teamArr.length > 0) {
          for (var i = 0; i < teamArr.length; i++) {

            // 이 팀이 현재 본부에 속한 팀인지 체크
            if (String(teamArr[i].pdept_sq) === String(dept_sq)) {
              str += `
                              <option value="${teamArr[i].dept_sq}">${teamArr[i].dept_nm}</option>
                          `;
            }
          }
        }

        if (targetId === "bonbu") {
          $("#team").html(str);
        } else if (targetId === "bonbu2") {
          $("#team2").html(str);
        }

      } else if (targetId === "team" || targetId === "team2") {
        const dept_sq = $("#" + targetId).val();

        str += `<option value="">-담당자-</option>`;
        if (userArr.length > 0) {
          for (var i = 0; i < userArr.length; i++) {

            // 이 팀이 현재 본부에 속한 팀인지 체크
            if (String(userArr[i].dept_sq) === String(dept_sq)) {
              str += `
                              <option value="${userArr[i].usr_id}">${userArr[i].usr_nm}</option>
                          `;
            }
          }
        }

        if (targetId === "team") {
          $("#damdang").html(str);
        } else if (targetId === "team2") {
          $("#damdang2").html(str);
        }
      }

    });

    initReceiptDate();
    table = $('#resultList').DataTable({
      language: lang_kor,
      serverSide: true,
      processing: true,
      ajax: {
        url: '/m706/m706a/getResultList',
        type: 'GET',
        beforeSend: function () {
          blockUI.blockPage({
            message: tpl
          })
        },
        complete: function () {
          blockUI.unblockPage()
        },
        data: function (d) {

          d.atcl_no = $("#frm_srch_info [name=atcl_no]").val(); // 매물번호
          d.stat_cd = $("#frm_srch_info [name=stat_cd]").val(); // 현재상태
          d.realtor_nm = $("#frm_srch_info [name=realtor_nm]").val(); // 중개소
          d.charger_gbn = $("#frm_srch_info [name=charger_gbn]").val(); // 배정여부
          d.assign_yn = $("#frm_srch_info [name=assign_yn]").val(); // 배정여부2
          d.receipt_sdate = $("#frm_srch_info [name=receipt_sdate]").val(); // 접수기간1
          d.receipt_edate = $("#frm_srch_info [name=receipt_edate]").val(); // 접수기간2
          d.complete_sdate = $("#frm_srch_info [name=complete_sdate]").val(); // 완료기간1
          d.complete_edate = $("#frm_srch_info [name=complete_edate]").val(); // 완료기간2
          d.srcSido = $("#frm_srch_info [name=srcSido]").val(); // 시도
          d.srcGugun = $("#frm_srch_info [name=srcGugun]").val(); // 시군구
          d.srcDong = $("#frm_srch_info [name=srcDong]").val(); // 읍면동
          // d.bonbu = $("#frm_srch_info [name=bonbu]").val(); // 본부
          d.team = $("#frm_srch_info [name=team]").val(); // 팀
          d.damdang = $("#frm_srch_info [name=damdang]").val(); // 담당
          d.vrfcreq_way = $("#frm_srch_info [name=vrfcreq_way]").val(); // 검증방식1
          d.rcpt_cpid = $("#frm_srch_info [name=rcpt_cpid]").val(); // 매체사          

          d.start = d.start || 0
          d.length = d.length || 10
        },
      },
      "columnDefs": [
        { className: 'text-center', targets: '_all' },
        { 'targets': '_all', "defaultContent": "" },
      ],
      columns: [
        { data: 'atcl_no' },
        { data: 'pre_stat' },
        { data: 'insert_tm' },
        { data: 'vrfc_type' },
        { data: null, render: fn_region_render },
        { data: null, render: fn_addr_render },
        { data: 'cpid' },
        { data: 'realtor_nm' },
        { data: 'usr_nm', width: "80px" },
        { data: null, render: fn_tm_render },
        { data: 'reg_charger' },
        { data: 'result_tm' },

      ],
      // 옵션들 예시
      paging: true,
      searching: false,
      ordering: false,
    });

    $('#resultList tbody').on('click', 'tr', function (e) {
      if ($(e.target).closest('td.dt-no-rowclick').length) return;

      const rowData = table.row(this).data();
      if (!rowData) return;

      const vr_sq = rowData.vr_sq;
      window.open("<?= site_url('m706/m706a/detail') ?>/" + vr_sq, '_blank');
    });

    $('#btnSearch').on('click', function () {
      table.ajax.reload()
    });

    // 엑셀 다운로드 click
    $("#excel-download").on("click", function () {
      $.ajax({
        url: "/m706/m706a/excel",
        method: "GET",
        dataType: "json",
        data: $("#frm_srch_info").serialize(),
        beforeSend: function () {
          blockUI.blockPage({
            message: tpl
          })
        },
        complete: function () {
          blockUI.unblockPage()
        },
        success: function (result) {
          downloadExcel(result.data);
        }
      });
    });


  });

  // 접수기간 초기화 
  function initReceiptDate() {

    const before3 = new Date();
    before3.setDate(date.getDate() - 2);

    const fmt = d => d.toISOString().slice(0, 10);

    $('#receipt_sdate').val(fmt(before3));
    $('#receipt_edate').val(fmt(date));

    $("#bonbu").val("3");
    $("#bonbu").trigger("change");
    $("#bonbu").prop("disabled", true);

  }


  function atcl_no_enter(event) {
    if (event.keyCode == 13) {
      table.ajax.reload()
    }
  }

  function fn_region_render(data, type, row) {
    var str = "";

    str = row.region_nm + " " + row.rm_no;

    return str;
  }

  // 주소 render
  function fn_addr_render(data, type, row) {
    var str = "";

    if (row.address2b == null) {
      str = row.address2 + " " + row.address3;
    } else {
      str = row.address2b + " " + row.address3;
    }

    return str;
  }

  function fn_tm_render(data, type, row) {
    var str = "";

    if (row.update_res_tm == null) {
      str = row.stat_39_tm;
    } else {
      str = row.update_res_tm;
    }

    return str;
  }

  // 엑셀 다운로드
  function downloadExcel(data) {
    const ws = XLSX.utils.json_to_sheet(data);
    ws['!cols'] = [
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
      { wpx: 100 },
    ];

    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

    const blob = new Blob([wbout], { type: 'application/octet-stream' });

    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "1차_재검증_매물현황" + getDateTimeString() + ".xlsx";
    link.click();
    URL.revokeObjectURL(link.href);
  }


  function getDateTimeString() {
    const d = new Date();
    const yyyy = d.getFullYear();
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    const hh = String(d.getHours()).padStart(2, '0');
    const mi = String(d.getMinutes()).padStart(2, '0');
    const ss = String(d.getSeconds()).padStart(2, '0');
    return `${yyyy}${mm}${dd}${hh}${mi}${ss}`;
  }

  function extractCode(code) {

    var codeArr = new Array();

    if (codes.length) {

      for (var i = 0; i < codes.length; i++) {

        if (code === codes[i].category) {
          codeArr.push(codes[i]);
        }

      }

    }

    return codeArr;
  }


  // 이미지 프리뷰
  function fn_preview(src) {
    const $img = $('#imgPreview');

    // 이미지 표시
    $img.attr('src', src).show();

    $('#previewTitle').text('이미지 미리보기');


    const modal = new bootstrap.Modal(document.getElementById('previewModal'));
    modal.show();
  }
</script>
<?= $this->endSection() ?>