<?php

use app\libraries\CommonHelper;

function __payment_status($status)
{
	return [
			'pending' => [
					'class' => 'red',
					'text' => '未繳費',
			],
//        'ready' => [
//            'class' => 'red',
//            'text' => '未繳費',
//        ],
//        'open' => [
//            'class' => 'red',
//            'text' => '未繳費',
//        ],
			'partial paid' => [
					'class' => 'green',
					'text' => '欠繳費',
			],
			'paid' => [
					'class' => 'blue',
					'text' => '已繳費',
			],
			'void' => [
					'class' => 'black',
					'text' => '無效',
			],
//        'merged'=>['class'=>'yellow','text'=>'已合併'],
	][$status];
}

?>
<style>
	.tblreceiptitems, .tblreceiptitems th, .tblreceiptitems td {
		border: 1px solid #999;
		padding: .2em;
	}

	.red {
		color: red;
	}

	.green {
		color: green;
	}

	.blue {
		color: blue;
	}

	.black {
		color: black;
	}
</style>
<div class="title">學費詳情</div>
<?php if (isset($__alert_success_message)) : ?>
	<div class="alert alert-success" role="alert" style="text-align: left;"><?php echo $__alert_success_message; ?>
		<button type="button" class="close" data-dismiss="alert" aria-label="Close"><a aria-hidden="true">×</a></button>
	</div>
<?php endif; ?>
<ul class="table-toolbar" style="text-align: left;">
	<li><a id="btnBack" class="toolbar-element btn btn-default btn-create" href="/invoicing"><i class="fa fa-reply"
																								style="margin-right: 8px;"></i>返回</a>
	</li>
</ul>
<div class="form-container">
	<form id="form" class="form-horizontal" role="form" method="post" action="/invoicing">
		<ul class="nav nav-tabs" id="invoicing-info-tab" role="tablist">
			<li class="nav-item active">
				<a class="nav-link active" id="invoicing-info-tab" data-toggle="tab" href="#invoicing-info" role="tab"
				   aria-controls="invoicing-info" aria-selected="true" aria-expanded="true">基本資料</a>
			</li>
			<li></li>
		</ul>
		<div class="tab-content" id="invoicing-info-tab-content">
			<div class="tab-pane fade active in" id="invoicing-info" role="tabpanel"
				 aria-labelledby="invoicing-info-tab">
				<?php if (isset($merged) && !$merged): ?>
					<div class="form-group mas-col2">
						<div class="col-sm-3 text-center mas-title2"><label for="issued_date">發票日期</label></div>
						<div class="col-sm-9 mas-box"><label class="mas-text"><span class="text block"
																					name="issued_date"><?php echo $issued_date ?? ''; ?></span></label>
						</div>
					</div>
				<?php endif; ?>
				<?php if (!empty($items)): ?>
					<?php foreach ($items as $item) : ?>
						<fieldset>
							<div class="form-group mas-col">
								<div class="col-sm-3 text-center mas-title"><label for="item_name">課程名稱</label></div>
								<div class="col-sm-9 mas-box"><input type="text" readonly
																	 style="width:100%;background-color:#ddf0f4;"
																	 value="<?php echo $item['item_name']; ?>"></div>
							</div>
							<div class="form-group mas-col">
								<div class="col-sm-3 text-center mas-title"><label for="chi_name">學生名稱</label></div>
								<div class="col-sm-9 mas-box"><label class="mas-text"><span class="text block"
																							name="chi_name"><?php echo $item['chi_name']; ?></span></label>
								</div>
							</div>
							<div class="form-group mas-col">
								<div class="col-sm-3 text-center mas-title"><label for="item_timeslot">課堂日期和時間</label>
								</div>
								<div class="col-sm-9 mas-box"
									 style="padding:6px 20px;background-color:#ddf0f4;min-height:<?= $item['slotheight'] ?>em">
									<table style="max-width:62%;">
										<?php foreach ($item['item_timeslot'] as $t): ?>
											<tr>
												<td><?= $t ?>,</td>
												<td><?= $t ?></td>
											</tr>
										<?php endforeach; ?>
									</table>
								</div>
							</div>
							<div class="form-group mas-col">
								<div class="col-sm-3 text-center mas-title"><label for="amount">學費款額</label></div>
								<div class="col-sm-9 mas-box"><input type="text" readonly
																	 style="width:100%;background-color:#ddf0f4;"
																	 value="<?php echo $item['amount']; ?>"></div>
							</div>
							<?php
							$extra = '';
							if (empty($item['extra'])) {
								$extra = CommonHelper::money(0);
							} else {
								foreach ($item['extra'] as $e) {
									$extra .= $e['name'] . '：' . CommonHelper::money($e['amount']) . "\r\n";
								}
							}
							?>
							<div class="form-group mas-col">
								<div class="col-sm-3 text-center mas-title"><label for="amount">額外款額</label></div>
								<div class="col-sm-9 mas-box">
									<textarea class="form-control mas-textarea" readonly
											  style="background-color:#ddf0f4;min-height:4.2em;"><?= $extra ?>
									</textarea>
								</div>
							</div>
							<div class="form-group mas-col">
								<div class="col-sm-3 text-center mas-title"><label for="amount">盈餘總額</label></div>
								<div class="col-sm-9 mas-box"><input type="text" readonly
																	 style="width:100%;background-color:#ddf0f4;"
																	 value="<?php echo $item['creditstxt']; ?>"></div>
							</div>
							<?php //if (isset($openaftercancelmerged) && !$openaftercancelmerged): ?>
								<div class="form-group mas-col">
									<div class="col-sm-3 text-center mas-title"><label for="amount_paid">已繳款額</label>
									</div>
									<div class="col-sm-9 mas-box">
										<?php
										$summary = '';
										$userId = $item['user_id'];
										$cashpayment = 0;
										$chequepayment = 0;
										$atmpayment = 0;
										$height = 1.4;
										if (!empty($receipt_items)) {
											if (isset($isinvoiceinmerge) && $isinvoiceinmerge) {
												foreach ($receipt_items as $ritem) {
													if ($ritem['user_id'] == $userId) {
														$cashpayment = floatval($ritem['cash_amount']);
														$chequepayment = floatval($ritem['cheque_amount']);
														$atmpayment = floatval($ritem['atm_amount']);
													}
												}

												if ($cashpayment > 0) {
													$summary .= "\n現金付款共：" . CommonHelper::money($cashpayment);
													$height += 1.4;
												}
												if ($chequepayment > 0) {
													$summary .= "\n支票付款共：" . CommonHelper::money($chequepayment);
													$height += 1.4;
												}
												if ($atmpayment > 0) {
													$summary .= "\n入數紙付款共：" . CommonHelper::money($atmpayment);
													$height += 1.4;
												}
												if ($summary !== '') {
													$summary .= "\n合共付款：" . CommonHelper::money($cashpayment + $chequepayment + $atmpayment);
													$height += 1.4;
												} else {
													$summary = '$ 0.00';
												}
											} else {
												foreach ($receipt_items as $ritem) {
													if ($ritem['user_id'] == $userId) {
														$cashpayment += floatval($ritem['cash_amount']);
														$chequepayment += floatval($ritem['cheque_amount']);
														$atmpayment += floatval($ritem['atm_amount']);
													}
												}

												if ($cashpayment > 0) {
													$summary .= "\n現金付款共：" . CommonHelper::money($cashpayment);
													$height += 1.4;
												}
												if ($chequepayment > 0) {
													$summary .= "\n支票付款共：" . CommonHelper::money($chequepayment);
													$height += 1.4;
												}
												if ($atmpayment > 0) {
													$summary .= "\n入數紙付款共：" . CommonHelper::money($atmpayment);
													$height += 1.4;
												}
												if ($summary !== '') {
													$summary .= "\n合共付款：" . CommonHelper::money($cashpayment + $chequepayment + $atmpayment);
													$height += 1.4;
												} else {
													$summary = '$ 0.00';
												}
											}
										} else {
											if (isset($canshowpaybtn) && !$canshowpaybtn && isset($amount_paid)) {
												$summary = $amount_paid;
											} else {
												$summary = '$ 0.00';
											}
										}
										?>
										<textarea class="form-control mas-textarea" readonly
												  style="background-color:#ddf0f4;min-height:<?= $height ?>em;"><?= $summary ?></textarea>
									</div>
								</div>
								<?php if (!empty($allreceiptitemdetail)):
									$allitemhtml = '<table class="tblreceiptitems"><thead><tr><th>付款類別</th><th>金額</th><th>時間</th>';
									if (isset($canshowvoidbtn) && $canshowvoidbtn) {
										$allitemhtml .= '<th></th>';
									}
									$allitemhtml .= '</tr></thead><tbody>';
									foreach ($allreceiptitemdetail as $ri) {
										if ($ri['user_id'] == $userId) {
											if ($ri['payment_type_id'] == PaymentType::Cash) {
												$allitemhtml .= '<tr><td>現金</td><td>' . $ri['cash_amount'] . ' </td><td>' . $ri['payment_date'] . '</td>';
											}
											if ($ri['payment_type_id'] == PaymentType::ATM) {
												$allitemhtml .= '<tr><td>入數紙</td><td>' . $ri['atm_amount'] . '</td><td>' . $ri['payment_date'] . '</td>';
											}
											if ($ri['payment_type_id'] == PaymentType::Cheque) {
												$allitemhtml .= '<tr><td><p>支票<br>號碼：' . $ri['cheque_no'] . '<br>銀行：' . $ri['cheque_bank_name'] . '</p></td><td>' . $ri['cheque_amount'] . '</td><td>' . $ri['payment_date'] . '</td>';
											}
											if (isset($canshowvoidbtn) && $canshowvoidbtn) {
												$allitemhtml .= '<td><a class="action-btn receiptvoid" href="javascript:void(0);" data-id="' . $ri['id'] . '">廢止</a></td>';
											}
											$allitemhtml .= '</tr>';
										}
									}
									$allitemhtml .= "</tbody></table>";
									?>

									<div class="form-group mas-col">
										<div class="col-sm-3 text-center mas-title"><label for="amount">繳款明細</label>
										</div>
										<div class="col-sm-9 mas-box"
											 style="padding:6px 20px;"><?php echo $allitemhtml; ?>
										</div>
									</div>
								<?php endif; ?>
							<?php //endif; ?>
						</fieldset>
					<?php endforeach; ?>
				<?php endif; ?>

				<div class="form-group mas-col2">
					<div class="col-sm-3 text-center mas-title2"><label for="amount_paid">已繳款額</label></div>
					<div class="col-sm-9 mas-box"><label class="mas-text"><span id="amount_paid" class="text block"
																				name="amount_paid"><?php echo $amount_paid ?? 0; ?></span></label>
					</div>
				</div>
				<div class="form-group mas-col2">
					<div class="col-sm-3 text-center mas-title2"><label for="net_amount_payable">尚欠款額</label></div>
					<div class="col-sm-9 mas-box"><label class="mas-text"><span class="text block"
																				name="net_amount_payable"><?php echo $net_amount_payable ?? 0; ?></span></label>
					</div>
				</div>
				<?php $status = __payment_status($payment_status ?? ''); ?>
				<div class="form-group mas-col2">
					<div class="col-sm-3 text-center mas-title2"><label for="payment_status">狀態</label></div>
					<div class="col-sm-9 mas-box"><label class="mas-text"><span id="payment_status"
																				class="text block <?php echo $status['class']; ?>"
																				name="payment_status"><?php echo $status['text']; ?></span></label>
					</div>
				</div>
				<?php if (!$merged): ?>
					<div class="form-group mas-col2">
						<div class="col-sm-3 text-center mas-title2"><label for="teacher_name">教師</label></div>
						<div class="col-sm-9 mas-box"><label class="mas-text"><span class="text block"
																					name="teacher_name"><?php echo $teacher_name ?? ''; ?></span></label>
						</div>
					</div>
					<div class="form-group mas-col2">
						<div class="col-sm-3 text-center mas-title2"><label for="room_name">課室</label></div>
						<div class="col-sm-9 mas-box"><label class="mas-text"><span class="text block"
																					name="room_name"><?php echo $room_name ?? ''; ?></span></label>
						</div>
					</div>
				<?php endif; ?>
				<?php if (isset($canshowpaybtn) && $canshowpaybtn): ?>
					<div class="form-group mas-col2">
						<div class="col-sm-3 text-center mas-title2"><label for="checkout">付款</label></div>
						<div class="col-sm-9 mas-box"><label class="mas-text"><span class="text block"
																					name="checkout"><a
											class="action-btn control-checkout" href="#">付款</a></span></label></div>
					</div>
				<?php endif; ?>
				<div class="form-group mas-col2">
					<div class="col-sm-3 text-center mas-title2"><label for="invoice">發票</label></div>
					<div class="col-sm-9 mas-box">
						<label class="mas-text">
                            <span class="text block" name="invoice">
                                <a class="action-btn control-invoice" href="javascript:void(0);" target="_blank">發票</a>
                            </span></label></div>
				</div>
				<div class="form-group mas-col2">
					<div class="col-sm-3 text-center mas-title2"><label for="receipt">收據</label></div>
					<div class="col-sm-9 mas-box"><label class="mas-text"><span class="text block" name="receipt"><a
										class="action-btn control-receipt"
										href="javascript:void(0);">收據</a></span></label></div>
				</div>

					<div class="form-group mas-col2">
						<div class="col-sm-3 text-center mas-title2"><label for="void">廢止</label></div>

						<div class="col-sm-9 mas-box">

							<label class="mas-text">
								<?php if (isset($canshowvoidbtn) && $canshowvoidbtn) : ?>
								<span class="text block" name="void">
									<a class="action-btn control-void"
											href="javascript:void(0);">廢止</a></span>
								<?php else:?>
									<span class="text block">未曾繳費或曾使用盈餘，不能廢止。</span>
								<?php endif; ?>
							</label>
						</div>

					</div>

				<?php if ($merged): ?>
					<div class="form-group mas-col2">
						<div class="col-sm-3 text-center mas-title2"><label for="unmerge">取消合併</label></div>
						<div class="col-sm-9 mas-box"><label class="mas-text"><span class="text block" name="unmerge"><a
											class="action-btn control-unmerge"
											href="javascript:void(0);">取消合併</a></span></label></div>
					</div>
				<?php endif; ?>
			</div>
		</div>
	</form>
</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>

<?php include(__DIR__ . '/partials/modal_index_checkout.php'); ?>
<?php include(__DIR__ . '/partials/invoicevoidmodal.php'); ?>
<script>
	let vm = 0;
	let voidmode = {"invoice": 'invoice', "receiptitem": 'receiptitem'};
	let receiptitemId = 0;
	const invoiceId = "<?php echo $id ?? 0; ?>";
	var tenantno = '<?= $this->session->userdata('tenant_no') ?>';
	var bankinfo = <?=$bankinfo ?? '';?>;
	var creditamt = 0;
	$(document).on('click', '#btnRefund', function (e) {
		e.preventDefault();
		var params = {};
		params.id = vm === voidmode.invoice ? invoiceId : receiptitemId;
		params.mode = vm;
		params.invoiceId = invoiceId;
		if (confirm('確定要退款?')) {
			getRemoteData('/api/Invoicing/refund', params, refundOk, getRemoteDataFail);
		}
	});
	$(document).on('click', '#btnTransfer', function (e) {
		e.preventDefault();
		var params = {};
		params.id = vm === voidmode.invoice ? invoiceId : receiptitemId;
		params.mode = vm;
		getRemoteData('/api/Invoicing/getusers', params, getUsersOk, getRemoteDataFail);
	});
	$(document).on('click', '#btnTransferConfirm', function (e) {
		e.preventDefault();
		var params = {};
		params.id = vm === voidmode.invoice ? invoiceId : receiptitemId;
		params.mode = vm;
		params.studentId = $('#drpusers').val();
		params.invoiceId = invoiceId;
		getRemoteData('/api/Invoicing/transfer', params, transferOk, getRemoteDataFail);
	});

	function transferOk(data) {
		var msg = vm === voidmode.invoice ? '已將全部餘款轉移至指定帳戶。' : '已將餘款轉移至指定帳戶。';
		alert(msg);
		window.location.href = '/invoicing';
	}

	function getUsersOk(users, defaultuser) {
		$.each(users, function (k, v) {
			$('#drpusers').append('<option value="' + v.id + '">' + v.chi_name + '</option>');
		});
		$('#drpusers').val(defaultuser);
		$('.transfer').show();
	}

	function refundOk(data) {
		alert('已儲存退款至系統。');
		// if (vm === voidmode.invoice)
		window.location.href = '/invoicing';
		// else window.location.reload(true);
	}

	function getRemoteData(remote_url, data, callback, callbackFail) {
		$.ajax({
			//async: false,
			//timeout: 30000, //最長等候回應時間
			type: "GET", //提交類型
			url: remote_url, //提交地址
			data: data, //提交內容
			dataType: 'json', //返回數據類型
			success: function (data) { //請求完成並成功
				if (data.success) {
					if (data.getusers)
						callback(data.users, data.defaultuser);
					else
						callback(data.data);
				} else {
					callbackFail();
				}
			},
			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, ' '));
	}

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

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

		$('.transfer').hide();
	})

	$(document).on('click', '.control-invoice', function () {
		var url = "/invoicing_invoice/printinvoice?invoiceId=" + invoiceId + '&output=FI&tenant_no=' + tenantno;
		window.open(url, '_blank');
	});

	$(document).on('click', '.control-void', function () {
		vm = voidmode.invoice;
		$('#btnTransfer').text('轉移全部已繳款額');
		var modalVoid = $('#modalVoid');
		modalVoid.modal('show');
	});

	$(document).on('click', '.control-receipt', function () {
		getRemoteData(
				"/api/invoicing/getreceiptsbyinvoice",
				{"invoiceId": invoiceId},
				getReceiptsOk,
				getRemoteDataFail
		);
	});

	$(document).on('click', '.receiptvoid', function () {
		vm = voidmode.receiptitem;
		receiptitemId = $(this).data('id');
		$('#btnTransfer').text('轉移已繳款額');
		var modalVoid = $('#modalVoid');
		modalVoid.modal('show');
	});

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

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

	const select = (inputName, $this = null) => {
		const name = 'select[name="' + inputName + '"]';
		return $this ? $(name, $this) : $(name);
	}

	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 paymentModal = invoiceId => {
		const modalPayment = $('#modal-checkout');

		modalPayment.modal('show');

		const paymentTypeId = $('select[name="payment_type_id"]');
		const 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(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');
		});
	}

	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.reload();
	}

	$('.control-checkout').click(e => {
		const _this = $(e.currentTarget);
		$.ajax({
			//async: false,
			//timeout: 30000, //最長等候回應時間
			type: "GET", //提交類型
			url: '/api/invoicing_checkout/checkout_init', //提交地址
			data: {"invoiceId": invoiceId},
			dataType: 'json', //返回數據類型
			success: function (data) { //請求完成並成功
				const payment = data.data.paymentForm;
				const modalcheckout = $('#modal-checkout');
				if (data.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);
			},
			error: function (data) { //請求返回錯誤信息
			},
			beforeSend: function (XHR) { //请求開始前执行
			},
			complete: function (XHR, status) { //请求完成后最终执行
			}
		});
	});

	$(document).on('click', '.control-unmerge', function () {
		if (confirm('確定要取消合併發票?')) {
			getRemoteData('/api/invoicing/unmerge', {"id": invoiceId}, unmergeOk, getRemoteDataFail);
		}
	});

	function unmergeOk(data) {
		alert('已成功取消合併發票!');
		window.location.href = '/invoicing';
	}
</script>
