<input type="hidden" id="tenantno" value="<?= $this->session->userdata('tenant_no') ?>">
<div class="title">學費</div>
<ul class="table-toolbar" style="text-align: left;padding:.3em; display: none;">
    <li class="toolbar-element">
        <i class="fa fa-search"></i><span>搜尋學生:</span>
        
    </li>
    <li class="toolbar-element">
        <input id="name" type="search" class="form-control input-sm search" placeholder="學生中文姓名">
    </li>
    <li class="toolbar-element">
        <input id="studentno" type="search" class="form-control input-sm search" placeholder="學生編號">
    </li>
    <li class="toolbar-element">
        <input id="mobile" type="search" class="form-control input-sm search" placeholder="家長電話">
    </li>
    <li class="toolbar-element">
        <button id="btnFilter" type="button" class="btn btn-primary">確定</button>
    </li>
</ul>
<ul class="table-toolbar" style="text-align: left;padding:.3em;">
    <li class="toolbar-element">
        <i class="fa fa-search"></i><span>搜尋發票:</span>
    </li>
    <li class="toolbar-element">
        <input id="invoiceno" type="search" class="form-control input-sm search" placeholder="發票號碼">
    </li>
    <li class="toolbar-element">
        <button id="btnInvoice" type="button" class="btn btn-primary">確定</button>
    </li>
</ul>

<div id="myTable_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
    <div class="row">
        <div class="col-sm-6"></div>
        <div class="col-sm-6"></div>
    </div>

    <div class="row">
        <div id="invoiceblock" class="col-sm-12">
            <ul class="table-toolbar" style="text-align: left;padding:.3em;">
                <li class="toolbar-element"><span>發票狀態:</span></li>
                <li class="toolbar-element"><select id="drpstatus">
                        <option value="">---</option>
                    </select></li>
            </ul>
            <!--            <p>以下是單張發票：</p>-->
            <table id="invoicetbl" class="display table datatables dataTable" cellspacing="0" role="grid">
                <thead>
                    <tr role="row">
                        <th>發票日期</th>
                        <th>發票編號&nbsp;&nbsp;<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="invoiceformat bi bi-info-circle" viewBox="0 0 16 16">
                                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"></path>
                                <path d="M8.93 6.588l-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"></path>
                            </svg>
                        </th>
                        <th>發票總額</th>
                        <th>尚欠款額</th>
                        <th>學生編號</th>
                        <th>中文姓名</th>
                        <th>課程名稱</th>
                        <th>課堂日期</th>
                        <th>狀態</th>
                        <th>詳情</th>
                        <th>付款</th>
                        <th>列印發票</th>
                        <th>列印收據</th>
                        <th>合併</th>
                    </tr>
                </thead>
                <tbody></tbody>
                <tfoot>
                    <tr>
                        <td colspan="14">
                            <button class="btn btn-footer submit" type="button" id="btnSubmit">確定合併</button>
                        </td>
                    </tr>
                </tfoot>
            </table>
            <div id="ipaging" class="pagingbar"></div>
        </div>

    </div>

    <div class="row">
        <div id="mergedblock" class="col-sm-12">
            <ul class="table-toolbar" style="text-align: left;padding:.3em;">
                <li class="toolbar-element"><span>已合併發票狀態:</span></li>
                <li class="toolbar-element"><select id="drpmergedstatus">
                        <option value="">---</option>
                    </select></li>
            </ul>
            <!--            <p>以下是已合併的發票：</p>-->
            <table id="mergedtbl" class="display table datatables dataTable" cellspacing="0" role="grid">
                <thead>
                    <tr role="row">
                        <th>發票總額</th>
                        <th>尚欠款額</th>
                        <th>狀態</th>
                        <th>詳情</th>
                        <th>付款</th>
                        <th>列印發票</th>
                        <th>列印收據</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <div id="mpaging" class="pagingbar"></div>
        </div>
    </div>
</div>

<div class="modal in" id="modalReceipt" tabindex="-1" role="dialog" aria-labelledby="modalReceiptTitle" aria-hidden="true">
    <div class="modal-lg modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <div class="form-container" style="padding: 0 7px;">
                    <h5 class="modal-title">列印收據</h5>
                    <form id="receiptForm" class="form-horizontal" style="margin-top: 15px;">
                        <div class="row">
                            <div class="col-sm-12" style="text-align: center;"><span>請選擇列印收據 : </span></div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-sm-12" style="text-align: center;"><select id="drpreceipt"></select></div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <a id="btnPrintReceipt" class="btn btn-footer btn-modal-ok">確定</a>
                <a class="btn btn-footer btn-modal-close" data-dismiss="modal">關閉</a>
            </div>
        </div>
    </div>
</div>

<div class="modal in" id="modalInvoice" tabindex="-1" role="dialog" aria-labelledby="modalInvoiceTitle" aria-hidden="true">
    <div class="modal-lg modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <div class="form-container" style="padding: 0 7px;">
                    <h5 class="modal-title">連結孤兒收據給發票</h5>
                    <form id="invoiceForm" class="form-horizontal" style="margin-top: 15px;">
                        <div class="row">
                            <div class="col-sm-12" style="text-align: center;"><span>請選擇要連結的發票 : </span></div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-sm-12" style="text-align: center;"><select id="drpinvoice"></select></div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <a id="btnLinkInvoice" class="btn btn-footer btn-modal-ok">確定</a>
                <a class="btn btn-footer btn-modal-close" data-dismiss="modal">關閉</a>
            </div>
        </div>
    </div>
</div>

<?php include(__DIR__ . '/partials/modal_index_checkout.php'); ?>

<div id='infblk' class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content" style='text-align:center;'>
            <img src='<?= base_url() ?>static/images/invoice_format.png' style='color:transparent;'>
        </div>
    </div>
</div>
<script>
    var invoicestatus = {
        'open': '有效',
        'completed': '已繳清',
        'merged': '已合併',
        'cancelmerged': '取消合併',
        'openaftercancelmerged': '有效(取消合併)',
        'void': '無效'
    };
    var paymentstatus = {
        'pending': '未繳費',
        'paid': '已繳費',
        'partial paid': '欠繳費'
    }
    var paymentstatustranscolor = [{
        id: "未繳費",
        color: "red"
    }, {
        id: "欠繳費",
        color: "green"
    }, {
        id: "已繳費",
        color: "blue"
    }, {
        id: "無效",
        color: "black"
    }];
    var name = '',
        studentno = '',
        mobile = '';
    var selectedno = '',
        selectedstatus = '',
        selectedmergedstatus = '',
        selectedReceiptId = 0;
    var studentlist = [],
        ipaging = [],
        mpaging = [];
    var ids = [];
    var checkall = false;
    var studentId = 0;
    var invoiceId = 0;
    var tenantno = $('#tenantno').val();
    var useselectedno = false;
    var filtering = false;
    var bankinfo = <?= $bankinfo ?? ''; ?>;
    var creditamt = 0;
    var ipage, mpage;

    $(document).ready(function() {
        var li = $('#sidebar-menu li').filter(function(i) {
            return $(this).find('.menu-dropdown').find('.menu-text').text() === '學費';
        });
        li.addClass('active open');

        name = getParameterByName('name') === null ? '' : getParameterByName('name');
        studentno = getParameterByName('studentno') === null ? '' : getParameterByName('studentno');
        mobile = getParameterByName('mobile') === null ? '' : getParameterByName('mobile');

        if (name !== '')
            $('#name').val(name);
        if (studentno !== '')
            $('#studentno').val(studentno);
        if (mobile !== '')
            $('#mobile').val(mobile);
        if (name !== '' || studentno !== '' || mobile !== '') {
            filtershandler(true);
        }

        var mergedId = getParameterByName('mergedId') === null ? '' : getParameterByName('mergedId');
        if (mergedId !== '') {
            getRemoteData('/api/invoicing/getmerged', {
                "id": mergedId
            }, getMergedOk, getRemoteDataFail);
        }

        $("#bankcode").autocomplete({
            source: [bankinfo]
        });
    });

    $(document).on('click', '.invoiceformat', function() {
        $('#infblk').modal({
            show: true
        });
    });
    $(document).on('click', '#btnInvoice', function() {
        if ($('#invoiceno').val() === '') {
            alert('請輸入發票編號!');
            return false;
        }
        $('.table-toolbar:eq(0)').find('li').each(function(i, e) {
            $(e).find('.search').val('');
        });
        $('#invoiceblock').hide();
        getRemoteData(
            "/api/invoicing/getbyinvoiceno", {
                "invoiceno": $('#invoiceno').val()
            },
            getByInvoicenoOk,
            getRemoteDataFail
        );
    });
    $(document).on('click', '#btnFilter', function() {
        filtering = true;
        filtershandler(false);
    });
    $(document).on('click', '#btnSubmit', function() {
        if (confirm('確定要合併這(些)發票?')) {
            // console.log('ids:', ids.join());
            // return false;
            var newForm = $('<form>', {
                'action': '/invoicing/merge',
                'method': 'post',
            }).append($('<input>', {
                'name': 'ids',
                'value': ids.join(),
                'type': 'hidden'
            }));
            $(document.body).append(newForm);
            newForm.submit();
        }
    });
    $(document).on('click', 'td.control-invoice a', function(e) {
        var _this = $(e.currentTarget);
        invoiceId = _this.closest('tr').data('id');
        var url = "/invoicing_invoice/printinvoice?invoiceId=" + invoiceId + '&output=FI&tenant_no=' + tenantno;
        window.open(url, '_blank');
    });
    $(document).on('change', '#drpstatus', function() {
        selectedstatus = $(this).val();
        if (selectedstatus !== '') {
            var _filteredinvoices = $.grep(invoices, function(n, i) {
                return selectedstatus === n.payment_status_trans;
            });
            //        console.log('filteredinvoices@drpstatus:',_filteredinvoices);
            if (_filteredinvoices.length > 0) {
                _genInvoices(_filteredinvoices);
            } else {
                $('#invoicetbl tbody').empty();
                $('#invoicetbl tfoot').hide();
            }
        } else {
            _genInvoices(invoices);
        }
    });
    $(document).on('change', '#drpmergedstatus', function() {
        selectedmergedstatus = $(this).val();
        if (selectedmergedstatus !== '') {
            var _filteredmerged = $.grep(merged, function(n, i) {
                return selectedmergedstatus === n.payment_status_trans;
            });
            //        console.log('filteredinvoices@drpstatus:',_filteredinvoices);
            if (_filteredmerged.length > 0) {
                _genMerged(_filteredmerged);
            } else {
                $('#mergedtbl tbody').empty();
                $('#mergedtbl tfoot').hide();
            }
        } else {
            _genMerged(merged);
        }
    });
    $(document).on('click', '.control-checkout a', function(e) {
        var _this = $(e.currentTarget);
        invoiceId = _this.closest('tr').data('id');
        getRemoteData(
            "/api/invoicing_checkout/checkout_init", {
                "invoiceId": invoiceId
            },
            checkoutInitOk,
            getRemoteDataFail
        );
    });
    $(document).on('change', '.checkbox-invoice', function() {
        var id = $(this).attr('id');
        if (this.checked && ids.indexOf(id) === -1) {
            ids.push(id);
        } else {
            var idx = ids.indexOf(id);
            if (idx > -1) {
                ids.splice(idx, 1);
            }
            checkall = false;
            $('.checkbox-invoice-all').prop('checked', false);
        }
        if (ids.length > 0) {
            $.each(ids, function(i, e) {
                // console.log('e:'+e+';id:'+id);
                if (e === id) {
                    $(this).prop('checked', true);
                }
            });
        }
    });
    $(document).on('change', '.checkbox-invoice-all', function() {
        if (this.checked) {
            $.each(unmerged, function(k, v) {
                ids.push(v.id);
            });
        } else {
            ids = [];
        }
        $('.checkbox-invoice').prop('checked', this.checked);
        //        console.log('ids@checkall:', ids);
        checkall = this.checked;
    });
    $(document).on('click', '.control-receipt a', function(e) {
        var _this = $(e.currentTarget);
        invoiceId = _this.closest('tr').data('id');
        getRemoteData(
            "/api/invoicing/getreceiptsbyinvoice", {
                "invoiceId": invoiceId
            },
            getReceiptsOk,
            getRemoteDataFail
        );
    });

    $(document).on('click', '.paging', function() {
        if ($(this).data('href').split('=')[0].charAt(0) === 'i') {
            ipage = $(this).data('href').split('=')[1];
        } else {
            mpage = $(this).data('href').split('=')[1];
        }
        filtershandler(false);
    });

    function getRemoteData(remote_url, data, callback, callbackFail) {
        $.ajax({
            type: "GET", //提交類型
            url: remote_url, //提交地址
            data: data, //提交內容
            dataType: 'json', //返回數據類型
            success: function(data) { //請求完成並成功
                if (data.success) {
                    if (data.getInvoices || data.getreceipts || data.getmerged || data.checkoutinit || data.checkout || data.linkinvoice || data.getbyinvoiceno || data.getmerged) {
                        callback(data.data);
                    }
                    if (data.getbyselectedno) {
                        callback(data.data, data.student);
                    }
                    if (data.getbystudent) {
                        //data.ipaging,data.istart,data.iend,data.iprevlink,data.inextlink, data.mpaging,data.mstart,data.mend,data.mprevlink,data.mnextlink
                        callback(data.ipaging, data.istart, data.iend, data.iprevlink, data.inextlink, data.mpaging, data.mstart, data.mend, data.mprevlink, data.mnextlink);
                    }
                } else {
                    alert("找不到紀錄");
                }
            },
            error: function(data) { //請求返回錯誤信息
                callbackFail();
            },
            beforeSend: function(XHR) { //请求開始前执行
            },
            complete: function(XHR, status) { //请求完成后最终执行
            }
        });
    }

    function getRemoteDataFail() {
        alert("發生錯誤");
    }

    function getParameterByName(name, url = window.location.href) {
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results)
            return null;
        if (!results[2])
            return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    function getMergedOk(merged) {
        _genMerged(merged);
    }

    function getByInvoicenoOk(invoice) {
        _genInvoices(invoice);
    }

    function filtershandler(_useselectedno) {
        $('.table-toolbar:eq(1)').find('li').each(function(i, e) {
            $(e).find('.search').val('');
        });
        $('#invoiceblock').hide();
        name = $('#name').val().trim();
        studentno = $('#studentno').val().trim();
        mobile = $('#mobile').val().trim();
        if (name === '' && studentno === '' && mobile === '') {
            alert('請輸入最少一項資料以作搜尋');
            return false;
        }

        useselectedno = _useselectedno;
        getRemoteData(
            "/api/invoicing/getbystudent", {
                "name": name,
                "studentno": studentno,
                "mobile": mobile,
                'ipage': ipage,
                'mpage': mpage
            },
            getByStudentOk,
            getRemoteDataFail
        );
    }

    function _genInvoices(filteredinvoices, istart, iend, iprevlink, inextlink) {
        if (typeof filteredinvoices !== 'undefined') {
            let invoicebody = $('#invoicetbl tbody');
            $('#invoiceblock').show();
            invoicebody.empty();
            var status = ['未繳費', '欠繳費', '已繳費', '無效'];
            $('#drpstatus').empty().append('<option value="">---</option>');
            $.each(status, function(k, v) {
                var selected = selectedstatus === v ? ' selected' : '';
                $('#drpstatus').append('<option value="' + v + '"' + selected + '>' + v + '</option>');
            });
            var html = '';
            if (filteredinvoices.length >= 1) {
                $.each(filteredinvoices, function(k, v) {
                    html += _geninvoicerow(v);
                });
            } else {
                html += _geninvoicerow(filteredinvoices);
            }
            invoicebody.append(html);
            $('#invoicetbl tfoot').show();
            // console.log('inextlink:'+inextlink);
            // console.log(iprevlink.slice(0,2)+';'+inextlink.slice(0,2));
            if (iprevlink.slice(0, 2) === '<s' && inextlink.slice(0, 2) === '<s') {
                $('#ipaging').empty();
            } else {
                $('#ipaging').html(iprevlink + '&nbsp;&nbsp;' + inextlink);
            }
        }
    }

    function _genMerged(merged, mstart, mend, mprevlink, mnextlink) {
        if (typeof merged !== 'undefined') {
            $('#mergedblock').show();
            let mbody = $('#mergedtbl tbody');
            mbody.empty();
            var status = ['未繳費', '欠繳費', '已繳費', '無效'];
            $('#drpmergedstatus').empty().append('<option value="">---</option>');
            $.each(status, function(k, v) {
                var selected = selectedmergedstatus === v ? ' selected' : '';
                $('#drpmergedstatus').append('<option value="' + v + '"' + selected + '>' + v + '</option>');
            });
            var html = '';
            if (merged.length >= 1) {
                $.each(merged, function(k, v) {
                    html += _genmergedrow(v);
                });
            } else {
                html += _genmergedrow(merged);
            }
            mbody.append(html);
            if (typeof mprevlink !== 'undefined' && typeof mnextlink !== 'undefined') {
                if (mprevlink.slice(0, 2) === '<s' && mnextlink.slice(0, 2) === '<s') {
                    $('#mpaging').empty();
                } else {
                    $('#mpaging').html(mprevlink + '&nbsp;&nbsp;' + mnextlink);
                }
            }
        }
    }

    function _genmergedrow(v) {
        var html = '';
        var invoicefile = '<a class="icon-circle" href="javascript:void(0);"><i class="fa fa-file-text-o"></i></a>';
        var receiptfile = '<a class="icon-circle" href="javascript:void(0);"><i class="fa fa-files-o"></i></a>';
        html += '<tr data-id="' + v.invoiceId + '" role="row">';
        html += '<td>' + v.amount_to_pay + '</td><td>' + v.net_amount_payable + '</td>';
        var icls = $.grep(paymentstatustranscolor, function(n, i) {
            //            console.log('n.id:' + n.id + ';v.trans:' + v.payment_status_trans);
            return n.id === v.payment_status_trans;
        });
        html += '<td><span class="' + icls[0].color + '">' + v.payment_status_trans + '</span></td><td class="control-details">' + v.details + '</td>';
        if (v.payment_status !== 'paid') {
            html += '<td class=" control-checkout"><a class="icon-circle" href="#"><i class="fa fa-dollar"></i></a></td>';
        } else {
            html += '<td class=" control-checkout">--</td>';
        }
        html += '<td class=" control-invoice">' + invoicefile + '</td>';
        html += '<td class=" control-receipt">' + receiptfile + '</td>';
        html += '</tr>';
        return html;
    }

    function _geninvoicerow(v) {
        var html = '';
        var invoicefile = '<a class="icon-circle" href="javascript:void(0);"><i class="fa fa-file-text-o"></i></a>';
        var receiptfile = '<a class="icon-circle" href="javascript:void(0);"><i class="fa fa-files-o"></i></a>';
        html += '<tr data-id="' + v.invoiceId + '" role="row">';
        html += '<td>' + v.issued_date + '</td><td>' + v.issued_name + '</td><td>' + v.amount_to_pay + '</td><td>' + v.net_amount_payable + '</td>';
        html += '<td>' + v.studentno + '</td><td>' + v.chi_name + '</td><td>' + v.course_name + '</td><td>' + v.date_range + '</td>';
        var icls = $.grep(paymentstatustranscolor, function(n, i) {
            //            console.log('n.id:'+n.id+';trans:'+v.payment_status_trans);
            return n.id === v.payment_status_trans;
        });
        html += '<td><span class="' + icls[0].color + '">' + v.payment_status_trans + '</span></td><td class="control-details">' + v.details + '</td>';
        if (v.payment_status !== 'paid') {
            html += '<td class=" control-checkout"><a class="icon-circle" href="#"><i class="fa fa-dollar"></i></a></td>';
        } else {
            html += '<td class=" control-checkout">--</td>';
        }
        html += '<td class=" control-invoice">' + invoicefile + '</td>';
        html += '<td class=" control-receipt">' + receiptfile + '</td>';
        var disabled = '';
        if (v.payment_status_trans === paymentstatus.paid || v.payment_status_trans === paymentstatus.void || v.invoice_status_trans === invoicestatus.merged) {
            disabled = 'disabled';
        }
        html += '<td><input type="checkbox" class="checkbox-invoice" id="' + v.invoiceId + '" ' + disabled + '></td>';
        html += '</tr>';
        return html;
    }

    function getByStudentOk(_ipaging, istart, iend, iprevlink, inextlink, _mpaging, mstart, mend, mprevlink, mnextlink) {
        // console.log('ipaging:', _ipaging);
        // console.log('mpaging:', _mpaging);
        if (_ipaging.length > 0) {
            ipaging = _ipaging.slice();
            _genInvoices(ipaging, istart, iend, iprevlink, inextlink);
        }
        if (_mpaging.length > 0) {
            mpaging = _mpaging.slice();
            _genMerged(mpaging, mstart, mend, mprevlink, mnextlink);
        }

        if (_ipaging.length === 0 && _mpaging.length === 0) {
            alert('查無此學生資料');
        }

        if (ids.length > 0) {
            $('.checkbox-invoice').each(function(idx, ele) {
                let chkin = $(ele);
                $.each(ids, function(i, e) {
                    // console.log('id:'+e+';chkid:'+$(ele).attr('id'));
                    if (chkin.attr('id') === e) {
                        chkin.prop('checked', true);
                    }
                });
            });
        }
    }

    function checkoutInitOk(data) {
        const payment = data.paymentForm;
        const modalcheckout = $('#modal-checkout');
        if (data.cannotPay) {
            modalcheckout.find('.btn-modal-ok').addClass('hide');
        } else {
            modalcheckout.find('.btn-modal-ok').removeClass('hide');
        }
        const form = $('#paymentForm');
        form.find('[name="net_amount_payable"]').text(payment.net_amount_payable);
        form.find('[name="creditstxt"]').text(payment.creditstxt);
        form.find('[name="credits"]').val(payment.credits);
        if (payment.credits > 0) {
            form.find('#usecreditblk').show().find('#use_credits').val(payment.credits);
        } else {
            form.find('#usecreditblk').hide();
        }
        creditamt = payment.credits;
        let paymentTypeOptions = [];
        $.each(payment.payment_type_id, (key, value) => {
            if (key <= 2) { //remove cheque+cash & paypal
                paymentTypeOptions.push(`<option value="${key}">${value}</option>`);
            }
        });
        form.find('[name="payment_type_id"]').empty().append(paymentTypeOptions.join(''));
        form.find('[name="payment_type_id"]').select2();
        form.find('[name="cash_amount"]').val(payment.cash_amount);
        form.find('[name="cheque_amount"]').val(payment.cheque_amount);
        form.find('[name="cheque_no"]').val(payment.cheque_no);
        form.find('[name="bankcode"]').val(payment.bankcode);

        paymentModal(invoiceId);
    }

    function validpayform() {
        var msg = '';
        var paymentTypeId = parseInt($('#payment_type_id').val());
        var cashamt = $('#cash_amount').val();
        var cheqamt = $('#cheque_amount').val();
        var cheqbank = $('#bankcode').val().trim().substr(0, 3);
        if (creditamt > 0) {
            const usecredits = parseInt($('#use_credits').val());
            if (usecredits > creditamt) {
                msg += "使用盈餘不得大於盈餘本身!\r\n";
            }
            if (usecredits < 0) {
                msg += "請輸入正確的使用盈餘數額!\r\n";
            }
        } else {
            if (paymentTypeId === 1) {
                if (cashamt === '' || parseInt(cashamt) <= 0) {
                    msg += "請輸入現金款項\n";
                } else if (isNaN(cashamt)) {
                    msg += "請輸入正確的現金款項\n";
                }
            } else {
                if (cheqamt === '' || parseInt(cheqamt) <= 0) {
                    msg += "請輸入支票款項\n";
                } else if (isNaN(cheqamt)) {
                    msg += "請輸入正確的支票款項\n";
                }
                var found = false;
                for (var i = 0; i < bankinfo.length; i++) {
                    if (cheqbank === bankinfo[i].substr(0, 3)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    msg += "請輸入正確的銀行編號\n";
                }
            }
        }
        if (msg !== '') {
            alert(msg);
        }
        return msg === '';
    }

    function checkoutOk(data) {
        alert('付款成功!');
        window.location.href = '/invoicing?name=' + name + '&studentno=' + studentno + '&mobile=' + mobile + '&selectedno=' + selectedno;
    }

    function paymentModal(invoiceId) {
        var modalPayment = $('#modal-checkout');
        modalPayment.modal('show');
        var paymentTypeId = $('select[name="payment_type_id"]');
        var initedVal = paymentTypeId.find('option:selected').val();
        paymentTypeId.change(e => {
            const _this = $(e.currentTarget);
            paymentTypeHandler(_this.find('option:selected').val());
        })
        paymentTypeHandler(initedVal);
        modalPayment.find('.btn-modal-ok').click(function(e) {
            if (validpayform()) {
                // return false;
                getRemoteData(
                    "/api/invoicing_checkout/checkout", {
                        "invoiceId": invoiceId,
                        "remark": $('#remark').val().trim(),
                        "internal_remark": $('#internal_remark').val().trim(),
                        "payment_type_id": $('#payment_type_id').val().trim(),
                        "cash_amount": $('#cash_amount').val().trim(),
                        "cheque_amount": $('#cheque_amount').val().trim(),
                        "cheque_bank_name": $('#bankcode').val().trim().substr(0, 3),
                        "cheque_no": $('#cheque_no').val().trim(),
                        "studentId": studentId,
                        "use_credits": $('#use_credits').val().trim()
                    },
                    checkoutOk,
                    getRemoteDataFail
                );
            }
        });
        modalPayment.on('hidden.bs.modal', function() {
            modalPayment.find('.btn-modal-ok').off('click');
        });
    }

    const paymentTypeHandler = val => {
        console.log(val);
        switch (parseInt(val)) {
            case 1:
                editable('#paymentForm', 'cash_amount');
                readonly('#paymentForm', 'cheque_amount', true);
                // readonly('#paymentForm', 'cheque_bank_name', true);
                readonly('#paymentForm', 'cheque_no', true);
                readonly('#paymentForm', 'bankcode', true);
                break;
            case 2:
                editable('#paymentForm', 'cheque_amount');
                // editable('#paymentForm', 'cheque_bank_name');
                editable('#paymentForm', 'cheque_no');
                editable('#paymentForm', 'bankcode');
                readonly('#paymentForm', 'cash_amount', true);
                break;
            case 3:
                editable('#paymentForm', 'cash_amount');
                editable('#paymentForm', 'cheque_amount');
                // editable('#paymentForm', 'cheque_bank_name');
                editable('#paymentForm', 'bankcode');
                editable('#paymentForm', 'cheque_no');
                break;
            default:
                break;
        }
        $('#payment_type_id').closest('.form-group').removeAttr('readonly').removeAttr('disabled').find('.overlay').remove();
    }

    const readonly = (form, elementName, disabled = false) => {
        const formgroup = $(form).find(`[name="${elementName}"]`).closest('.form-group');
        formgroup.attr('readonly', true).prepend('<div class="overlay"></div>');

        if (disabled === true) {
            formgroup.attr('disabled', true);
        }
    }

    const editable = (form, elementName) => {
        const formgroup = $(form).find(`[name="${elementName}"]`).closest('.form-group');
        formgroup.removeAttr('readonly').removeAttr('disabled');
        formgroup.find('.overlay').remove();
    }

    function getReceiptsOk(receipts) {
        //        console.log('receipts:', receipts);
        if (receipts.length === 0) {
            alert('先付款，後收據。');
            return false;
        }
        var modalReceipt = $('#modalReceipt');
        var drpreceipt = modalReceipt.find('#drpreceipt');
        drpreceipt.empty();
        drpreceipt.append('<option value="---">---</option>');
        $.each(receipts, function(k, v) {
            drpreceipt.find('option:first').after('<option value="' + v.id + '">' + v.issued_name + '</option>');
        });
        modalReceipt.modal('show');
        modalReceipt.find('#btnPrintReceipt').on('click', function() {
            if (drpreceipt.val() === '---') {
                alert('請選擇要列印的收據');
                return false;
            }

            var url = "/invoicing_receipt/printreceipt?receiptId=" + drpreceipt.val() + '&output=FI&tenant_no=' + tenantno;
            //            console.log('url:',url);///invoicing_receipt/printreceipt?receiptId=32&output=FI&tenant_no=main
            //            return false;
            window.open(url, '_blank');
        });
        modalReceipt.on('hidden.bs.modal', function() {
            modalReceipt.find('.btn-modal-ok').off('click');
        });
    }

    function getUnpaidoutInvoicesOk(invoices) {
        var modalInvoice = $('#modalInvoice');
        var drpinvoice = modalInvoice.find('#drpinvoice');
        drpinvoice.empty();
        drpinvoice.append('<option value="---">---</option>');
        $.each(invoices, function(k, v) {
            drpinvoice.find('option:first').after('<option value="' + v.id + '">' + v.issued_name + '</option>');
        });
        modalInvoice.modal('show');
        modalInvoice.find('#btnLinkInvoice').on('click', function() {
            if (drpinvoice.val() === '---') {
                alert('請選擇要連結的發票');
                return false;
            }
            //            console.log('invoiceid:'+drpinvoice.val()+';selectedreceiptid:'+selectedReceiptId);//2;1
            //            return false;
            getRemoteData('/api/invoicing/linkinvoice', {
                "invoiceId": drpinvoice.val(),
                "receiptId": selectedReceiptId
            }, linkInvoiceOk, getRemoteDataFail);
        });
        modalInvoice.on('hidden.bs.modal', function() {
            modalInvoice.find('.btn-modal-ok').off('click');
        });
    }

    function linkInvoiceOk(data) {
        if (data) {
            alert('已成功將該收據連結至所選發票!');
            window.location.reload();
        } else {
            alert('發票金額少於收據金額，不能連結!');
        }
    }

    function formatMoney(number, decPlaces, decSep, thouSep) {
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
            decSep = typeof decSep === "undefined" ? "." : decSep;
        thouSep = typeof thouSep === "undefined" ? "," : thouSep;
        var sign = number < 0 ? "-" : "";
        var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));
        var j = (j = i.length) > 3 ? j % 3 : 0;

        return sign +
            (j ? i.substr(0, j) + thouSep : "") +
            i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) +
            (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");
    }
</script>