<!DOCTYPE html>
<html lang="en" dir="rtl">
<head>
  <title>Nikan</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="./js/jquery.min.js"></script>
  <script src="./js/bootstrap.min.js"></script>
  <script src="moment.min.js"></script>
  
  <!--  <link rel="stylesheet" href="js/bootstrap-theme.min.css" />-->
  <link rel="stylesheet" href="./js/jquery.Bootstrap-PersianDateTimePicker.css"/>
  <script src="./js/jalaali.js" type="text/javascript"></script>
  <script src="./js/jquery.Bootstrap-PersianDateTimePicker.js" type="text/javascript"></script>
  <script src="./js/jalali-moment.browser.js"></script>
  <script>
    let inputMobile = null, inputCode = null;
    let onFetch = false;
    let lastTime = 0;

    function OnChangeCodeMely(e) {
      try {
        if (e.value.length >= 4) {
          const v2 = inputMobile.value;
          GetReport(e.value, v2.length >= 4 ? v2 : null);
        }
      } catch {
      }
    }
    
    function OnChangeMobile(e) {
      try {
        if (e.value.length >= 4) {
          const v1 = inputCode.value;
          GetReport(v1.length >= 4 ? v1 : null, e.value);
        }
      } catch {
      }
    }
    
    function IsFilterActive() {
      try {
        if (inputMobile == null || inputCode == null) return false;
        return inputMobile.value >= 4 || inputCode.value >= 4;
      } catch {
        return true;
      }
    }
    
    setInterval(FetchReport, 1000);
    
    async function OnDocumentLoad() {
      inputMobile = document.getElementById('inputMobile')
      inputCode = document.getElementById('inputCode')
    }
    
    function GetIranDate(date) {
      if (date === null) return 'تنظیم نشده است';
      return moment(date, 'YYYY/MM/DD').utc().format("YYYY-MM-DD");
    }
    
    function GetIranTime(time) {
      if (time === null) return 'تنظیم نشده است';
      return moment(time, 'HH:mm:ss').utc().format("HH:mm");
    }
    
    function GetRecipCode(date, code) {
      code = ("000" + code).slice(-4);
      return (date + '-' + code).replaceAll('/', '').slice(-9);
    }
    
    function ButtonAction(Id, action, time) {
      if (action === "delete") {
        if (confirm(`ایا از حذف رکور کد ${Id} اطمینان دارید ؟`)) {
          $.get(`/delete/${Id}`).done(() => Get(lastReport));
        }
        return;
      }
      
      if (action === 'cancel') {
        if (confirm(`ایا از لغو رزرو کد ${Id} اطمینان دارید ؟`)) {
          const sms = confirm("آیا اس ام اس لغو ارسال شود؟");
          $.get(`/cancel/${Id}/${sms ? 1 : 0}`).done(() => Get(lastReport));
        }
        return;
      }
      
      if (action === 'accept') {
        window.workId = Id;
        return;
      }
      if (action === 'accept-send') {
        const utc = moment.from(time, 'fa', 'YYYY/MM/DD HH:mm:ss').locale('en').format('YYYY/MM/DD');
        const sp = time.split(' ');
        if (sp.length === 2) {

          const settings = {
            "url": `/accept/${window.workId}`,
            "method": "POST",
            "timeout": 0,
            "headers": {
              "Content-Type": "application/json"
            }, "data": JSON.stringify({utc, time}),
          };

          $.ajax(settings).done(() => Get(lastReport));
        }
        return;
      }
    }
    
    let lastReport = "";
    
    function GetReport(meli, mobile) {
      let url = "";
      if (meli == null && mobile == null) {
        url = `/logs-today`;
      } else url = `/logs-filter/${meli}/${mobile}`;
      lastReport = url;
      Get(url);
    }
    
    function Get(url) {
      $.get({url, timeout: 10000}).done(function (data) {
        if (url === '/logs-today') lastTime = Date.now();
        onFetch = false;
        const table = document.getElementById("table-content");
        table.innerHTML = "";
        if (data.length > 0) {
          for (let i = 0; i < data.length; i += 1) {
            const {
              Id, time, date, reserveTime, reserveDate,
              mobile, codeMeli, bime, sherkat,
              IsReject, IsAccept, Sms, Code
            } = data[i];
            let row = "";
            row += "<tr>";
            row += `<td class="text-center">${i + 1}</td>`
            row += `<td class="text-center">${Id}</td>`
            
            row += `<td class="text-center">${GetIranDate(date)}</td>`
            row += `<td class="text-center">${GetIranTime(time)}</td>`
            row += `<td class="text-center">${codeMeli}</td>`
            row += `<td class="text-center">${mobile}</td>`
            row += `<td class="text-center">${bime == null ? "ثبت نشده" : bime}</td>`
            row += `<td class="text-center">${sherkat == null ? "ثبت نشده" : sherkat}</td>`
            row += `<td class="text-center">${GetIranDate(reserveDate)}</td>`
            row += `<td class="text-center">${GetIranTime(reserveTime)}</td>`
            row += `<td class="text-center">${GetRecipCode(date, Code)}</td>`
            
            if (IsReject === 0 && IsAccept === 0) {
              row += `<td class="text-center">ارسال نشده است.</td>`
              row += `<td class="text-center">`;
              row += `<div class="btn-group">`;
              row += `<button onclick="ButtonAction(${Id}, 'delete')" type="button" class="btn btn-danger">حذف</button>`;
              row += `<button onclick="ButtonAction(${Id}, 'accept')" type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">تاییید </button>`;
              row += `<button onclick="ButtonAction(${Id}, 'cancel')" type="button" class="btn btn-warning">لغو </button>`;
              row += `</div>`;
              row += `</td>`;
              
            } else {
              row += `<td class="text-center" style="max-width: 200px"><pre>${Sms}</pre</td>`
              row += `<td class="text-center">`;
              row += `<div class="btn-group">`;
              if (IsReject === 1) row += "لغو شده";
              if (IsAccept === 1) row += "تایید شده";
              row += `</div>`;
              row += `</td>`;
            }
            
            row += "</tr>";
            setTimeout(() => table.innerHTML += row, 1);
          }
        } else {
          table.innerHTML = `<tr><td colspan='13' class="text-center">موردی یافت نشد.</td></tr>`;
        }
      });
    }
    
    function FetchReport() {
      if (IsFilterActive()) return;
      if (onFetch || (Math.abs(Date.now() - lastTime) / 1000) < 10) return;
      onFetch = true;
      GetReport(null, null);
    }
  
  </script>
</head>
<body onload="OnDocumentLoad()">

<div class="container">
  <div class="row">
    <div class="col-md-6" style="padding:10px;">
      <label for="inputCode" class="sr-only">فیلتر کد ملی</label>
      <input type="text" id="inputCode" oninput="OnChangeCodeMely(this)" class="form-control" placeholder="کد ملی"
             required autofocus>
    </div>
    <div class="col-md-6" style="padding:10px">
      <label for="inputMobile" class="sr-only">موبایل</label>
      <input type="text" id="inputMobile" oninput="OnChangeMobile(this)" class="form-control" placeholder="موبایل"
             required>
    </div>
  </div>
  <table class="table table-bordered" data-toggle="table" style="width:100%!important; height:100%!important;">
    <thead>
    <tr>
      <th class="text-center">شماره</th>
      <th class="text-center">کد</th>
      <th class="text-center">تاریخ ثبت</th>
      <th class="text-center">ساعت ثبت</th>
      <th class="text-center">کد ملی</th>
      <th class="text-center">شماره تماس</th>
      <th class="text-center">نوع بیمه</th>
      <th class="text-center">شرکت بیمه</th>
      <th class="text-center">تاریخ مراجعه</th>
      <th class="text-center">ساعت مراجعه</th>
      <th class="text-center">شماره رهگیری</th>
      <th class="text-center">اس ام اس</th>
      <th class="text-center">وضعیت</th>
    </tr>
    </thead>
    <tbody id="table-content">
    </tbody>
  </table>
</div>

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel" id="exampleModal" dir="ltr">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="gridSystemModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label class="sr-only" for="exampleInput1">تاریخ و زمان</label>
          <div class="input-group">
            <div class="input-group-addon" data-mddatetimepicker="true" data-targetselector="#exampleInput2"
                 data-name="datepicker1"
                 data-englishNumber="true"
                 data-trigger="click" data-enabletimepicker="true"
                 data-isgregorian="false" data-disablebeforetoday="true">
              <span class="glyphicon glyphicon-calendar"></span>
            </div>
            <input type="text" class="form-control" id="exampleInput2" placeholder="تاریخ"/>
          </div>
        </div>
      </div>
      
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">بستن</button>
        <button type="button" class="btn btn-primary" data-dismiss="modal"
                onclick="ButtonAction(0, 'accept-send', $(`[data-name='datepicker1']`).MdPersianDateTimePicker('getValue'))">
          ارسال اس ام اس تایید
        </button>
      </div>
    </div>
  </div>
</div>
</body>
</html>