@php
    if (Auth::user()->role === \App\Models\Users::ROLE_ADMIN) {
        $route_list_trx = route('view_transactions');
    } else {
        $route_list_trx = route('view_user_client_transaction');
    }
@endphp

@extends('app.app')
@section('title')
    User Client
@endsection
@section('customcss')
@endsection

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="row">
                {{-- Form Order --}}
                <div class="col-sm-6">
                    <div class="card">
                        {{-- <div class="card-header">
                            <div class="row d-flex align-items-center">
                                <div class="col">
                                    <p class="card-title text-bold mb-0">Add new job</p>
                                </div>
                            </div>
                        </div> --}}
                        <div class="card-body pb-0">
                            @if (Auth::user()->role == \App\Models\Users::ROLE_ADMIN)
                                <div class="row mb-3 d-flex align-items-center d-none">
                                    <div class="col-sm-5 col-5 mb-3">
                                        <label for="add-client" class="form-label text-nowrap">Company</label>
                                        <select name="add-client" id="add-client" class="select2 form-control">

                                            @foreach ($uclients as $uclient)
                                                <option value="{{ $uclient->id }}" data-uid="{{ $uclient->id }}" data-cptid="{{ $uclient->client_group_id }}">
                                                    {{ $uclient->client_group_name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            @endif
                            <div class="row mb-3 d-flex align-items-center">
                                <div class="col-12 mb-3">
                                    <p class="text-danger text-bold mb-0">Orign & Destination</p>
                                    {{-- <small>select time, pickup and drop zone from your zone list. Can't find your zone? <a href="{{ route('view_zone') }}">Add new zone</a></small> --}}
                                    <small>Enter the date, time, origin location, and destination location from<br>the list of registered zones.</small>
                                </div>
                                <div class="col-sm-5 col-5 mb-3">
                                    <label for="add-pickup_date" class="form-label text-nowrap">Date</label>
                                    <input type="date" name="add-pickup_date" id="add-pickup_date" class="form-control">
                                </div>
                                <div class="col-2"></div>
                                <div class="col-sm-5 col-5 mb-3">
                                    <label for="add-pickup_time" class="form-label text-nowrap">Time</label>
                                    {{-- <input type="time" name="add-pickup_time" id="add-pickup_time" class="form-control"
                                        min="23:30"> --}}
                                    <div class="row">
                                        <div class="col-md-4 col-lg-3" style="padding:0 0 0 0.75rem;">
                                            <select name="add-pickup_time_hour" id="add-pickup_time_hour" class="form-control">
                                                <option value="" selected disabled hidden>--</option>
                                                @for ($i = 0; $i < 24; $i++)
                                                    <option value="{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}">{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}</option>
                                                @endfor
                                            </select>
                                        </div>
                                        <div class="col-md-4 col-lg-3" style="padding:0 0 0 0.75rem;">
                                            <select name="add-pickup_time_minute" id="add-pickup_time_minute" class="form-control">
                                                <option value="" selected disabled hidden>--</option>
                                                @for ($i = 0; $i < 60; $i++)
                                                    <option value="{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}">{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}</option>
                                                @endfor
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row mb-3 d-flex align-items-center">
                                <div class="col-5 mb-3">
                                    <label for="add-pickup_zone" class="form-label">Origin</label>
                                    <select name="add-pickup_zone" id="add-pickup_zone" class="select2 form-control">
                                        <option value="" selected disabled>No origin location selected</option>
                                        @if (Auth::user()->role === \App\Models\Users::ROLE_CLIENT_ADMIN)
                                            @foreach ($pickups as $pickup)
                                                <option value="{{ $pickup->id }}" data-id="{{ $pickup->id }}" data-title="{{ $pickup->name }}" data-addr="{{ $pickup->fulladdress }}">
                                                    {{ $pickup->name }}</option>
                                            @endforeach
                                        @endif
                                    </select>
                                </div>
                                <div class="col-2 text-center">
                                    <label for="" class="form-label mb-0 mt-2">&nbsp;</label>
                                    {{-- <p class="mb-0">to</p> --}}
                                    <span class="ion-arrow-right-c text-danger" style="font-size: 15px"></span>
                                </div>
                                <div class="col-5 mb-3">
                                    <label for="add-drop_zone" class="form-label">Destination</label>
                                    <select name="add-drop_zone" id="add-drop_zone" class="select2 form-control">
                                        <option value="" selected disabled>No destination location selected</option>
                                        @if (Auth::user()->role === \App\Models\Users::ROLE_CLIENT_ADMIN)
                                            @foreach ($drops as $drop)
                                                <option value="{{ $drop->id }}" data-id="{{ $drop->id }}" data-title="{{ $drop->name }}" data-addr="{{ $drop->fulladdress }}">
                                                    {{ $drop->name }}</option>
                                            @endforeach
                                        @endif
                                    </select>
                                </div>
                            </div>
                            <div class="row d-flex align-items-center justify-content-between">
                                <div class="col-12 mb-3">
                                    <p class="text-danger text-bold mb-0">Informasi Kendaraan</p>
                                    {{-- <small>You must fill in at least 1 of the package information.</small> --}}
                                </div>
                                {{-- <div class="col-7 mb-3 text-bold">Description</div>
                                <div class="col-5 mb-3 text-bold">Unit</div>

                                <div class="col-7 mb-3">Weight</div>
                                <div class="col-5 mb-3 d-flex align-items-center">
                                    <input type="number" name="add-weight" id="add-weight" class="form-control w-75 me-2">Kg
                                </div>

                                <div class="col-7 mb-3">Volume</div>
                                <div class="col-5 mb-3 d-flex align-items-center">
                                    <input type="number" name="add-cbm" id="add-cbm" class="form-control w-75 me-2">m³
                                </div>

                                <div class="col-7 mb-3">Koli</div>
                                <div class="col-5 mb-3 d-flex align-items-center">
                                    <input type="number" name="add-koli" id="add-koli" class="form-control w-75 me-2">pcs
                                </div> --}}
                                {{-- <div class="col-5 mb-3">
                                    <label for="add-truck_type" class="form-label">Jenis Kendaraan</label>
                                    <select name="add-truck_type" id="add-truck_type" class="select2 form-control">
                                        <option value="" selected disabled>Pilih kendaraan</option>
                                        @foreach ($truck_types as $tt)
                                            <option value="{{ $tt->type_id }}" data-id="{{ $tt->id }}" data-type_id="{{ $tt->type_id }}" data-name="{{ $tt->type_name }}" data-weight="{{ $tt->max_kg }}" data-cbm="{{ $tt->max_cbm }}" data-koli="{{ $tt->max_koli }}">
                                                {{ $tt->type_name }}</option>
                                        @endforeach
                                    </select>
                                </div> --}}
                                <div class="col-5 mb-3">
                                    <label for="add-truck_type" class="form-label">Select Vehicle</label>
                                    <select name="add-truck_type" id="add-truck_type" class="select2 form-control">
                                        <option value="" selected disabled>Select Vehicle</option>
                                        @foreach ($vehicle as $_vehicle)
                                            <option value="{{ $_vehicle->vid }}" data-id="{{ $_vehicle->vid }}" data-type_id="{{ $_vehicle->vid }}" data-name="{{ $_vehicle->name }}">
                                                {{ $_vehicle->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-5 mb-3">
                                    <label for="add-driver" class="form-label">Driver</label>
                                    <select name="add-driver" id="add-driver" class="select2 form-control">
                                        <option value="" selected disabled>Select Driver</option>
                                        @foreach ($driver as $_driver)
                                            <option value="{{ $_driver->id }}" data-id="{{ $_driver->id }}" data-driver_id="{{ $_driver->id }}" data-name="{{ $_driver->fullname }}">
                                                {{ $_driver->fullname }}</option>
                                        @endforeach
                                    </select>
                                </div>

                            </div>
                            {{-- <div class="row d-flex align-items-center">
                                <div class="col-12 mb-3">
                                    <p class="text-danger text-bold mb-0">Package list</p>
                                    <small>Upload your packing list according to the specified format. don't have it? <a
                                            href="#" id="download_template_packing_list">Download packing list
                                            template</a></small>
                                </div>
                                <div id="add-group_upload_packinglist" class="col-sm-12">
                                    <label for="add-packinglist" class="form-label">Upload Packing List</label>
                                    <input class="form-control" type="file" name="add-packinglist" id="add-packinglist"
                                        required>
                                </div>
                                <div id="add-group_upload_packinglist_spinner" class="col-12 d-none">
                                    <div class="spinner-border" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                </div>
                            </div> --}}
                            <div class="row d-flex align-items-center mb-3 d-none">
                                <div class="col-12 mb-3">
                                    <p class="text-danger text-bold mb-0">Asuransi</p>
                                    <small>Apakah Anda ingin menambahkan Asuransi untuk pengiriman ini?</small>
                                </div>
                                <div class="col-5">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="" id="insuranceCheck">
                                        <label class="form-check-label" for="insuranceCheck">
                                            Ya, Asuransikan pengiriman saya
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="row d-flex align-items-center d-none" id="insurancePrice">
                                <div class="col-5">
                                    <label for="insuranceInput" class="form-label">Total Harga Pertanggungan
                                        (Rp)</label>
                                    <input type="number" name="insuranceInput" class="form-control" id="insuranceInput">
                                </div>
                            </div>
                        </div>
                        <div class="card-footer">
                            <div class="row d-flex align-items-center">
                                <div class="col-8">
                                    <p class="mb-0">
                                        Have you filled in all the required fields?
                                    </p>
                                </div>
                                <div class="col-4 text-end">
                                    <button class="btn btn-warning btn-block btn-sm" id="btnCalculate">&nbsp;&nbsp;&nbsp;&nbsp;Next&nbsp;&nbsp;&nbsp;&nbsp;</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                {{-- Checkout --}}
                <div class="col-sm-6 d-none" id="checkOutView">
                    {{-- <div class="col-sm-6"> --}}
                    <div class="card">
                        <div class="card-header">
                            <div class="row d-flex align-items-center">
                                <div class="col">
                                    <p class="card-title text-bold mb-0">Checkout</p>
                                </div>
                            </div>
                        </div>
                        <div id="checkout-spinner" class="card-body pb-0 d-none">
                            <div class="row d-flex align-items-center">
                                <div class="col-12 mb-3">
                                    <div class="spinner-border" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-body pb-0 checkoutBody">
                            <div class="row d-flex align-items-center">
                                <div class="col-12 mb-3">
                                    <p class="text-danger text-bold mb-0">Orign & Destination</p>
                                </div>
                                <div class="col-sm-5 mb-3">
                                    <label for="" class="form-label">Date</label>
                                    <div class="card bg-light border mb-0">
                                        <div class="card-body">
                                            <p id="checkout-pickup_at" class="mb-0">Feb 22, 2022 23:59:00</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-2"></div>
                                <div class="col-sm-5 mb-3">
                                    <label for="" class="form-label">Vehicle</label>
                                    <div class="card bg-light border mb-0">
                                        <div class="card-body">
                                            <p id="checkout-truck_type" class="mb-0">CDD Long</p>
                                            <p id="checkout-driver" class="mb-0">CDD Long</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row d-flex align-items-center">
                                <div class="col-5 mb-3">
                                    <label for="" class="form-label">Origin</label>
                                    <div class="card bg-light border mb-0">
                                        <div class="card-body">
                                            <p id="checkout-pickup_zone_title" class="text-bold mb-2">Gudang Pluit SiCepat
                                                (Jakarta)</p>
                                            <p id="checkout-pickup_zone_addr" class="mb-0">Jl. Pluit Karang Karya
                                                2 No.33, RT.7/RW.16, Pejagalan,
                                                Kec. Penjaringan, Kota Jkt Utara, Daerah Khusus Ibukota Jakarta 14440</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-2 text-center">
                                    <label for="" class="form-label mb-0 mt-0">&nbsp;</label>
                                    {{-- <p class="mb-0">to</p> --}}
                                    <span class="ion-arrow-right-c text-danger" style="font-size: 15px"></span>
                                </div>
                                <div class="col-5 mb-3">
                                    <label for="" class="form-label">Destination</label>
                                    <div class="card bg-light border mb-0">
                                        <div class="card-body">
                                            <p id="checkout-drop_zone_title" class="text-bold mb-2">Kantor Pusat SiCepat
                                                (yogyakarta)</p>
                                            <p id="checkout-drop_zone_addr" class="mb-0">Jl. Prof. Herman Yohanes
                                                No.989, Terban, Gondokusuman,
                                                Kota Yogyakarta, Daerah Istimewa Yogyakarta 55223, Indonesia</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {{-- <div class="row d-flex align-items-center mb-3">
                                <div class="col-12 mb-3">
                                    <p class="text-danger text-bold mb-0">Informasi Pengiriman</p>
                                </div>
                                <div id="checkout-unit" class="row mb-3">
                                    <div class="col-sm-5">
                                        <label for="" class="form-label">Koli</label>
                                        <div class="card bg-light border mb-0 w-100">
                                            <div class="card-body">
                                                <p class="mb-0">150 Pcs</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-5">
                                    <label for="" class="form-label">Jenis Kendaraan</label>
                                    <div class="card bg-light border mb-0 w-100">
                                        <div class="card-body">
                                            <p id="checkout-truck_type" class="mb-0">Box Truck</p>
                                        </div>
                                    </div>
                                </div>
                            </div> --}}
                            {{-- <div class="row d-flex align-items-center">
                                <div class="col-12 mb-3">
                                    <p class="text-danger text-bold mb-0">Package list</p>
                                </div>
                                <div class="col-sm-12">
                                    <label for="formFile" class="form-label">File Packing List</label>
                                    <div class="d-flex align-items-center mb-3">
                                        <p class="mb-0 text-success me-4">package-list.xlsx</p>
                                        <button id="checkout-download_packing_list"
                                            class="btn btn-sm btn-info">Download</button>
                                    </div>
                                </div>
                            </div> --}}
                            <div class="row d-none">
                                <div class="col-12">
                                    <hr>
                                </div>
                            </div>
                            <div class="row d-flex align-items-center d-none">
                                <div class="col-12 mb-3 mt-3">
                                    <p class="text-danger text-bold mb-0">Pilih Layanan</p>
                                    <small>Berikut layanan yang tersedia untuk pesanan Anda</small>
                                </div>
                                <div class="col-sm-12">
                                    <div class="row mb-3">
                                        <div class="col-12">Durasi Pengantaran</div>
                                    </div>
                                    <div id="checkout-group_pricing">
                                        {{-- <div class="row mb-3 d-flex align-items-center">
                                            <div class="col-10">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="chooseFleet"
                                                        id="chooseFleet1" data-lead_time="1" data-price="2040000">
                                                    <label class="form-check-label text-success" for="chooseFleet1">
                                                        1 Day <span class="badge bg-success ms-2">Best services</span>
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-2 text-end text-bold">
                                                <p class="text-bold m-0 text-success" for="chooseFleet1">Rp2.040.000</p>
                                            </div>
                                        </div>
                                        <div class="row mb-3 d-flex align-items-center">
                                            <div class="col-10">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="chooseFleet"
                                                        id="chooseFleet2" data-lead_time="2" data-price="1740000">
                                                    <label class="form-check-label" for="chooseFleet2">
                                                        2 Days
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-2 text-end text-bold">
                                                <p class="text-bold m-0" for="chooseFleet2">Rp1.740.000</p>
                                            </div>
                                        </div>
                                        <div class="row mb-3 d-flex align-items-center">
                                            <div class="col-10">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="chooseFleet"
                                                        id="chooseFleet3" data-lead_time="4" data-price="740000">
                                                    <label class="form-check-label" for="chooseFleet3">
                                                        4 Days
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-2 text-end text-bold">
                                                <p class="text-bold m-0" for="flexRadioDefault3">Rp740.000</p>
                                            </div>
                                        </div> --}}
                                        <div class="row mb-3 d-flex align-items-center">
                                            <div class="col-6">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="chooseFleet" data-lead_time_id="${opt.lead_time_id}" data-lead_time="${opt.lead_time}" data-price="${opt.price}" data-real_price="${opt.real_price}" data-disc_price="${opt.disc_price}">
                                                    <label class="form-check-label text-success">
                                                        1 Hari <span class="badge bg-success ms-2">Best services</span>
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-6 text-end text-bold">
                                                <p class="text-bold m-0 text-danger"><strike>Rp1.600.000</strike></p>
                                                <p class="text-bold m-0 text-dark">Diskon 10%</p>
                                                <p class="text-bold m-0 text-success">Rp1.440.000</p>
                                            </div>
                                        </div>
                                        <div class="row mb-3 d-flex align-items-center">
                                            <div class="col-6">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="chooseFleet" data-lead_time_id="${opt.lead_time_id}" data-lead_time="${opt.lead_time}" data-price="${opt.price}" data-real_price="${opt.real_price}" data-disc_price="${opt.disc_price}">
                                                    <label class="form-check-label text-dark">
                                                        2 Hari
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-6 text-end text-bold">
                                                <p class="text-bold m-0 text-dark">Rp1.250.000</p>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="row mb-3 d-flex align-items-center">
                                            <div class="col-6">
                                                <p class="mb-0">Biaya Asuransi</p>
                                            </div>
                                            <div class="col-6 text-end text-bold">
                                                <p class="text-bold m-0 text-dark">Rp302.892</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer checkoutBody">
                            <div class="row d-flex align-items-center">
                                <div class="col-8">
                                    <p class="mb-0">
                                        Have you reviewed the job information?
                                    </p>
                                </div>
                                <div class="col-4 text-end">
                                    {{-- <button class="btn btn-danger btn-block btn-sm" id="btnOrder" disabled>Pesan Sekarang</button> --}}
                                    <button class="btn btn-danger btn-block btn-sm" id="btnOrder">Submit</button>
                                    <div id="btnOrderSpinner" class="d-none">
                                        <div class="spinner-border" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('customjs')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.2/xlsx.full.min.js" integrity="sha512-oCjkwxjURabnte5K4Zeoc+hZ/G5pQE7GI4DYl+0wl6WaJIkBjb9FvUIaMU3lOPoBMSRZZ7QrczpGQoBFAKKB1Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
        $("#insuranceCheck").change(function() {
            $("#insurancePrice").toggleClass("d-none")
            if ($("#insurancePrice").hasClass("d-none")) {
                $("#insuranceInput").removeAttr('required')
            } else {
                $("#insuranceInput").prop('required', true);
            }
        })

        $(document).ready(function() {
            setTimeout(function() {
                $('select[name=add-client]').val('1').change();
            }, 100);
        });
    </script>
    <script>
        'use strict';
        const State = {
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            storage_lara: "{{ asset('storage') }}/",
            checked_packing_list: 0, // 0:not, 1:process, 2:valid, 3:fail
            input_packing_list: [],
            weight: 0,
            cbm: 0,
            koli: 0,
            qty: 0,
            delay_typing_fast: 1000,
            discount_type: {
                no: "{{ App\Models\Clients::DISC_TYPE_NO }}",
                fix: "{{ App\Models\Clients::DISC_TYPE_FIX }}",
                percent: "{{ App\Models\Clients::DISC_TYPE_PERCENT }}",
            },
            workflow_type: {
                pickup: "{{ App\Models\Zone::ZONE_WORKFLOW_PICKUP }}",
                drop: "{{ App\Models\Zone::ZONE_WORKFLOW_DEST }}",
            },
            route_list_trx: "{{ $route_list_trx }}",
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                TrxNew.activate();
            },
            event: function() {
                // $('#checkout-group_pricing').on('click', 'input[name=chooseFleet]', function() {
                //     $('#btnOrder').prop("disabled", false);
                // });
                // min date is today
                let TimeISOString = moment().toISOString().split('T');
                let time = TimeISOString[1].split('.')[0].split(':');
                $('#add-pickup_date').attr('min', TimeISOString[0]);
            },
        };

        const Req = {
            check_packing_list: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_user_client_check_packing_list') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data,
                        success: (resp, textStatus, jqXHR) => {
                            if (cb) cb(resp);
                            if (resp.meta.type != 'success') {
                                resolve({
                                    type: 'fail',
                                    msg: resp.meta.message,
                                });
                                if (isAlert) Helper.toast('Warning', 'just now', resp.meta
                                    .message, 'bg-warning', 5000);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: resp,
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            if (cb) cb(jqXHR.responseJSON);
                            if (jqXHR.status >= 500) {
                                if (isAlert) Helper.toast('Error', 'just now',
                                    'please try again', 'bg-warning', 5000);
                            } else {
                                if (isAlert) Helper.toast('Error', 'just now', jqXHR
                                    .responseJSON.meta.message, 'bg-warning', 5000);
                            }
                            resolve({
                                type: 'error',
                                msg: jqXHR.responseJSON.meta.message,
                            });
                        }
                    })
                })
            },
            list_client_zone: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_list_client_zones') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data,
                        success: (resp, textStatus, jqXHR) => {
                            if (cb) cb(resp);
                            if (resp.meta.type != 'success') {
                                resolve({
                                    type: 'fail',
                                    msg: resp.meta.message,
                                });
                                if (isAlert) Helper.toast('Warning', 'just now', resp.meta
                                    .message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: resp,
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            if (cb) cb(jqXHR.responseJSON);
                            if (jqXHR.status >= 500) {
                                if (isAlert) Helper.toast('Error', 'just now',
                                    'please try again');
                            } else {
                                if (isAlert) Helper.toast('Error', 'just now', jqXHR
                                    .responseJSON.meta.message);
                            }
                            resolve({
                                type: 'error',
                                msg: jqXHR.responseJSON.meta.message,
                            });
                        }
                    })
                })
            },
            checkout: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_user_client_checkout_v2') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data,
                        success: (resp, textStatus, jqXHR) => {
                            if (cb) cb(resp);
                            if (resp.meta.type != 'success') {
                                resolve({
                                    type: 'fail',
                                    msg: resp.meta.message,
                                });
                                if (isAlert) Helper.toast('Warning', 'just now', resp.meta
                                    .message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: resp,
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            if (cb) cb(jqXHR.responseJSON);
                            if (jqXHR.status >= 500) {
                                if (isAlert) Helper.toast('Error', 'just now',
                                    'please try again');
                            } else {
                                if (isAlert) Helper.toast('Error', 'just now', jqXHR
                                    .responseJSON.meta.message);
                            }
                            resolve({
                                type: 'error',
                                msg: jqXHR.responseJSON.meta.message,
                            });
                        }
                    })
                })
            },
        }

        const TrxNew = {
            activate: function() {
                TrxNew.event();
            },
            event: function() {
                // button
                $('#btnCalculate').on('click', async function() {
                    // general data
                    let data = TrxNew.getData();
                    TrxNew.showCheckoutSpinner();
                    let isValid = TrxNew.checkData(data, true);
                    if (!isValid) {
                        TrxNew.hideCheckoutSpinner();
                        TrxNew.hideCheckout();
                        return false;
                    }

                    // // start packing list data
                    // let check_packing_list = await Req.check_packing_list({
                    //     packing_list: State.input_packing_list,
                    //     // weight: data.weight,
                    //     // cbm: data.cbm,
                    //     // koli: data.koli,
                    // }, true);
                    // if (check_packing_list.type == 'success') {
                    //     State.checked_packing_list = 2;
                    // } else {
                    //     State.checked_packing_list = 3;
                    //     TrxNew.hideCheckoutSpinner();
                    //     TrxNew.hideCheckout();
                    //     return false;
                    // }
                    // data.weight = check_packing_list.resp.data.calc_weight;
                    // State.weight = data.weight;
                    // data.cbm = check_packing_list.resp.data.calc_cbm;
                    // State.cbm = data.cbm;
                    // data.koli = check_packing_list.resp.data.total_koli;
                    // State.koli = data.koli;
                    // // data.qty = check_packing_list.resp.data.total_qty;
                    // // State.qty = data.qty;
                    // // recheck general data again
                    // isValid = TrxNew.checkData(data, true);
                    // if (!isValid) {
                    //     TrxNew.hideCheckoutSpinner();
                    //     TrxNew.hideCheckout();
                    //     return false;
                    // }
                    // // end packing list data

                    // checkout data
                    let checkoutData = await Req.checkout(data, true);
                    if (checkoutData.type != 'success') {
                        TrxNew.hideCheckoutSpinner();
                        TrxNew.hideCheckout();
                        return false;
                    }
                    data.pricing_options = checkoutData.resp.data;
                    data.insurance = checkoutData.resp.insurance;
                    TrxNew.showCheckout(data);
                    TrxNew.hideCheckoutSpinner();
                });
                $('#btnOrder').on('click', function() {
                    let data = TrxNew.getData();

                    // // start packing list data
                    // data.packing_list = State.input_packing_list;
                    // data.weight = State.weight;
                    // data.cbm = State.cbm;
                    // data.koli = State.koli;
                    // // data.qty = State.qty;
                    // // end packing list data

                    TrxNew.showBtnOrdSpinner();
                    let isValid = TrxNew.checkData(data, true);
                    if (!isValid) {
                        TrxNew.hideBtnOrdSpinner();
                        return false;
                    }
                    TrxNew.submitData(data);

                    // static fe
                    // Helper.toast('Success', 'just now', 'success create order');
                    // window.location.href =
                    //     "{{ route('view_user_client_transaction') }}";
                });
                $('#checkout-download_packing_list').on('click', function() {
                    const fileName = 'package-list.xlsx';
                    const sheetName = 'template_packing_list';
                    downloadPackingList(fileName, sheetName, State.input_packing_list);
                });
                // link
                $('#download_template_packing_list').on('click', function() {
                    TrxNew.downloadTemplatePackingList();
                });
                // input
                TrxNew.evInputChange();
                // select
                $('#add-client').on('change', async function(e) {
                    TrxNew.hideCheckout();
                    let selected = $('#add-client :selected');

                    $('#add-pickup_zone').html('<option value="" selected disabled>No location has been selected.</option>');
                    $('#add-drop_zone').html('<option value="" selected disabled>No location has been selected.</option>');

                    const listPickupZones = await Req.list_client_zone({
                        cptid: selected.data('cptid'),
                        workflow_type: State.workflow_type.pickup,
                    });
                    if (listPickupZones.type != 'success') {
                        Helper.toast('Warning', 'just now', listPickupZones.msg);
                        $('#add-pickup_zone').val(null).trigger('change');
                        $('#add-pickup_zone').select2();
                        $('#add-drop_zone').val(null).trigger('change');
                        $('#add-drop_zone').select2();
                        return false;
                    }
                    for (let pck of listPickupZones.resp.data) {
                        $('#add-pickup_zone').append(`<option value="${pck.id}" data-id="${pck.id}" data-title="${pck.name}" data-addr="${pck.fulladdress}">${pck.name}</option>`);
                    }
                    $('#add-pickup_zone').select2();

                    const listDropZones = await Req.list_client_zone({
                        cptid: selected.data('cptid'),
                        workflow_type: State.workflow_type.drop,
                    });
                    if (listDropZones.type != 'success') {
                        Helper.toast('Warning', 'just now', listDropZones.msg);
                        $('#add-drop_zone').val(null).trigger('change');
                        $('#add-drop_zone').select2();
                        return false;
                    }
                    for (let drop of listDropZones.resp.data) {
                        $('#add-drop_zone').append(`<option value="${drop.id}" data-id="${drop.id}" data-title="${drop.name}" data-addr="${drop.fulladdress}">${drop.name}</option>`);
                    }
                    $('#add-drop_zone').select2();
                });
            },
            evInputChange: function() {
                TrxNew.handleUploadPacking();
                $('#add-pickup_date').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#add-pickup_time').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#add-pickup_zone').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#add-drop_zone').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#add-weight').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#add-cbm').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#add-koli').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#add-truck_type').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#add-packinglist').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#insuranceCheck').on('change', function() {
                    TrxNew.hideCheckout();
                });
                $('#insuranceInput').on('keydown', function() {
                    TrxNew.hideCheckout();
                });
            },
            getData: function() {
                let data = {};

                let clientSelected = $('#add-client :selected');
                data.uid = clientSelected.data('uid');

                data.pickup_date = $('#add-pickup_date').val().trim();
                // data.pickup_time = $('#add-pickup_time').val().trim();
                data.pickup_time_hour = $('#add-pickup_time_hour').val()?.trim();
                data.pickup_time_minute = $('#add-pickup_time_minute').val()?.trim();
                data.pickup_time = `${data.pickup_time_hour}:${data.pickup_time_minute}`;
                data.pickup_at = moment(data.pickup_date + ' ' + data.pickup_time).unix();

                let pickup_zone = $('#add-pickup_zone :selected');
                data.pickup_zone_id = pickup_zone.data('id');
                data.pickup_zone_title = pickup_zone.data('title')?.trim();
                data.pickup_zone_addr = pickup_zone.data('addr')?.trim();
                let drop_zone = $('#add-drop_zone :selected');
                data.drop_zone_id = drop_zone.data('id');
                data.drop_zone_title = drop_zone.data('title')?.trim();
                data.drop_zone_addr = drop_zone.data('addr')?.trim();

                // data.weight = Number($('#add-weight').val() || 'n');
                // data.cbm = Number($('#add-cbm').val() || 'n');
                // data.koli = Number($('#add-koli').val() || 'n');

                let truck_type = $('#add-truck_type :selected');
                data.vehicle_id = truck_type.data('type_id');
                data.vehicle_name = truck_type.data('name')?.trim();

                let driver = $('#add-driver :selected');
                data.driver_id = driver.data('driver_id');
                data.driver_name = driver.data('name')?.trim();
                // data.truck_type_weight = truck_type.data('weight');
                // data.truck_type_cbm = truck_type.data('cbm');
                // data.truck_type_koli = truck_type.data('koli');

                data.is_insurance = $('#insuranceCheck').prop('checked');
                data.amt_beneficiary = $('#insuranceInput').val();
                if ($('#checkout-insurance_value').data('id')) {
                    let insurance = $('#checkout-insurance_value');
                    data.insurance_id = insurance.data('id');
                    data.insurance_price = insurance.data('price');
                }

                for (let chooseFleet of $('input[name="chooseFleet"]')) {
                    if ($(chooseFleet).prop('checked')) {
                        data.lead_time_id = $(chooseFleet).data('lead_time_id');
                        data.lead_time = $(chooseFleet).data('lead_time');
                        data.price = $(chooseFleet).data('price');
                        data.real_price = $(chooseFleet).data('real_price');
                        data.disc_price = $(chooseFleet).data('disc_price');
                    }
                }

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (data.pickup_at < 1 || isNaN(data.pickup_at)) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Date / time not valid');
                    return false;
                }
                if (data.pickup_at < moment().unix()) {
                    if (isAlert) Helper.toast('Warning', 'just now',
                        'Date / time is less than the current date / time');
                    return false;
                }
                // if (data.pickup_at < moment().add(3, 'hours').unix()) {
                if (data.pickup_at < moment().add(5, 'minutes').unix()) {
                    if (isAlert) Helper.toast('Warning', 'just now',
                        'The selected time is too soon. Minimum is 5 minutes from now.');
                    return false;
                }
                if (typeof data.pickup_zone_id == 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Origin zone not valid');
                    return false;
                }
                if (typeof data.drop_zone_id == 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Destination zone not valid');
                    return false;
                }

                // // start packing list data
                // if (isNaN(data.weight) && isNaN(data.cbm) && isNaN(data.koli)) {
                //     if (isAlert) Helper.toast('Warning', 'just now',
                //         'weight / volume / koli must be provided at least 1 of them');
                //     return false;
                // }
                // if (typeof data.vehicle_id != 'undefined') {
                //     if (!isNaN(data.weight) && data.truck_type_weight != 0 && data.weight > data
                //         .truck_type_weight) {
                //         if (isAlert) Helper.toast('Warning', 'just now',
                //             `maximum weight for type truck ${data.vehicle_name} is ${data.truck_type_weight} Kg`
                //         );
                //         return false;
                //     }
                //     if (!isNaN(data.cbm) && data.truck_type_cbm != 0 && data.cbm > data.truck_type_cbm) {
                //         if (isAlert) Helper.toast('Warning', 'just now',
                //             `maximum volume for type truck ${data.vehicle_name} is ${data.truck_type_cbm} m³`
                //         );
                //         return false;
                //     }
                //     if (!isNaN(data.koli) && data.truck_type_koli != 0 && data.koli > data.truck_type_koli) {
                //         if (isAlert) Helper.toast('Warning', 'just now',
                //             `maximum koli for type truck ${data.vehicle_name} is ${data.truck_type_koli} Pcs`
                //         );
                //         return false;
                //     }
                // }
                // if (State.checked_packing_list == 0) {
                //     if (isAlert) Helper.toast('Warning', 'just now', 'You haven\'t upload packing list');
                //     return false;
                // }
                // if (State.checked_packing_list == 1) {
                //     if (isAlert) Helper.toast('Warning', 'just now', 'Packing list in process of checking');
                //     return false;
                // }
                // if (State.checked_packing_list == 3 || State.input_packing_list.length < 1) {
                //     if (isAlert) Helper.toast('Warning', 'just now', 'Packing list not valid');
                //     return false;
                // }
                // // end packing list data

                return true;
            },
            showCheckoutSpinner: function() {
                $('#checkOutView').removeClass('d-none');
                $('#checkOutView').removeClass('d-block');

                $('#checkout-spinner').removeClass('d-none');
                $('.checkoutBody').addClass('d-none');
            },
            hideCheckoutSpinner: function() {
                $('#checkout-spinner').addClass('d-none');
                $('.checkoutBody').removeClass('d-none');
            },
            showCheckout: function(data) {
                $('#checkout-pickup_at').text(moment.unix(data.pickup_at).format('DD MMM YYYY HH:mm:ss'));
                $('#checkout-pickup_zone_title').text(data.pickup_zone_title);
                $('#checkout-pickup_zone_addr').text(data.pickup_zone_addr);
                $('#checkout-drop_zone_title').text(data.drop_zone_title);
                $('#checkout-drop_zone_addr').text(data.drop_zone_addr);

                // // start packing list data
                // $('#checkout-unit').html('');
                // if (!isNaN(data.weight)) {
                //     $('#checkout-unit').append(`
            //         <div class="col-sm-4 mb-0 d-flex align-items-center">
            //             <label for="" class="form-label">Berat</label>
            //             <div class="card bg-light border mb-0 w-100">
            //                 <div class="card-body">
            //                     <p class="mb-0">${data.weight} Kg</p>
            //                 </div>
            //             </div>
            //         </div>
            //     `);
                // }
                // if (!isNaN(data.cbm)) {
                //     $('#checkout-unit').append(`
            //         <div class="col-sm-4 mb-0 d-flex align-items-center">
            //             <label for="" class="form-label">Volume</label>
            //             <div class="card bg-light border mb-0 w-100">
            //                 <div class="card-body">
            //                     <p class="mb-0">${data.cbm} m&sup3;</p>
            //                 </div>
            //             </div>
            //         </div>
            //     `);
                // }
                // if (!isNaN(data.koli)) {
                //     $('#checkout-unit').append(`
            //         <div class="col-sm-4 mb-0 d-flex align-items-center">
            //             <label for="" class="form-label">Koli</label>
            //             <div class="card bg-light border mb-0 w-100">
            //                 <div class="card-body">
            //                     <p class="mb-0">${data.koli} Pcs</p>
            //                 </div>
            //             </div>
            //         </div>
            //     `);
                // }
                // // end packing list data

                $('#checkout-group_pricing').html('');
                for (let opt of data.pricing_options) {
                    let badge_best_service = '',
                        real_price = '',
                        disc_price = '';
                    if (opt.is_best) {
                        badge_best_service = '<span class="badge bg-success ms-2">Best services</span>';
                    }
                    if (opt.disc_type == State.discount_type.fix) {
                        real_price =
                            `<p class="text-bold m-0 text-danger"><strike>Rp${(new Intl.NumberFormat('id-ID')).format(opt.real_price)}</strike></p>`;
                        disc_price =
                            `<p class="text-bold m-0 text-dark">Discount -${(new Intl.NumberFormat('id-ID')).format(opt.disc_price)}</p>`;
                    } else if (opt.disc_type == State.discount_type.percent) {
                        real_price =
                            `<p class="text-bold m-0 text-danger"><strike>Rp${(new Intl.NumberFormat('id-ID')).format(opt.real_price)}</strike></p>`;
                        disc_price =
                            `<p class="text-bold m-0 text-dark">Discount ${(new Intl.NumberFormat('id-ID')).format(opt.disc_percent)}%</p>`;
                    }
                    $('#checkout-group_pricing').append(`
                        <div class="row mb-3 d-flex align-items-center">
                            <div class="col-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="chooseFleet" data-lead_time_id="${opt.lead_time_id}" data-lead_time="${opt.lead_time}" data-price="${opt.price}"
                                    data-real_price="${opt.real_price}" data-disc_price="${opt.disc_price}">
                                    <label class="form-check-label text-success">
                                        ${opt.lead_time} Day ${badge_best_service}
                                    </label>
                                </div>
                            </div>
                            <div class="col-6 text-end text-bold">
                                ${real_price}
                                ${disc_price}
                                <p class="text-bold m-0 text-success">Rp${(new Intl.NumberFormat('id-ID')).format(opt.price)}</p>
                            </div>
                        </div>
                    `);
                }

                if (data.is_insurance) {
                    $('#checkout-group_pricing').append(`
                        <hr>
                        <div class="row mb-3 d-flex align-items-center">
                            <div class="col-6">
                                <p class="mb-0">Biaya Asuransi</p>
                            </div>
                            <div class="col-6 text-end text-bold">
                                <p id="checkout-insurance_value" class="text-bold m-0 text-dark" data-id="${data.insurance.id}" data-price="${data.insurance.premi_price}">Rp${(new Intl.NumberFormat('id-ID')).format(data.insurance.premi_price)}</p>
                            </div>
                        </div>
                    `);
                }

                $('#checkout-truck_type').text(data.vehicle_name);
                console.log("driver:", data.driver_name);
                $('#checkout-driver').text(data.driver_name);

                $('#checkOutView').removeClass('d-none');
                $('#checkOutView').addClass('d-block');
            },
            hideCheckout: function() {
                $('#checkOutView').addClass('d-none');
                $('#checkOutView').removeClass('d-block');
                $('#btnOrder').attr('disabled', false);
            },
            downloadTemplatePackingList: function() {
                const fileName = 'template_packing_list.xlsx';
                const sheetName = 'template_packing_list';
                downloadPackingList(fileName, sheetName);
            },
            handleUploadPacking: function() {
                const reader = new FileReader();
                reader.onload = async function(e) {
                    TrxNew.hideUploadPackingList();
                    State.input_packing_list = [];
                    State.checked_packing_list = 1;

                    // let {
                    //     weight,
                    //     cbm,
                    //     koli,
                    // } = TrxNew.getData();

                    let data = e.target.result;
                    let workbook = XLSX.read(data, {
                        type: 'binary'
                    });
                    let sheet = workbook.Sheets['template_packing_list'];
                    let rowBodyStart = 3;
                    for (let key in sheet) {
                        if (key.indexOf('!') > -1) continue;
                        let rowNumber = Number(key.slice(1));
                        if (rowNumber < 3) continue;
                        if (key.indexOf('A') > -1) {
                            if (!sheet[key].v) {
                                Helper.toast('Warning', 'just now', 'Item Code not valid on row ' +
                                    rowNumber);
                                State.checked_packing_list = 3;
                                State.input_packing_list = [];
                                TrxNew.showUploadPackingList();
                                return false;
                            }
                            State.input_packing_list[rowNumber - rowBodyStart] = {};
                            for (let checkUniqCode of State.input_packing_list) {
                                if (checkUniqCode['Item Code'] == sheet[key].v) {
                                    State.checked_packing_list = 3;
                                    State.input_packing_list = [];
                                    Helper.toast('Warning', 'just now', 'Item Code: ' + sheet[key].v +
                                        ' is not uniq');
                                    TrxNew.showUploadPackingList();
                                    return false;
                                }
                            }
                            State.input_packing_list[rowNumber - rowBodyStart]['Item Code'] = sheet[key].v;
                        }
                        if (key.indexOf('B') > -1) {
                            if (!sheet[key].v) {
                                Helper.toast('Warning', 'just now', 'Description not valid on row' +
                                    rowNumber);
                                State.checked_packing_list = 3;
                                State.input_packing_list = [];
                                TrxNew.showUploadPackingList();
                                return false;
                            }
                            State.input_packing_list[rowNumber - rowBodyStart]['Description'] = sheet[key]
                                .v;
                        }
                        if (key.indexOf('C') > -1) {
                            if (isNaN(Number(sheet[key].v))) {
                                State.checked_packing_list = 3;
                                State.input_packing_list = [];
                                Helper.toast('Warning', 'just now', 'Weight (kg) not numeric on row' +
                                    rowNumber);
                                TrxNew.showUploadPackingList();
                                return false;
                            }
                            State.input_packing_list[rowNumber - rowBodyStart]['Weight (kg)'] = Number(
                                sheet[
                                    key].v);
                        }
                        // if (key.indexOf('D') > -1) {
                        //     if (Number(sheet[key].v) < 1) {
                        //         if (State.input_packing_list[rowNumber - rowBodyStart]['Item Code']
                        //             .toLowerCase()
                        //             .indexOf('note') >
                        //             -1 || State.input_packing_list[rowNumber - rowBodyStart]['Item Code']
                        //             .toLowerCase().indexOf(
                        //                 'catatan') > -1) {} else {
                        //             State.checked_packing_list = 3;
                        //             State.input_packing_list = [];
                        //             Helper.toast('Warning', 'just now',
                        //                 'Qty cannot be 0 minimum qty is 1 on row' + rowNumber);
                        //             TrxNew.showUploadPackingList();
                        //             return false;
                        //         }
                        //     }
                        //     State.input_packing_list[rowNumber - rowBodyStart]['Qty'] = Number(sheet[key]
                        //         .v);
                        // }
                        if (key.indexOf('D') > -1) {
                            if (isNaN(Number(sheet[key].v))) {
                                State.checked_packing_list = 3;
                                State.input_packing_list = [];
                                Helper.toast('Warning', 'just now', 'Length (cm) not numeric on row' +
                                    rowNumber);
                                TrxNew.showUploadPackingList();
                                return false;
                            }
                            State.input_packing_list[rowNumber - rowBodyStart]['Length (cm)'] = Number(
                                sheet[
                                    key].v);
                        }
                        if (key.indexOf('E') > -1) {
                            if (isNaN(Number(sheet[key].v))) {
                                State.checked_packing_list = 3;
                                State.input_packing_list = [];
                                Helper.toast('Warning', 'just now', 'Wide (cm) not numeric on row' +
                                    rowNumber);
                                TrxNew.showUploadPackingList();
                                return false;
                            }
                            State.input_packing_list[rowNumber - rowBodyStart]['Wide (cm)'] = Number(sheet[
                                    key]
                                .v);
                        }
                        if (key.indexOf('F') > -1) {
                            if (isNaN(Number(sheet[key].v))) {
                                State.checked_packing_list = 3;
                                State.input_packing_list = [];
                                Helper.toast('Warning', 'just now', 'Height (cm) not numeric on row' +
                                    rowNumber);
                                TrxNew.showUploadPackingList();
                                return false;
                            }
                            State.input_packing_list[rowNumber - rowBodyStart]['Height (cm)'] = Number(
                                sheet[
                                    key].v);
                        }
                        if (key.indexOf('G') > -1) {
                            if (isNaN(Number(sheet[key].v))) {
                                State.checked_packing_list = 3;
                                State.input_packing_list = [];
                                Helper.toast('Warning', 'just now', 'Volume (m3) not numeric on row' +
                                    rowNumber);
                                TrxNew.showUploadPackingList();
                                return false;
                            }
                            State.input_packing_list[rowNumber - rowBodyStart]['Volume (m3)'] = Number(
                                sheet[
                                    key].v);
                            if (State.input_packing_list[rowNumber - rowBodyStart]['Item Code']
                                .toLowerCase()
                                .indexOf('note') >
                                -1 || State.input_packing_list[rowNumber - rowBodyStart]['Item Code']
                                .toLowerCase().indexOf(
                                    'catatan') > -1) {
                                // rereset array index
                                State.input_packing_list.splice(rowNumber - rowBodyStart);
                                // not rereset array index
                                // State.input_packing_list[rowNumber-rowBodyStart] = undefined;
                            }
                        }
                    }
                    // State.input_packing_list = State.input_packing_list.filter(() => true);
                    let check_packing_list = await Req.check_packing_list({
                        packing_list: State.input_packing_list,
                        // weight,
                        // cbm,
                        // koli,
                    }, true);
                    if (check_packing_list.type == 'success') {
                        State.checked_packing_list = 2;
                    } else {
                        State.checked_packing_list = 3;
                    }
                    TrxNew.showUploadPackingList();
                };
                reader.onerror = function(err) {
                    console.error(err);
                };
                reader.onabort = function(err) {
                    console.error(err);
                };
                $('#add-packinglist').on('change', function(e) {
                    if (browserBack()) {
                        return false;
                    }
                    let file = e.target.files[0];
                    let type = file.name.split('.');
                    if (type[1].indexOf('xlsx') < 0) {
                        Helper.toast('Warning', 'just now',
                            'Format file not supported. Supported format is .xlsx');
                        return false;
                    }
                    // let {
                    //     weight,
                    //     cbm,
                    //     koli,
                    // } = TrxNew.getData();
                    // if (isNaN(weight) && isNaN(cbm) && isNaN(koli)) {
                    //     Helper.toast('Warning', 'just now',
                    //         'weight / volume / koli must be provided at least 1 of them');
                    //     return false;
                    // }
                    reader.readAsBinaryString(file);
                });
                $('#add-packinglist').on('click', function() {
                    $('#add-packinglist').val('');
                });
            },
            hideUploadPackingList: function() {
                $('#add-group_upload_packinglist').addClass('d-none');
                $('#add-group_upload_packinglist_spinner').removeClass('d-none');
            },
            showUploadPackingList: function() {
                $('#add-group_upload_packinglist').removeClass('d-none');
                $('#add-group_upload_packinglist_spinner').addClass('d-none');
            },
            showBtnOrdSpinner: function() {
                $('#btnOrderSpinner').removeClass('d-none');
                $('#btnOrder').addClass('d-none');
            },
            hideBtnOrdSpinner: function() {
                $('#btnOrderSpinner').addClass('d-none');
                $('#btnOrder').removeClass('d-none');
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnOrder').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnOrder').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_user_client_create_order_v2') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            TrxNew.hideBtnOrdSpinner();
                            $('#btnOrder').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success create order');
                            window.location.href = State.route_list_trx;
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            TrxNew.hideBtnOrdSpinner();
                            $('#btnOrder').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'Please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                })
            },
        }

        Wrapper.activate();
    </script>
@endsection
