@extends('views.layouts.master')
<link rel="stylesheet" href="{{ csset('/themes/pro/modunawa/resources/css/checkout.css') }}">
@section('content')

<!--=====================================
                    BANNER PART START
        =======================================-->
        <section class="inner-section single-banner">
            <div class="container">
                <h2>결제하기</h2>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="/">Home</a></li>
                    <!--<li class="breadcrumb-item"><a href="shop-4column.html">shop grid</a></li>-->
                    <li class="breadcrumb-item active" aria-current="page">결제하기</li>
                </ol>
            </div>
        </section>
        <!--=====================================
                    BANNER PART END
        =======================================-->


        <!--=====================================
                    CHECKOUT PART START
        =======================================-->
        <section class="inner-section checkout-part">
            <form class="container" id="checkout-form" action="{{ route('checkout.store') }}" method="POST">
                <input type="hidden" name="ship_fee" value="{{ $checkoutCharge['charge_amt'] }}">
                @csrf
                <div class="row">
                    <!--
					<div class="col-lg-12">
                        <div class="alert-info">
                            <p>Returning customer? <a href="login.html">Click here to login</a></p>
                        </div>
                    </div>
					-->
                    <div class="col-lg-12 order">
                        <div class="account-card">
                            <div class="account-title">
                                <h4>Your order</h4>
                            </div>
                            <div class="account-content">
                                <div class="table-scroll table-responsive">
                                    <table class="table-list" id="cart-table">
                                        <thead>
                                            <tr>
                                                <th scope="col">
                                                    <input type="checkbox" class="all-check" tabindex="-1" onchange="change_cart_all_checkbox(this)"
                                                           onclick="checkbox_all_checked(this, 'bd-cud-check')" @if ($allCartChecked) checked @endif>
                                                </th>
                                                <th scope="col">Serial</th>
                                                <th scope="col">Product</th>
                                                <th scope="col">Name</th>
                                                <th scope="col">Price</th>
                                                <th scope="col">brand</th>
                                                <th scope="col">quantity</th>
                                                <th scope="col">action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        @forelse ($listType1Book['Book'][2]['Page'] ?? [] as $index => $cart)
                                            <tr>
                                                <input type="hidden" class="cart_id" value="{{ $cart['Id'] }}">
                                                <td>
                                                    <input type="checkbox" class="cart-check" name="bd-cud-check" value="1" tabindex="-1" @if($cart['C9'] === '1') checked @endif
                                                        onchange="change_cart_checkbox(this)">
                                                </td>
                                                <td class="table-serial"><h6>{{ $cart['C3'] }}</h6></td>
                                                <td class="table-image"><img src="{{ env('MEDIA_URL') . $cart['C2']  }}" alt="product"></td>
                                                <td class="table-name"><a href="{{ route('item-details', $cart['C10'] ?: $cart['C1']) }}"><h6>{{ $cart['C4'] }}</h6></a></td>
                                                <td class="table-price"><h6>{{ number_format($cart['C6']) }} 원<!--<small>/kilo</small>--></h6></td>
                                                <td class="table-brand"><h6>{{ $cart['C5'] }}</h6></td>
                                                <td class="table-quantity">
                                                    <h6>
                                                        <div class="product-action">
                                                            <button type="button" class="action-minus" title="Quantity Minus"><i class="icofont-minus"></i></button>
                                                            <input class="action-input" title="Quantity Number" onchange="cart_qty_update(this, {{ $cart['Id'] }})"
                                                                   type="text" min="1" value="{{ (int)$cart['C7'] }}">
                                                            <button type="button" class="action-plus" title="Quantity Plus"><i class="icofont-plus"></i></button>
                                                        </div>
                                                    </h6>
                                                </td>
                                                <td class="table-action">
{{--                                                    <a class="view" href="#" title="Quick View" data-bs-toggle="modal" data-bs-target="#product-view"><i class="fas fa-eye"></i></a>--}}
                                                    <button type="button" class="trash" onclick="cart_delete({{ $cart['Id'] }})" title="Remove Wishlist">
                                                        <i class="icofont-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td class="text-center" colspan="7">쇼핑카트가 비어있습니다</td>
                                            </tr>
                                        @endforelse
                                        </tbody>
                                    </table>
                                </div>
                                <div class="chekout-coupon">
{{--                                    <button type="button" class="coupon-btn">쿠폰 코드가 있습니까?</button>--}}
{{--                                    <form class="coupon-form">--}}
{{--                                        <input type="text" placeholder="Enter your coupon code">--}}
{{--                                        <button type="submit"><span>확인</span></button>--}}
{{--                                    </form>--}}
                                </div>
                                <div class="checkout-charge">
                                    <ul>
                                        <li>
                                            <span>Sub total</span>
                                            <span>{{ number_format($checkoutCharge['sub_total']) }} 원</span>
                                        </li>
                                        <li>
                                            <span>배송료</span>
                                            <span>{{ number_format($checkoutCharge['charge_amt']) }} 원</span>
                                        </li>
                                        <li>
                                            <span>할인</span>
                                            <span>0 원</span>
                                        </li>
                                        <li>
                                            <span>Total<small>(VAT 포함)</small></span>
                                            <span>{{ number_format($checkoutCharge['total']) }} 원</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
{{--                    <div class="col-lg-12">--}}
{{--                        <div class="account-card">--}}
{{--                            <div class="account-title">--}}
{{--                                <h4>배송일정</h4>--}}
{{--                            </div>--}}
{{--                            <div class="account-content">--}}
{{--                                <div class="row">--}}
{{--                                    <div class="col-md-6 col-lg-4 alert fade show">--}}
{{--                                        <div class="profile-card schedule">--}}
{{--                                            <h6>express</h6>--}}
{{--                                            <p>90 min express delivery</p>--}}
{{--                                        </div>--}}
{{--                                    </div>--}}
{{--                                    <div class="col-md-6 col-lg-4 alert fade show">--}}
{{--                                        <div class="profile-card schedule">--}}
{{--                                            <h6>8am-10pm</h6>--}}
{{--                                            <p>8.00 AM - 10.00 PM</p>--}}
{{--                                        </div>--}}
{{--                                    </div>--}}
{{--                                    <div class="col-md-6 col-lg-4 alert fade show">--}}
{{--                                        <div class="profile-card schedule">--}}
{{--                                            <h6>Next day</h6>--}}
{{--                                            <p>Next day or Tomorrow</p>--}}
{{--                                        </div>--}}
{{--                                    </div>--}}
{{--                                </div>--}}
{{--                            </div>--}}
{{--                        </div>--}}
{{--                    </div>--}}
                    <div class="col-lg-12">
                        <div class="account-card">
                            <div class="account-title">
                                <h4>연락처</h4>
                                <button id="contact-btn" type="button" class="medium-btn" data-attr="{{ route('contact.index', [ 'seq_no' =>  $listType1Book['Book'][0]['Page'] ? (int)$listType1Book['Book'][0]['Page'][count($listType1Book['Book'][0]['Page']) - 1]['C1'] + 1 : 0 ]) }}">
                                    연락처 추가
                                </button>
                            </div>
                            <div class="account-content">
                                <div class="row" id="company-contact-bd-div">
                                    @forelse ($listType1Book['Book'][0]['Page'] ?? [] as $contact)
                                        <div class="col-md-6 col-lg-4 alert fade show">
                                            <div class="profile-card contact">
                                                <h6>(<span class="sort-txt">{{ DataConverter::execute($contact['C2'], "sort('company-contact-bd')") }}</span>) <span class="ship-contact-txt">{{ $contact['C3'] }}</span></h6>
                                                <p class="ship-mobile-txt">{{ $contact['C4'] }}</p>
                                                <ul>
                                                    <li><button type="button" class="edit icofont-edit medium-btn" title="Edit This" data-attr="{{ route('contact.show', $contact['Id']) }}"></button></li>
                                                    <li><button type="button" class="trash icofont-ui-delete destroy-btn save-prev-scroll-submits" title="Remove This" data-attr="{{ route('contact.destroy', $contact['Id']) }}"></button></li>
                                                </ul>
                                            </div>
                                        </div>
                                    @empty
                                        <div class="col">
                                            비어있습니다
                                        </div>
                                    @endforelse
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="account-card">
                            <div class="account-title">
                                <h4>배송지</h4>
                                <button type="button" id="address-btn" class="medium-btn" data-attr="{{ route('address.index', [ 'seq_no' =>  $listType1Book['Book'][1]['Page'] ? (int)$listType1Book['Book'][1]['Page'][count($listType1Book['Book'][1]['Page']) - 1]['C1'] + 1 : 0 ]) }}">주소 추가</button>
                            </div>
                            <div class="account-content">
                                <div class="row" id="company-destina-bd-div">
                                    @forelse ($listType1Book['Book'][1]['Page'] ?? [] as $index => $address)
                                        <div class="col-md-6 col-lg-4 alert fade show">
                                            <div class="profile-card address">
                                                <h6 class="sort">{{ DataConverter::execute($address['C2'], "sort('company-destina-bd')") }}</h6>
                                                <p>(<span class="ship-zip-code-txt">{{ $address['C3'] }}</span>) <span class="ship-addr1-txt">{{ $address['C4'] }}</span> <span class="ship-addr2-txt">{{ $address['C5'] }}</span></p>
                                                <ul class="user-action">
                                                    <li><button type="button" class="edit icofont-edit medium-btn" title="Edit This" data-attr="{{ route('address.show', $address['Id']) }}"></button></li>
                                                    <li><button type="button" class="trash icofont-ui-delete destroy-btn save-prev-scroll-submits" title="Remove This" data-attr="{{ route('address.destroy', $address['Id']) }}"></button></li>
                                                </ul>
                                            </div>
                                        </div>
                                    @empty
                                        <div class="col">
                                            비어있습니다
                                        </div>
                                    @endforelse
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="account-card page-pc">
                            <div class="account-title">
                                <h4>결제방법</h4>
                                <button type="button" class="medium-btn" id="crypto1-send-transaction-btn"
                                        style="display: none;" data-attr="{{ route('wallet-send.index', ['msqxpAmount' => $checkoutCharge['point_payrate']['crypto1']['msqxp'], 'p2upAmount' => $checkoutCharge['point_payrate']['crypto1']['p2up']]) }}">
                               </button>

                                <button type="button" class="medium-btn" id="crypto2-send-transaction-btn"
                                        style="display: none;" data-attr="{{ route('wallet-send.index', [ 'msqxpAmount' => 0, 'p2upAmount' => $checkoutCharge['point_payrate']['crypto2']['p2up'] ]) }}">
                                </button>
                                {{--                                <button type="button" class="medium-btn qrcode-scan" style="display: none;" data-attr="{{ route('wallet-balance.index') }}">--}}
{{--                                    내 자산 QR 코드 스캔--}}
{{--                                </button>--}}
                            </div>
                            <div class="account-content" id="paymethod-div">
                                <div class="d-flex align-items-center">
                                    @php
                                        $shopPayMethodSetup = json_decode($listType1Book['Book'][6]['Page'][0]['C1'], true);
                                    @endphp
                                    @forelse ($codeTitle['paymethod']['sorder'] ?? [] as $key => $paymethod)
                                        @php
                                            $key = 'Is' . $paymethod['Code'];
                                        @endphp
                                        @if (array_key_exists( $key,  $shopPayMethodSetup) && $shopPayMethodSetup[$key])
                                            <div class="paymethod-div">
                                                <input type="radio" value="{{ $paymethod['Code'] }}" name="paymethod" id="paymethod-radio-{{ $paymethod['Code'] }}" onclick="checkBox(this)">
                                                <label for="paymethod-radio-{{ $paymethod['Code'] }}" class="form-label">{{ $paymethod['Title'] }}</label>
                                            </div>
                                        @endif
                                    @empty
                                        <div class="col">
                                            비어있습니다
                                        </div>
                                    @endforelse
                                </div>

                                <div id="paymethod-Remit" class="divcont virtual-account-payment pay-type-content">
                                    @include('views.shop.checkout.paymethod-remit', [ 'parentClass' => '#paymethod-Remit' ])
                                </div>

                                <div id="paymethod-CrCard" class="divcont virtual-account-payment pay-type-content">
                                </div>

                                <div id="paymethod-Crypto1" class="divcont virtual-account-payment pay-type-content">
                                	<p class="validate-message" style="display: none;"></p>
                                    <ul class="pay-type-sections msqxp-group">
                                        <li class="payBox-section pay-type-section mt-2">
                                            @php
                                                if ($checkoutCharge['total'] > 0) {
                                                    $crypto1P2upPercent = number_format($checkoutCharge['point_payrate']['crypto1']['p2up'] / $checkoutCharge['total'] * 100, 2);
                                                } else {
                                                    $crypto1P2upPercent = 0;
                                                }
                                            @endphp
                                            <label class="line-title d-block">P2UP 결제* (최대 {{ $crypto1P2upPercent }}% 까지)</label>
                                            <input type="text" class="form-control decimal p2up-txt"
                                                   data-point="0"
                                                   onchange="change_p2up(this, 'crypto1', '#paymethod-Crypto1 #msqxp-txt')"
                                                   value="{{ number_format($checkoutCharge['point_payrate']['crypto1']['p2up']) }}">
                                        </li>

                                        <li class="payBox-section pay-type-section mt-2">
                                            <label class="line-title d-block">MSQXP 결제 (잔액결제)</label>
                                            <input type="text" id="msqxp-txt" class="form-control" value="{{ number_format($checkoutCharge['point_payrate']['crypto1']['msqxp']) }}" readonly>
                                        </li>

{{--                                        <li class="payBox-section pay-type-section mt-2">--}}
{{--                                            <label class="line-title d-block">MSQ XP 현잔액</label>--}}
{{--                                            <input type="text" class="form-control" id="msqxp-balance-txt" readonly>--}}
{{--                                        </li>--}}
{{--                                        <li class="payBox-section pay-type-section mt-2 avail possible" style="display: none;">--}}
{{--                                            결제가능--}}
{{--                                            <strong class="text-primary"><i class="far fa-circle"></i></strong>--}}
{{--                                        </li>--}}
{{--                                        <li class="payBox-section pay-type-section mt-2 avail impossible">--}}
{{--                                            결제불가--}}
{{--                                            <strong class="text-danger"><i class="fas fa-times"></i></strong>--}}
{{--                                        </li>--}}
                                    </ul>

{{--                                    <ul class="pay-type-sections pay-cypto p2up-group">--}}
{{--                                        <li class="payBox-section pay-type-section mt-2">--}}
{{--                                            <label class="line-title d-block">P2U 결제 (50%)</label>--}}
{{--                                            <input type="text" class="form-control" name="" id="txt" value="{{ number_format($checkoutCharge['half_total']) }}" readonly>--}}
{{--                                        </li>--}}

{{--                                        <li class="payBox-section pay-type-section mt-2">--}}
{{--                                            <label class="line-title d-block">P2U 현잔액</label>--}}
{{--                                            <input type="text" class="form-control" id="p2up-balance-txt" readonly>--}}
{{--                                        </li>--}}

{{--                                        <li class="payBox-section pay-type-section mt-2 avail possible" style="display: none;">--}}
{{--                                            결제가능--}}
{{--                                            <strong class="text-primary"><i class="far fa-circle"></i></strong>--}}
{{--                                        </li>--}}
{{--                                        <li class="payBox-section pay-type-section mt-2 avail impossible">--}}
{{--                                            결제불가--}}
{{--                                            <strong class="text-danger"><i class="fas fa-times"></i></strong>--}}
{{--                                        </li>--}}
{{--                                    </ul>--}}
                                </div>

                                <div id="paymethod-Crypto2" class="divcont virtual-account-payment pay-type-content">
                                    <div>
                                        <p class="validate-message" style="display: none;"></p>
                                        <ul class="pay-type-sections msqxp-group">
                                            <li class="payBox-section pay-type-section mt-2">
                                                @php
                                                    if ($checkoutCharge['total'] > 0) {
                                                        $crypto2P2upPercent = number_format($checkoutCharge['point_payrate']['crypto2']['p2up'] / $checkoutCharge['total'] * 100, 2);
                                                    } else {
                                                        $crypto2P2upPercent = 0;
                                                    }
                                                @endphp

                                                <label class="line-title d-block">P2UP 결제* (최대 {{ $crypto2P2upPercent }}% 까지)</label>
                                                <input type="text" class="form-control decimal p2up-txt"
                                                       data-point="0"
                                                       onchange="change_p2up(this, 'crypto2', '#paymethod-Crypto2 #cash-txt')"
                                                       value="{{ number_format($checkoutCharge['point_payrate']['crypto2']['p2up']) }}">
                                            </li>

                                            <li class="payBox-section pay-type-section mt-2">
                                                <label class="line-title d-block">원화 결제 (잔액결제)</label>
                                                <input type="text" id="cash-txt" class="form-control" value="{{ number_format($checkoutCharge['point_payrate']['crypto2']['cash']) }}" readonly>
                                            </li>

                                            {{--                                        <li class="payBox-section pay-type-section mt-2">--}}
                                            {{--                                            <label class="line-title d-block">현금 결제</label>--}}
                                            {{--                                            <input type="text" class="form-control" value="{{ number_format($checkoutCharge['point_payrate']['cash']) }}" readonly>--}}
                                            {{--                                        </li>--}}
                                        </ul>
                                    </div>

                                    <div>
                                        @include('views.shop.checkout.paymethod-remit', [ 'parentClass' => '#paymethod-Crypto2' ])
                                    </div>
                                </div>

{{--                                <div id="paymethod-Crypto2" class="divcont virtual-account-payment pay-type-content">--}}
{{--                                    <p class="validate-message" style="display: none;"></p>--}}
{{--                                    <ul class="pay-type-sections pay-cypto">--}}
{{--                                        <li class="payBox-section pay-type-section mt-2">--}}
{{--                                            <label class="line-title d-block">세번째 레이어MSQ XP 결제 (50%)</label>--}}
{{--                                            <input type="text" class="form-control" id="" readonly>--}}
{{--                                        </li>--}}

{{--                                        <li class="payBox-section pay-type-section mt-2">--}}
{{--                                            <label class="line-title d-block">MSQXP 현잔액</label>--}}
{{--                                            <input type="text" class="form-control" id="" readonly>--}}
{{--                                        </li>--}}
{{--                                        <li class="payBox-section pay-type-section mt-2 avail">--}}
{{--                                            결제가능--}}
{{--                                            <strong class="text-primary"><i class="far fa-circle"></i></strong>--}}
{{--                                        </li>--}}
{{--                                    </ul>--}}
{{--                                    <ul class="pay-type-sections pay-cypto">--}}
{{--                                        <li class="payBox-section pay-type-section mt-2">--}}
{{--                                            <label class="line-title d-block">P2U 결제 (50%)</label>--}}
{{--                                            <input type="text" class="form-control" name="" id=""  readonly>--}}
{{--                                        </li>--}}

{{--                                        <li class="payBox-section pay-type-section mt-2">--}}
{{--                                            <label class="line-title d-block">P2U 현잔액</label>--}}
{{--                                            <input type="text" class="form-control" id="" readonly>--}}
{{--                                        </li>--}}

{{--                                        <li class="payBox-section pay-type-section mt-2 avail">--}}
{{--                                            결제가능--}}
{{--                                            <strong class="text-danger"><i class="fas fa-times"></i></strong>--}}
{{--                                        </li>--}}
{{--                                    </ul>--}}
{{--                                </div>--}}

                            </div>
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="account-card mb-0">
                            <div class="account-title">
                                <h4>결제하기</h4>
{{--                                <button data-bs-toggle="modal" data-bs-target="#payment-add">지갑 추가</button>--}}
                            </div>
{{--                            <div class="account-content">--}}
{{--                                <div>--}}
{{--                                    <label class="line-title d-block">입금자명</label>--}}
{{--                                    <input type="text" class="form-text" name="remit_name" id="remit-name-txt" required>--}}
{{--                                </div>--}}
{{--							</div>--}}

                            <div class="checkout-check">
                                <input type="checkbox" id="checkout-check">
                                <label for="checkout-check">약관동의 <a href="{{ route('policy.index') }}" target="_blank">약관보기</a></label>
                            </div>
                            <div class="checkout-proced">
{{--                                <a href="/checkout-ok" class="btn btn-inline">결제하기</a>--}}
                                <button type="submit" id="checkout-btn" class="btn btn-inline button-prevent-multiple-submits">
                                    <i class="spinner fa fa-spinner fa-spin"></i>
                                    결제하기
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </section>
        <!--=====================================
                    CHECKOUT PART END
        =======================================-->


        <!--=====================================
                    MODAL ADD FORM START
        =======================================-->
@endsection

@push('modal')
    @include('views.modals.medium')
@endpush

@push('js')
{{--<script type="text/javascript" src="https://cdn.iamport.kr/js/iamport.payment-1.2.0.js"></script>--}}
    <script>
        $(document).ready(function() {
            const first_paymethod = $('.paymethod-div').first().find('input')
            first_paymethod.prop('checked', true)
            checkBox('#' + first_paymethod.attr('id'))

            // IMP.init(import_pg_setup['MerchantId']);
        });

        function change_p2up($this, type, dom_val) {
            const checkout_charge = @json($checkoutCharge);
            const p2up_max_val = checkout_charge['point_payrate'][type]['p2up']
            const p2up_val = minusComma( $($this).val() )

            if (p2up_val < 0 || p2up_val > p2up_max_val) {
                $($this).val( format_decimal( p2up_max_val, 0) )

                switch (type) {
                    case 'crypto1':
                        $(dom_val).val( format_decimal( checkout_charge['point_payrate'][type]['msqxp'], 0 ) )
                        break;
                    case 'crypto2':
                        $(dom_val).val( format_decimal( checkout_charge['point_payrate'][type]['cash'], 0 ) )
                        break;
                }
                return iziToast.info({ title: 'Info', message: 'P2UP 최대 결제금액을 초과했습니다' })
            }

            const second_val = format_decimal(checkout_charge['total'] - p2up_val, 0)
            $(dom_val).val(second_val)
        }

        {{--function request_pay() {--}}
        {{--    const checkout_form = $('#checkout-form')--}}
        {{--    const amount = @json($checkoutCharge['total']);--}}
        {{--    const item_name = @json($checkoutCharge['item_name']);--}}
        {{--    // IMP.request_pay(param, callback) 결제창 호출--}}
        {{--    IMP.request_pay({ // param--}}
        {{--        pg: import_pg_setup['PG'],--}}
        {{--        pay_method: "card",--}}
        {{--        // merchant_uid: "",--}}
        {{--        name: item_name,--}}
        {{--        amount: Number(amount),--}}
        {{--        buyer_email: window.Member['Email'],--}}
        {{--        buyer_name: $(checkout_form).find('input[name="ship_contact"]').val(),--}}
        {{--        buyer_tel: $(checkout_form).find('input[name="ship_mobile"]').val(),--}}
        {{--        buyer_addr: $(checkout_form).find('input[name="ship_addr1"]').val(),--}}
        {{--        buyer_postcode: $(checkout_form).find('input[name="ship_zip_code"]').val()--}}
        {{--    }, function (rsp) { // callback--}}
        {{--        if (rsp.success) {--}}
        {{--            success_external_payment_callback(checkout_form)--}}
        {{--            $(checkout_form).trigger('submit', true)--}}
        {{--        } else {--}}
        {{--            failed_external_payment_callback(checkout_form)--}}
        {{--        }--}}
        {{--    });--}}
        {{--}--}}

        async function change_cart_all_checkbox($this) {
            const page = []
            $('#cart-table > tbody > tr').each(function () {
                page.push( {
                    Id: Number($(this).find('.cart_id').val()),
                    Checked: $($this).is(':checked') ? '1' : '0'
                } )
            })

            await cart_act_parameter(page)
        }

        async function change_cart_checkbox($this) {
            await cart_act_parameter([
                {
                    Id: Number($($this).closest('tr').find('.cart_id').val()),
                    Checked: $($this).prop('checked') ? '1' : '0'
                }
            ])
        }

        async function cart_act_parameter(page) {
            const response = await get_api_data('cart-act', {
                Page : page
            })

            show_iziToast_msg(response.data.Page, function () {
                location.reload()
            })
        }

        function failed_external_payment_callback(checkout_form) {
            $(checkout_form).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'status', 'value': 'F' }))
            $(checkout_form).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'situation', 'value': 'FF' }))
            $(checkout_form).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'situation_title', 'value': format_conver_for('FF', "situation('sorder')") }))
        }

        function success_external_payment_callback(checkout_form) {
            $(checkout_form).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'status', 'value': '1' }))
            $(checkout_form).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'ok_success', 'value': true }))
            $(checkout_form).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'ok_paid', 'value': true }))
        }

        function completed_wallet_send(data) {
            const checkout_form = $('#checkout-form')

            // if ('error' !== 'success') {
            if (data['transaction']['status'] !== 'success') {
                failed_external_payment_callback(checkout_form)
            } else {
                success_external_payment_callback(checkout_form)
            }
            $(checkout_form).trigger('submit', true)
        }

        function fn_move(dom_val){
            // $(dom_val).focus()
            const offset = $(dom_val).offset()
            $('html, body').animate({scrollTop : offset.top - 250}, 400)
        }

        {{--function check_balance_possible(dom_val, balance, half_total) {--}}
        {{--    if (balance >= half_total) {--}}
        {{--        $(dom_val).find('.possible').show()--}}
        {{--        $(dom_val).find('.impossible').hide()--}}
        {{--    } else {--}}
        {{--        $(dom_val).find('.possible').hide()--}}
        {{--        $(dom_val).find('.impossible').show()--}}
        {{--    }--}}
        {{--}--}}

        {{--function update_balance_ui(data) {--}}
        {{--    const checkout_form = $('#checkout-form')--}}
        {{--    const msq_bal = data['wallet']['balance']['MSQXP']--}}
        {{--    const p2u_bal = data['wallet']['balance']['P2U']--}}
        {{--    const half_total = @json($checkoutCharge['half_total']);--}}

        {{--    $(checkout_form).find('#msqxp-balance-txt').val(format_decimal( msq_bal, 0 ))--}}
        {{--    $(checkout_form).find('#p2up-balance-txt').val(format_decimal( p2u_bal, 0 ))--}}

        {{--    check_balance_possible('.msqxp-group', msq_bal, half_total)--}}
        {{--    check_balance_possible('.p2up-group', p2u_bal, half_total)--}}
        {{--}--}}

        // 결제방법 탭 변경 이벤트
        // $('input[name=paymethod]').on('change', function() {
        //     $('.page-pc').find('.qrcode-scan').hide()
        //
        //     switch ($(this).val()) {
        //         case 'Remit':
        //             break
        //         case 'Crypto1':
        //             $('.page-pc').find('.qrcode-scan').show()
        //             break
        //     }
        // });

        function check_remit_error(dom_val) {
            const deposit_bank_select = `${dom_val} #deposit-bank-select option:selected`

            if (isEmpty($(dom_val).find('#remit-name-txt').val())) {
                fn_move(`${dom_val} #remit-name-txt`)
                return { error: true, msg: '입금자명을 입력하세요'  }
            } else if (isEmpty($(deposit_bank_select).val())) {
                fn_move(`${dom_val} #deposit-bank-select`)
                return { error: true, msg: '무통장입금 계좌를 선택하세요'  }
            }

            return { error: false, data: []  }
        }

        // 결제방법 에따른 체크 메시지
        function check_paymethod_radio() {
            const paymethod = $('input[name=paymethod]:checked').val()
            const checkout_charge = @json($checkoutCharge);

            // console.log(paymethod)
            switch (paymethod) {
                case 'Remit':
                    return check_remit_error('#paymethod-Remit')

                case 'Crypto1':
                    const crypto1_p2up = Number( minusComma( $('#paymethod-Crypto1').find('.p2up-txt').val() ) )
                    const crypto1_total = crypto1_p2up + Number( minusComma( $('#paymethod-Crypto1').find('#msqxp-txt').val() ) )
                    const crypto1_p2up_max_val  = checkout_charge['point_payrate']['crypto1']['p2up']

                    if (checkout_charge['total'] !== crypto1_total) {
                        return { error: true, msg: '결제 금액을 다시 확인하세요'  }
                    } else if (crypto1_p2up < 0 || crypto1_p2up > crypto1_p2up_max_val) {
                        return { error: true, msg: 'P2UP 최대 결제금액을 초과했습니다'  }
                    }
                    return { error: false, data: []  }
                case 'Crypto2':
                    const crypto2_p2up = Number( minusComma( $('#paymethod-Crypto2').find('.p2up-txt').val() ))
                    const crypto2_total = crypto2_p2up + Number( minusComma( $('#paymethod-Crypto2').find('#cash-txt').val() ) )
                    const crypto2_p2up_max_val  = checkout_charge['point_payrate']['crypto2']['p2up']

                    if (checkout_charge['total'] !== crypto2_total) {
                        return { error: true, msg: '결제 금액을 다시 확인하세요'  }
                    } else if (crypto2_p2up < 0 || crypto2_p2up > crypto2_p2up_max_val) {
                        return { error: true, msg: 'P2UP 최대 결제금액을 초과했습니다'  }
                    }

                    return check_remit_error('#paymethod-Crypto2')
                default:
                    return { error: false, data: []  }
            }
        }

        function make_remit_form_data(form, dom_val) {
            const deposit_bank_select = `${dom_val} #deposit-bank-select option:selected`
            const remit_account = $(deposit_bank_select).text() + ' ' + $(dom_val).find('#account-no-txt').val() + ' ' + $(dom_val).find('#holder-name-txt').val()
            const remit_name = $(dom_val).find('#remit-name-txt').val()

            $(form).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'remit_account', 'value': remit_account }))
            $(form).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'remit_name', 'value': remit_name }))
        }

        // 결제방법에 따른 폼데이터 추가
        function create_add_form_data($this) {
            // 동적으로 추가한 폼데이터 삭제
            $($this).find('.dynamic_add_data').remove()

            const paymethod = $('input[name=paymethod]:checked').val()
            const checkout_charge = @json($checkoutCharge);

            switch (paymethod) {
                case 'Remit':
                    make_remit_form_data($this, '#paymethod-Remit')

                    $($this).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'cash_amt', 'value': checkout_charge['total'] }))
                    $($this).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'ok_success', 'value': true }))
                    return { error: false, data: []  }
                case 'Crypto1':
                    const crypto1_p2up = minusComma( $('#paymethod-Crypto1').find('.p2up-txt').val() )
                    const crypto1_msqxp = minusComma( $('#paymethod-Crypto1').find('#msqxp-txt').val() )

                    $($this).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'x1_pay_amt', 'value': crypto1_p2up }))
                    $($this).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'x2_pay_amt', 'value': crypto1_msqxp }))

                    const crypto1_url = $('#crypto1-send-transaction-btn').attr('data-attr').split('?')
                    const crypto1_params = new URLSearchParams(crypto1_url[1])
                    crypto1_params.set('p2upAmount', crypto1_p2up)
                    crypto1_params.set('msqxpAmount', crypto1_msqxp)

                    $('#crypto1-send-transaction-btn').attr('data-attr', crypto1_url[0] + '?' + crypto1_params.toString())
                    $('#crypto1-send-transaction-btn').trigger('click')
                    return { error: true, msg: ''  }
                case 'Crypto2':
                    const crypto2_p2up = minusComma( $('#paymethod-Crypto2').find('.p2up-txt').val() )
                    const crypto2_cash = minusComma( $('#paymethod-Crypto2').find('#cash-txt').val() )

                    make_remit_form_data($this, '#paymethod-Crypto2')
                    $($this).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'x1_pay_amt', 'value': crypto2_p2up }))
                    $($this).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'cash_amt', 'value': crypto2_cash }))
                    $($this).append($('<input>', { 'type': 'hidden', 'class': 'dynamic_add_data', 'name': 'ok_success', 'value': true }))

                    // p2u가 0일 떄 qr코드 스킵
                    if (Number(crypto2_p2up) === 0) {
                        return { error: false, data: []  }
                    }

                    const crypto2_url = $('#crypto2-send-transaction-btn').attr('data-attr').split('?')
                    const crypto2_params = new URLSearchParams(crypto2_url[1])
                    crypto2_params.set('p2upAmount', crypto2_p2up)

                    $('#crypto2-send-transaction-btn').attr('data-attr', crypto2_url[0] + '?' + crypto2_params.toString())
                    $('#crypto2-send-transaction-btn').trigger('click')
                    return { error: true, msg: ''  }
                case 'CrCard':
                    // request_pay()
                    return { error: true, msg: ''  }
            }

        }

        $('#checkout-form').on('submit', function (event, direct_submit) {
            event.preventDefault()

            // 바로 submit
            if (direct_submit) {
                return this.submit()
            }

            const sub_total = @json($checkoutCharge['sub_total']);
            if (sub_total <= 0) {
                return iziToast.info({ title: 'Info', message: '쇼핑카트가 비어있습니다' })
            }

            const result = check_paymethod_radio()
            if (result['error']) {
                return iziToast.info({ title: 'Info', message: result['msg'] })
            }

            const company_contact_bd_div = '#company-contact-bd-div .profile-card'
            const company_destina_bd_div = '#company-destina-bd-div .profile-card'

            if (! $(company_contact_bd_div).hasClass('active')) {
                fn_move('#contact-btn')
                return iziToast.info({ title: 'Info', message: '연락처를 선택하세요' })
            }

            if (! $(company_destina_bd_div).hasClass('active')) {
                fn_move('#address-btn')
                return iziToast.info({ title: 'Info', message: '배송지를 선택하세요' })
            }

            if (! $('#checkout-check').prop('checked')) {
                fn_move('#checkout-check')
                return iziToast.info({ title: 'Info', message: '약관을 확인하세요' })
            }

            click_submit_btn(this)

            const ship_contact = $(company_contact_bd_div + '.active').find('.ship-contact-txt').text()
            const ship_mobile = $(company_contact_bd_div + '.active').find('.ship-mobile-txt').text()

            const ship_zip_code = $(company_destina_bd_div + '.active').find('.ship-zip-code-txt').text()
            const ship_addr1 = $(company_destina_bd_div + '.active').find('.ship-addr1-txt').text()
            const ship_addr2 = $(company_destina_bd_div + '.active').find('.ship-addr2-txt').text()

            $(this).append($('<input>', { 'type': 'hidden', 'name': 'ship_contact', 'value': ship_contact }))
            $(this).append($('<input>', { 'type': 'hidden', 'name': 'ship_mobile', 'value': ship_mobile }))
            $(this).append($('<input>', { 'type': 'hidden', 'name': 'ship_zip_code', 'value': ship_zip_code }))
            $(this).append($('<input>', { 'type': 'hidden', 'name': 'ship_addr1', 'value': ship_addr1 }))
            $(this).append($('<input>', { 'type': 'hidden', 'name': 'ship_addr2', 'value': ship_addr2 }))

            if (create_add_form_data(this)['error']) {
                return click_submit_btn(this, false)
            }

            this.submit()
        });

        function change_remit_account($this, closet_val) {
            $(closet_val).find('#account-no-txt').val($($this).val())
            $(closet_val).find('#holder-name-txt').val($($this).find('option:selected').data('holder-name'))
        }

        function checkBox($this) {
            const payMethod = document.getElementsByName('paymethod'); //체크박스 name
            $(payMethod).each(function () {
                const disign = $('#paymethod-' +  $(this).val())// 보여질내용
                if($(this).val() === $($this).val()) {
                    disign.show()
                } else{
                    disign.hide()
                }
            });
        }

        const import_pg_setup = @json($importPgSetup);
    </script>

@endpush
