@extends('app.app')

@section('title')
    Publish Rate & Duration
@endsection

@section('customcss')
    <style>
        /* .select2-container {
            z-index: 99999;
        } */

    </style>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="card">
                <div class="card-header">
                    <div class="row d-flex align-items-center">
                        <div class="col-3">
                            <p class="card-title text-bold mb-0">Rates (<span id="count_rates">0</span>)</p>
                        </div>
                        <div class="col text-end">
                            <button id="btnMdlNewRate" class="btn btn-sm btn-danger">Add New Rates</button>
                        </div>
                        <div class="col-auto text-end ps-0">
                            {{-- <button class="btn btn-sm btn-danger">Upload</button> --}}
                            {{-- <button class="btn btn-sm btn-danger">Download</button> --}}
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="tRates" class="table table-hover dataTable">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center">Action</th>
                                    <th class="">Code</th>
                                    <th class="">Origin</th>
                                    <th class="">Via</th>
                                    <th class="">Dest Province</th>
                                    <th class="">Dest City</th>
                                    <th class="">Dest District</th>
                                    <th class="">Vendor</th>
                                    <th class="">Vehicle</th>
                                    <th class="text-center text-nowrap">Lead Time</th>
                                    <th class="text-end text-nowrap">Sell KG</th>
                                    <th class="text-end text-nowrap">Buy KG</th>
                                    <th class="text-end text-nowrap">Margin</th>
                                    <th class="text-end text-nowrap">Percentage</th>
                                    <th class="text-end text-nowrap">Sell CBM</th>
                                    <th class="text-end text-nowrap">Buy CBM</th>
                                    <th class="text-end text-nowrap">Margin</th>
                                    <th class="text-end text-nowrap">Percentage</th>
                                    <th class="text-end text-nowrap">Sell FTL</th>
                                    <th class="text-end text-nowrap">Buy FTL</th>
                                    <th class="text-end text-nowrap">Margin</th>
                                    <th class="text-end text-nowrap">Percentage</th>
                                    <th class="text-center">Status</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlNewRate"
        aria-labelledby="mdlNewRateLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlNewRateLabel">Add New Rate</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        {{-- Origin --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Origin</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-origin_prov" class="col-form-label">Origin<span class="text-danger">*</span></label>
                                    <select name="add-origin_prov" id="add-origin_prov"
                                        class="form-control" style="width:100%;">
                                        <option value="">Select Origin</option>
                                        @foreach ($provs as $prov)
                                            <option value="{{ $prov->kodeProv }}">
                                                {{ $prov->nmProvinsiKel }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-via" class="col-form-label">Via<span class="text-danger">*</span></label>
                                    <select name="add-via" id="add-via" class="form-control" style="width:100%;">
                                        <option value="">Select Via</option>
                                        @foreach ($lanes as $lane)
                                            <option value="{{ $lane->id }}">
                                                {{ $lane->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        {{-- Dest --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Destination</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-dest_prov" class="col-form-label">Dest Province<span class="text-danger">*</span></label>
                                    <select name="add-dest_prov" id="add-dest_prov" class="form-control" style="width:100%;">
                                        <option value="">Select Dest Province</option>
                                        @foreach ($provs as $prov)
                                            <option value="{{ $prov->kodeProv }}">
                                                {{ $prov->nmProvinsiKel }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-dest_city" class="col-form-label">Dest City<span class="text-danger">*</span></label>
                                    <select name="add-dest_city" id="add-dest_city" class="form-control" style="width:100%;">
                                        <option value="">Select Dest City</option>
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-dest_district" class="col-form-label">Dest District (Optional)</label>
                                    <select name="add-dest_district" id="add-dest_district"
                                        class="form-control" style="width:100%;">
                                        <option value="">Select Dest District</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        {{-- Vendor & Vehicle --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Vendor & Vehicle</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-vendor_id" class="col-form-label">Vendor<span class="text-danger">*</span></label>
                                    <select name="add-vendor_id" id="add-vendor_id" class="form-control" style="width:100%;">
                                        <option value="">Select Vendor</option>
                                        @foreach ($vendors as $vendor)
                                            <option value="{{ $vendor->id }}">
                                                {{ $vendor->first_name . ' (' . $vendor->email . ')' }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-vhc_type" class="col-form-label">Vehicle Type<span class="text-danger">*</span></label>
                                    <select name="add-vhc_type" id="add-vhc_type" class="form-control" style="width:100%;">
                                        <option value="">Select Vehicle Type</option>
                                        @foreach ($truck_types as $truck_type)
                                            <option value="{{ $truck_type->type_id }}">
                                                {{ $truck_type->type_name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        {{-- Time --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Lead Time</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-fast_time" class="col-form-label">Fastest (Day)<span class="text-danger">*</span></label>
                                    <input type="number" name="add-fast_time" id="add-fast_time" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-long_time" class="col-form-label">Longest (Day)<span class="text-danger">*</span></label>
                                    <input type="number" name="add-long_time" id="add-long_time" class="form-control">
                                </div>
                            </div>
                        </div>
                        {{-- Pricing (KG) --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Pricing (Rp) (KG)</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-sell_kg" class="col-form-label">Sell KG (Rp)</label>
                                    <input type="text" name="add-sell_kg" id="add-sell_kg" class="form-control" value="0">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-buy_kg" class="col-form-label">Buy KG (Rp)</label>
                                    <input type="text" name="add-buy_kg" id="add-buy_kg" class="form-control" value="0">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-margin_kg" class="col-form-label">Margin</label>
                                    <input type="text" name="add-margin_kg" id="add-margin_kg" class="form-control" value="0"
                                        readonly>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-percent_kg" class="col-form-label">Percentage</label>
                                    <div class="input-group">
                                        <input type="number" name="add-percent_kg" id="add-percent_kg"
                                            class="form-control" value="0" readonly>
                                        <span class="input-group-text">%</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Pricing (CBM) --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Pricing (Rp) (CBM)</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-sell_cbm" class="col-form-label">Sell CBM (Rp)</label>
                                    <input type="text" name="add-sell_cbm" id="add-sell_cbm" class="form-control" value="0">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-buy_cbm" class="col-form-label">Buy CBM (Rp)</label>
                                    <input type="text" name="add-buy_cbm" id="add-buy_cbm" class="form-control" value="0">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-margin_cbm" class="col-form-label">Margin</label>
                                    <input type="text" name="add-margin_cbm" id="add-margin_cbm" class="form-control" value="0"
                                        readonly>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-percent_cbm" class="col-form-label">Percentage</label>
                                    <div class="input-group">
                                        <input type="number" name="add-percent_cbm" id="add-percent_cbm"
                                            class="form-control" value="0" readonly>
                                        <span class="input-group-text">%</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Pricing (FTL) --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Pricing (Rp) (FTL)</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-sell_ftl" class="col-form-label">Sell FTL (Rp)</label>
                                    <input type="text" name="add-sell_ftl" id="add-sell_ftl" class="form-control" value="0">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-buy_ftl" class="col-form-label">Buy FTL (Rp)</label>
                                    <input type="text" name="add-buy_ftl" id="add-buy_ftl" class="form-control" value="0">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-margin_ftl" class="col-form-label">Margin</label>
                                    <input type="text" name="add-margin_ftl" id="add-margin_ftl" class="form-control" value="0"
                                        readonly>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-percent_ftl" class="col-form-label">Percentage</label>
                                    <div class="input-group">
                                        <input type="number" name="add-percent_ftl" id="add-percent_ftl"
                                            class="form-control" value="0" readonly>
                                        <span class="input-group-text">%</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Utilites --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Utilities</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-status" class="form-label">Status</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="add-status">
                                        <label class="form-check-label" for="add-status"><span class="text-dark"
                                                id="add-txtStatus">Inactive</span></label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitNewRate" type="button" class="btn btn-sm btn-danger">Submit data</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlEdtRate"
        aria-labelledby="mdlEdtRateLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlEdtRateLabel">Edit Rate</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        {{-- Rates --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Rates</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-origin_prov" class="col-form-label">Origin<span class="text-danger">*</span></label>
                                    <select name="updt-origin_prov" id="updt-origin_prov"
                                        class="form-control" style="width:100%;">
                                        <option value="">Select Origin</option>
                                        @foreach ($provs as $prov)
                                            <option value="{{ $prov->kodeProv }}">
                                                {{ $prov->nmProvinsiKel }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-via" class="col-form-label">Via<span class="text-danger">*</span></label>
                                    <select name="updt-via" id="updt-via" class="form-control" style="width:100%;">
                                        <option value="">Select Via</option>
                                        @foreach ($lanes as $lane)
                                            <option value="{{ $lane->id }}">
                                                {{ $lane->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        {{-- Dest --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Destination</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-dest_prov" class="col-form-label">Dest Province<span class="text-danger">*</span></label>
                                    <select name="updt-dest_prov" id="updt-dest_prov" class="form-control" style="width:100%;">
                                        <option value="">Select Dest Province</option>
                                        @foreach ($provs as $prov)
                                            <option value="{{ $prov->kodeProv }}">
                                                {{ $prov->nmProvinsiKel }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-dest_city" class="col-form-label">Dest City<span class="text-danger">*</span></label>
                                    <select name="updt-dest_city" id="updt-dest_city" class="form-control" style="width:100%;">
                                        <option value="">Select Dest City</option>
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-dest_district" class="col-form-label">Dest District (Optional)<span class="text-danger">*</span></label>
                                    <select name="updt-dest_district" id="updt-dest_district"
                                        class="form-control" style="width:100%;">
                                        <option value="">Select Dest District</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        {{-- Vendor & Vehicle --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Vendor & Vehicle</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-vendor_id" class="col-form-label">Vendor<span class="text-danger">*</span></label>
                                    <select name="updt-vendor_id" id="updt-vendor_id" class="form-control" style="width:100%;">
                                        <option value="">Select Vendor</option>
                                        @foreach ($vendors as $vendor)
                                            <option value="{{ $vendor->id }}">
                                                {{ $vendor->first_name . ' (' . $vendor->email . ')' }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-vhc_type" class="col-form-label">Vehicle Type<span class="text-danger">*</span></label>
                                    <select name="updt-vhc_type" id="updt-vhc_type" class="form-control" style="width:100%;">
                                        <option value="">Select Vehicle Type</option>
                                        @foreach ($truck_types as $truck_type)
                                            <option value="{{ $truck_type->type_id }}">
                                                {{ $truck_type->type_name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        {{-- Time --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Lead Time</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-fast_time" class="col-form-label">Fastest (Day)<span class="text-danger">*</span></label>
                                    <input type="number" name="updt-fast_time" id="updt-fast_time" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-long_time" class="col-form-label">Longest (Day)<span class="text-danger">*</span></label>
                                    <input type="number" name="updt-long_time" id="updt-long_time" class="form-control">
                                </div>
                            </div>
                        </div>
                        {{-- Pricing (KG) --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Pricing (Rp) (KG)</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-sell_kg" class="col-form-label">Sell KG (Rp)</label>
                                    <input type="text" name="updt-sell_kg" id="updt-sell_kg" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-buy_kg" class="col-form-label">Buy KG (Rp)</label>
                                    <input type="text" name="updt-buy_kg" id="updt-buy_kg" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-margin_kg" class="col-form-label">Margin</label>
                                    <input type="text" name="updt-margin_kg" id="updt-margin_kg" class="form-control"
                                        readonly>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-percent_kg" class="col-form-label">Percentage</label>
                                    <div class="input-group">
                                        <input type="number" name="updt-percent_kg" id="updt-percent_kg"
                                            class="form-control" readonly>
                                        <span class="input-group-text">%</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Pricing (CBM) --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Pricing (Rp) (CBM)</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-sell_cbm" class="col-form-label">Sell CBM (Rp)</label>
                                    <input type="text" name="updt-sell_cbm" id="updt-sell_cbm" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-buy_cbm" class="col-form-label">Buy CBM (Rp)</label>
                                    <input type="text" name="updt-buy_cbm" id="updt-buy_cbm" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-margin_cbm" class="col-form-label">Margin</label>
                                    <input type="text" name="updt-margin_cbm" id="updt-margin_cbm" class="form-control"
                                        readonly>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-percent_cbm" class="col-form-label">Percentage</label>
                                    <div class="input-group">
                                        <input type="number" name="updt-percent_cbm" id="updt-percent_cbm"
                                            class="form-control" readonly>
                                        <span class="input-group-text">%</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Pricing (FTL) --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Pricing (Rp) (FTL)</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-sell_ftl" class="col-form-label">Sell FTL (Rp)</label>
                                    <input type="text" name="updt-sell_ftl" id="updt-sell_ftl" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-buy_ftl" class="col-form-label">Buy FTL (Rp)</label>
                                    <input type="text" name="updt-buy_ftl" id="updt-buy_ftl" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-margin_ftl" class="col-form-label">Margin</label>
                                    <input type="text" name="updt-margin_ftl" id="updt-margin_ftl" class="form-control"
                                        readonly>
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-percent_ftl" class="col-form-label">Percentage</label>
                                    <div class="input-group">
                                        <input type="number" name="updt-percent_ftl" id="updt-percent_ftl"
                                            class="form-control" readonly>
                                        <span class="input-group-text">%</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Utilites --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Utilities</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-status" class="form-label">Status</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="updt-status">
                                        <label class="form-check-label" for="updt-status"><span class="text-dark"
                                                id="updt-txtStatus">Inactive</span></label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" id="btnDelRate_updt" class="btn btn-sm btn-warning">Delete ?</button>
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitEdtRate" type="button" class="btn btn-sm btn-danger">Update data</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlDelRate"
        aria-labelledby="mdlDelRateLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlDelRateLabel">Delete Rate</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-center">
                        <p class="mb-0">
                            Are you sure want to delete this rate
                            <a href="#" class="text-danger">
                                <span id="del-code"></span>
                            </a>
                        </p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-danger" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitDelRate" type="button" class="btn btn-sm btn-secondary">Yes, delete</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('customjs')
    <script src="{{ asset('assets/js/load-image.all.min.js') }}"></script>
    <script>
        'use strict';
        const State = {
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            storage_lara: "{{ asset('storage') }}/",
            stts_conf: {
                active: "{{ App\Models\ConfRates::IS_ACTIVE }}",
                inactive: "{{ App\Models\ConfRates::IS_INACTIVE }}",
            },
            unit_time: {
                day: "{{ App\Models\ConfRates::UNIT_DAY }}",
            },
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                RNew.activate();
                RUpdt.activate();
                RDel.activate();
            },
            event: function() {
                $('#add-status').bind('change', function() {
                    if ($(this).is(':checked'))
                        $('#add-txtStatus').html('Active')
                    else
                        $('#add-txtStatus').html('Inactive')
                });
                $('#updt-status').bind('change', function() {
                    if ($(this).is(':checked'))
                        $('#updt-txtStatus').html('Active')
                    else
                        $('#updt-txtStatus').html('Inactive')
                });

                $('#add-origin_prov').select2({
                    dropdownParent: $('#mdlNewRate'),
                });
                $('#add-via').select2({
                    dropdownParent: $('#mdlNewRate'),
                });
                $('#add-dest_prov').select2({
                    dropdownParent: $('#mdlNewRate'),
                });
                $('#add-dest_city').select2({
                    dropdownParent: $('#mdlNewRate'),
                });
                $('#add-dest_district').select2({
                    dropdownParent: $('#mdlNewRate'),
                });
                $('#add-vendor_id').select2({
                    dropdownParent: $('#mdlNewRate'),
                });
                $('#add-vhc_type').select2({
                    dropdownParent: $('#mdlNewRate'),
                });

                $('#updt-origin_prov').select2({
                    dropdownParent: $('#mdlEdtRate'),
                });
                $('#updt-via').select2({
                    dropdownParent: $('#mdlEdtRate'),
                });
                $('#updt-dest_prov').select2({
                    dropdownParent: $('#mdlEdtRate'),
                });
                $('#updt-dest_city').select2({
                    dropdownParent: $('#mdlEdtRate'),
                });
                $('#updt-dest_district').select2({
                    dropdownParent: $('#mdlEdtRate'),
                });
                $('#updt-vendor_id').select2({
                    dropdownParent: $('#mdlEdtRate'),
                });
                $('#updt-vhc_type').select2({
                    dropdownParent: $('#mdlEdtRate'),
                });
            },
            calcMargin: function(sell, buy) {
                return (Number(sell) - Number(buy)).toFixed(2);
            },
            calcPercentMargin: function(margin, buy) {
                return ((Number(margin) / Number(buy)) * 100).toFixed(2);
            },
        };

        const Req = {
            list_city: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_region_list_city') }}",
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: 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,
                            });
                        }
                    })
                })
            },
            list_district: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_region_list_district') }}",
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: 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,
                            });
                        }
                    })
                })
            },
            list_village: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_region_list_village') }}",
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: 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 DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tRates').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                $('#tRates').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_conf_list_rates') }}",
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_rates').text(count);
                            }
                            // removeTableSkeletonLoading()
                        },
                    },
                    deferRender: true,
                    columns: [{
                            data: 'DT_RowIndex',
                            className: 'text-end',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'action',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let action = `
									<a href="#" class="text-decoration-none me-1 btnUpdtRate">
										<span class="icon ion-edit fz-16"></span>
									</a>
								`;
                                // <a href="#" class="text-decoration-none text-danger btnDelRate">
                                //     <span class="icon ion-trash-b fz-16"></span>
                                // </a>
                                return action;
                            }
                        },
                        {
                            data: 'code',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-rid', rowData.id);
                                $(td).attr('data-code', rowData.code);
                                $(td).attr('data-origin_prov_name', rowData.origin_prov_name);
                                $(td).attr('data-dest_prov_name', rowData.dest_prov_name);
                                $(td).attr('data-dest_city_name', rowData.dest_city_name);
                            },
                        },
                        {
                            data: 'origin_prov_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'lane_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'dest_prov_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'dest_city_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return data || '-';
                            }
                        },
						{
                            data: 'dest_district_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return data || '-';
                            }
                        },
                        {
                            data: 'vdr_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (!data) {
                                    return '-';
                                }
                                return `${data} (${row.vdr_mail})`;
                            }
                        },
                        {
                            data: 'vhc_type_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (!data) {
                                    return '-';
                                }
                                return data;
                            }
                        },
                        {
                            data: 'fast_time',
                            className: 'text-center text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let unit_time = '';
                                if (row.unit_time == State.unit_time.day) {
                                    unit_time = 'day';
                                }
                                return row.fast_time + ' - ' + row.long_time + ' ' + unit_time;
                            }
                        },
                        {
                            data: 'sell_kg',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'buy_kg',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'margin_kg',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'percent_kg',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return data + '%';
                            }
                        },
                        {
                            data: 'sell_cbm',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'buy_cbm',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'margin_cbm',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'percent_cbm',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return data + '%';
                            }
                        },
                        {
                            data: 'sell_ftl',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'buy_ftl',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'margin_ftl',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (new Intl.NumberFormat('id-ID')).format(data);
                            }
                        },
                        {
                            data: 'percent_ftl',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return data + '%';
                            }
                        },
                        {
                            data: 'is_active',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data == State.stts_conf.active) {
                                    return '<span class="badge rounded-pill bg-success">Active</span>';
                                } else {
                                    return '<span class="badge rounded-pill bg-danger">Inactive</span>';
                                }
                            }
                        },
                    ],
                });
            },
        };

        const RNew = {
            activate: function() {
                RNew.event();
            },
            event: function() {
                // modal
                $('#btnMdlNewRate').on('click', function() {
                    $('#mdlNewRate').modal('show');
                });
                $('#mdlNewRate').on('shown.bs.modal', function() {
                    
                });
                // button
                $('#btnSubmitNewRate').on('click', function() {
                    let data = RNew.getData();
                    RNew.submitData(data);
                });
                // input
                $('#add-dest_prov').on('change', async function(e) {
                    let list_city = await Req.list_city({
                        kodeProv: $('#add-dest_prov').val(),
                    }, true);
                    if (list_city.type == 'success') {
                        $('#add-dest_city').html('<option value="">Select Dest City</option>');
                        for (let city of list_city.resp.data) {
                            $('#add-dest_city').append('<option value="' + city.kodeKab + '">' + city
                                .nmKotamadyaKel + '</option>');
                        }
                    }
                });
                $('#add-dest_city').on('change', async function(e) {
                    let list_district = await Req.list_district({
                        kodeKab: $('#add-dest_city').val(),
                    }, true);
                    if (list_district.type == 'success') {
                        $('#add-dest_district').html('<option value="">Select Dest District</option>');
                        for (let district of list_district.resp.data) {
                            $('#add-dest_district').append('<option value="' + district.kodeKec +
                                '">' + district
                                .nmKecamatanKel + '</option>');
                        }
                    }
                });

                function calcMarginNPercentKg(sell_kg, buy_kg) {
                    let margin = Wrapper.calcMargin(sell_kg, buy_kg);
                    let percent = Wrapper.calcPercentMargin(margin, buy_kg);
                    percent = (isNaN(percent)) ? 0 : percent;
                    $('#add-margin_kg').val((new Intl.NumberFormat('id-ID')).format(margin));
                    $('#add-percent_kg').val(percent);
                }
                let timeoutSellKg = null;
                $('#add-sell_kg').on('keyup', function(e) {
                    let sell_kg = $('#add-sell_kg').val().split('.').join('');
                    let buy_kg = $('#add-buy_kg').val().split('.').join('');
                    $('#add-sell_kg').val((new Intl.NumberFormat('id-ID')).format(sell_kg));
                    clearTimeout(timeoutSellKg);
                    timeoutSellKg = setTimeout(() => {
                        calcMarginNPercentKg(sell_kg, buy_kg);
                    }, State.delay_typing_front);
                });
                let timeoutBuyKg = null;
                $('#add-buy_kg').on('keyup', function(e) {
                    let sell_kg = $('#add-sell_kg').val().split('.').join('');
                    let buy_kg = $('#add-buy_kg').val().split('.').join('');
                    $('#add-buy_kg').val((new Intl.NumberFormat('id-ID')).format(buy_kg));
                    clearTimeout(timeoutBuyKg);
                    timeoutBuyKg = setTimeout(() => {
                        calcMarginNPercentKg(sell_kg, buy_kg);
                    }, State.delay_typing_front);
                });

                function calcMarginNPercentCbm(sell_cbm, buy_cbm) {
                    let margin = Wrapper.calcMargin(sell_cbm, buy_cbm);
                    let percent = Wrapper.calcPercentMargin(margin, buy_cbm);
                    percent = (isNaN(percent)) ? 0 : percent;
                    $('#add-margin_cbm').val((new Intl.NumberFormat('id-ID')).format(margin));
                    $('#add-percent_cbm').val(percent);
                }
                let timeoutSellCbm = null;
                $('#add-sell_cbm').on('keyup', function(e) {
                    let sell_cbm = $('#add-sell_cbm').val().split('.').join('');
                    let buy_cbm = $('#add-buy_cbm').val().split('.').join('');
                    $('#add-sell_cbm').val((new Intl.NumberFormat('id-ID')).format(sell_cbm));
                    clearTimeout(timeoutSellCbm);
                    timeoutSellCbm = setTimeout(() => {
                        calcMarginNPercentCbm(sell_cbm, buy_cbm);
                    }, State.delay_typing_front);
                });
                let timeoutBuyCbm = null;
                $('#add-buy_cbm').on('keyup', function(e) {
                    let sell_cbm = $('#add-sell_cbm').val().split('.').join('');
                    let buy_cbm = $('#add-buy_cbm').val().split('.').join('');
                    $('#add-buy_cbm').val((new Intl.NumberFormat('id-ID')).format(buy_cbm));
                    clearTimeout(timeoutBuyCbm);
                    timeoutBuyCbm = setTimeout(() => {
                        calcMarginNPercentCbm(sell_cbm, buy_cbm);
                    }, State.delay_typing_front);
                });

                function calcMarginNPercentFtl(sell_ftl, buy_ftl) {
                    let margin = Wrapper.calcMargin(sell_ftl, buy_ftl);
                    let percent = Wrapper.calcPercentMargin(margin, buy_ftl);
                    percent = (isNaN(percent)) ? 0 : percent;
                    $('#add-margin_ftl').val((new Intl.NumberFormat('id-ID')).format(margin));
                    $('#add-percent_ftl').val(percent);
                }
                let timeoutSellFtl = null;
                $('#add-sell_ftl').on('keyup', function(e) {
                    let sell_ftl = $('#add-sell_ftl').val().split('.').join('');
                    let buy_ftl = $('#add-buy_ftl').val().split('.').join('');
                    $('#add-sell_ftl').val((new Intl.NumberFormat('id-ID')).format(sell_ftl));
                    clearTimeout(timeoutSellFtl);
                    timeoutSellFtl = setTimeout(() => {
                        calcMarginNPercentFtl(sell_ftl, buy_ftl);
                    }, State.delay_typing_front);
                });
                let timeoutBuyFtl = null;
                $('#add-buy_ftl').on('keyup', function(e) {
                    let sell_ftl = $('#add-sell_ftl').val().split('.').join('');
                    let buy_ftl = $('#add-buy_ftl').val().split('.').join('');
                    $('#add-buy_ftl').val((new Intl.NumberFormat('id-ID')).format(buy_ftl));
                    clearTimeout(timeoutBuyFtl);
                    timeoutBuyFtl = setTimeout(() => {
                        calcMarginNPercentFtl(sell_ftl, buy_ftl);
                    }, State.delay_typing_front);
                });
            },
            getData: function() {
                let data = {};
                data.origin_prov = $('#add-origin_prov').val();
                data.via = $('#add-via').val();
                data.dest_prov = $('#add-dest_prov').val();
                data.dest_city = $('#add-dest_city').val();
                data.dest_district = $('#add-dest_district').val();

                data.vendor_id = $('#add-vendor_id').val();
                data.vhc_type_id = $('#add-vhc_type').val();

                data.fast_time = $('#add-fast_time').val();
                data.long_time = $('#add-long_time').val();

                data.sell_kg = $('#add-sell_kg').val().split('.').join('');
                data.buy_kg = $('#add-buy_kg').val().split('.').join('');
                data.margin_kg = $('#add-margin_kg').val().split('.').join('');
                data.percent_kg = $('#add-percent_kg').val();

                data.sell_cbm = $('#add-sell_cbm').val().split('.').join('');
                data.buy_cbm = $('#add-buy_cbm').val().split('.').join('');
                data.margin_cbm = $('#add-margin_cbm').val().split('.').join('');
                data.percent_cbm = $('#add-percent_cbm').val();

                data.sell_ftl = $('#add-sell_ftl').val().split('.').join('');
                data.buy_ftl = $('#add-buy_ftl').val().split('.').join('');
                data.margin_ftl = $('#add-margin_ftl').val().split('.').join('');
                data.percent_ftl = $('#add-percent_ftl').val();

                if ($('#add-status').prop('checked')) {
                    data.status = State.stts_conf.active;
                } else {
                    data.status = State.stts_conf.inactive;
                }

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitNewRate').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitNewRate').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_conf_add_rate') }}",
                        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) => {
                            $('#btnSubmitNewRate').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 add new rate');
                            $('#mdlNewRate').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitNewRate').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'
                            });
                        }
                    })
                })
            },
        }

        const RUpdt = {
            activate: function() {
                RUpdt.event();
            },
            event: function() {
                // modal
                $('#tRates').on('click', '.btnUpdtRate', async function(e) {
                    let rid = $(e.target).closest('tr').find('td[data-rid]').data('rid');
                    let resp = await RUpdt.reqData({
                        rid
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Rate Not Found', 'just now', 'please try again');
                        return false;
                    }
                    RUpdt.passDataToView(resp.data);
                });
                $('#mdlEdtRate').on('shown.bs.modal', function() {
                    
                });
                // button
                $('#btnSubmitEdtRate').on('click', function() {
                    let data = RUpdt.getData();
                    RUpdt.submitData(data);
                });
                // input
                $('#updt-dest_prov').on('change', async function(e) {
                    let list_city = await Req.list_city({
                        kodeProv: $('#updt-dest_prov').val(),
                    }, true);
                    if (list_city.type == 'success') {
                        $('#updt-dest_city').html('<option value="">Select Dest City</option>');
                        for (let city of list_city.resp.data) {
                            $('#updt-dest_city').append('<option value="' + city.kodeKab + '">' + city
                                .nmKotamadyaKel + '</option>');
                        }
                    }
                });
                $('#updt-dest_city').on('change', async function(e) {
                    let list_district = await Req.list_district({
                        kodeKab: $('#updt-dest_city').val(),
                    }, true);
                    if (list_district.type == 'success') {
                        $('#updt-dest_district').html('<option value="">Select Dest District</option>');
                        for (let district of list_district.resp.data) {
                            $('#updt-dest_district').append('<option value="' + district.kodeKec +
                                '">' + district
                                .nmKecamatanKel + '</option>');
                        }
                    }
                });

                function calcMarginNPercentKg(sell_kg, buy_kg) {
                    let margin = Wrapper.calcMargin(sell_kg, buy_kg);
                    let percent = Wrapper.calcPercentMargin(margin, buy_kg);
                    percent = (isNaN(percent)) ? 0 : percent;
                    $('#updt-margin_kg').val((new Intl.NumberFormat('id-ID')).format(margin));
                    $('#updt-percent_kg').val(percent);
                }
                let timeoutSellKg = null;
                $('#updt-sell_kg').on('keyup', function(e) {
                    let sell_kg = $('#updt-sell_kg').val().split('.').join('');
                    let buy_kg = $('#updt-buy_kg').val().split('.').join('');
                    $('#updt-sell_kg').val((new Intl.NumberFormat('id-ID')).format(sell_kg));
                    clearTimeout(timeoutSellKg);
                    timeoutSellKg = setTimeout(() => {
                        calcMarginNPercentKg(sell_kg, buy_kg);
                    }, State.delay_typing_front);
                });
                let timeoutBuyKg = null;
                $('#updt-buy_kg').on('keyup', function(e) {
                    let sell_kg = $('#updt-sell_kg').val().split('.').join('');
                    let buy_kg = $('#updt-buy_kg').val().split('.').join('');
                    $('#updt-buy_kg').val((new Intl.NumberFormat('id-ID')).format(buy_kg));
                    clearTimeout(timeoutBuyKg);
                    timeoutBuyKg = setTimeout(() => {
                        calcMarginNPercentKg(sell_kg, buy_kg);
                    }, State.delay_typing_front);
                });

                function calcMarginNPercentCbm(sell_cbm, buy_cbm) {
                    let margin = Wrapper.calcMargin(sell_cbm, buy_cbm);
                    let percent = Wrapper.calcPercentMargin(margin, buy_cbm);
                    percent = (isNaN(percent)) ? 0 : percent;
                    $('#updt-margin_cbm').val((new Intl.NumberFormat('id-ID')).format(margin));
                    $('#updt-percent_cbm').val(percent);
                }
                let timeoutSellCbm = null;
                $('#updt-sell_cbm').on('keyup', function(e) {
                    let sell_cbm = $('#updt-sell_cbm').val().split('.').join('');
                    let buy_cbm = $('#updt-buy_cbm').val().split('.').join('');
                    $('#updt-sell_cbm').val((new Intl.NumberFormat('id-ID')).format(sell_cbm));
                    clearTimeout(timeoutSellCbm);
                    timeoutSellCbm = setTimeout(() => {
                        calcMarginNPercentCbm(sell_cbm, buy_cbm);
                    }, State.delay_typing_front);
                });
                let timeoutBuyCbm = null;
                $('#updt-buy_cbm').on('keyup', function(e) {
                    let sell_cbm = $('#updt-sell_cbm').val().split('.').join('');
                    let buy_cbm = $('#updt-buy_cbm').val().split('.').join('');
                    $('#updt-buy_cbm').val((new Intl.NumberFormat('id-ID')).format(buy_cbm));
                    clearTimeout(timeoutBuyCbm);
                    timeoutBuyCbm = setTimeout(() => {
                        calcMarginNPercentCbm(sell_cbm, buy_cbm);
                    }, State.delay_typing_front);
                });

                function calcMarginNPercentFtl(sell_ftl, buy_ftl) {
                    let margin = Wrapper.calcMargin(sell_ftl, buy_ftl);
                    let percent = Wrapper.calcPercentMargin(margin, buy_ftl);
                    percent = (isNaN(percent)) ? 0 : percent;
                    $('#updt-margin_ftl').val((new Intl.NumberFormat('id-ID')).format(margin));
                    $('#updt-percent_ftl').val(percent);
                }
                let timeoutSellFtl = null;
                $('#updt-sell_ftl').on('keyup', function(e) {
                    let sell_ftl = $('#updt-sell_ftl').val().split('.').join('');
                    let buy_ftl = $('#updt-buy_ftl').val().split('.').join('');
                    $('#updt-sell_ftl').val((new Intl.NumberFormat('id-ID')).format(sell_ftl));
                    clearTimeout(timeoutSellFtl);
                    timeoutSellFtl = setTimeout(() => {
                        calcMarginNPercentFtl(sell_ftl, buy_ftl);
                    }, State.delay_typing_front);
                });
                let timeoutBuyFtl = null;
                $('#updt-buy_ftl').on('keyup', function(e) {
                    let sell_ftl = $('#updt-sell_ftl').val().split('.').join('');
                    let buy_ftl = $('#updt-buy_ftl').val().split('.').join('');
                    $('#updt-buy_ftl').val((new Intl.NumberFormat('id-ID')).format(buy_ftl));
                    clearTimeout(timeoutBuyFtl);
                    timeoutBuyFtl = setTimeout(() => {
                        calcMarginNPercentFtl(sell_ftl, buy_ftl);
                    }, State.delay_typing_front);
                });
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_conf_show_rate', '') }}/" + params.rid,
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        data: params,
                        success: (data, textStatus, jqXHR) => {
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                data: data.data
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            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'
                            });
                        }
                    })
                });
            },
            passDataToView: async function(data) {
                $('#updt-origin_prov').val(data.origin_prov).trigger('change');
                $('#updt-via').val(data.lane).trigger('change');
                $('#updt-dest_prov').val(data.dest_prov).trigger('change');

                // $('#updt-dest_city').html('<option value="">Select Dest City</option>');
                // $('#updt-dest_city').append(`<option value="${data.dest_city}" selected>${data.dest_city_name}</option>`).trigger('change');
                let list_city = await Req.list_city({
                    kodeProv: $('#updt-dest_prov').val(),
                }, true);
                if (list_city.type == 'success') {
                    $('#updt-dest_city').html('<option value="">Select Dest City</option>');
                    for (let city of list_city.resp.data) {
                        $('#updt-dest_city').append('<option value="' + city.kodeKab + '">' + city
                            .nmKotamadyaKel + '</option>');
                    }
                }
                $('#updt-dest_city').val(data.dest_city).trigger('change');

                let list_district = await Req.list_district({
                    kodeKab: $('#updt-dest_city').val(),
                }, true);
                if (list_district.type == 'success') {
                    $('#updt-dest_district').html('<option value="">Select Dest District</option>');
                    for (let district of list_district.resp.data) {
                        $('#updt-dest_district').append('<option value="' + district.kodeKec +
                            '">' + district
                            .nmKecamatanKel + '</option>');
                    }
                }
                $('#updt-dest_district').val(data.dest_district).trigger('change');

                $('#updt-vendor_id').val(data.vdr_id).trigger('change');
                $('#updt-vhc_type').val(data.vhc_type).trigger('change');

                $('#updt-fast_time').val(data.fast_time);
                $('#updt-long_time').val(data.long_time);

                $('#updt-sell_kg').val((new Intl.NumberFormat('id-ID')).format(data.sell_kg));
                $('#updt-buy_kg').val((new Intl.NumberFormat('id-ID')).format(data.buy_kg));
                $('#updt-margin_kg').val((new Intl.NumberFormat('id-ID')).format(data.margin_kg));
                $('#updt-percent_kg').val(data.percent_kg);

                $('#updt-sell_cbm').val((new Intl.NumberFormat('id-ID')).format(data.sell_cbm));
                $('#updt-buy_cbm').val((new Intl.NumberFormat('id-ID')).format(data.buy_cbm));
                $('#updt-margin_cbm').val((new Intl.NumberFormat('id-ID')).format(data.margin_cbm));
                $('#updt-percent_cbm').val(data.percent_cbm);

                $('#updt-sell_ftl').val((new Intl.NumberFormat('id-ID')).format(data.sell_ftl));
                $('#updt-buy_ftl').val((new Intl.NumberFormat('id-ID')).format(data.buy_ftl));
                $('#updt-margin_ftl').val((new Intl.NumberFormat('id-ID')).format(data.margin_ftl));
                $('#updt-percent_ftl').val(data.percent_ftl);

                if (data.is_active == State.stts_conf.active) {
                    $('#updt-status').prop('checked', true);
                } else {
                    $('#updt-status').prop('checked', false);
                }

                $('#mdlEdtRate').data('id', data.id);
                $('#mdlEdtRate').modal('show');
            },
            getData: function() {
                let data = {};
                data.rid = $('#mdlEdtRate').data('id');

                data.origin_prov = $('#updt-origin_prov').val();
                data.via = $('#updt-via').val();
                data.dest_prov = $('#updt-dest_prov').val();
                data.dest_city = $('#updt-dest_city').val();
                data.dest_district = $('#updt-dest_district').val();

                data.vendor_id = $('#updt-vendor_id').val();
                data.vhc_type_id = $('#updt-vhc_type').val();

                data.fast_time = $('#updt-fast_time').val();
                data.long_time = $('#updt-long_time').val();

                data.sell_kg = $('#updt-sell_kg').val().split('.').join('');
                data.buy_kg = $('#updt-buy_kg').val().split('.').join('');
                data.margin_kg = $('#updt-margin_kg').val().split('.').join('');
                data.percent_kg = $('#updt-percent_kg').val();

                data.sell_cbm = $('#updt-sell_cbm').val().split('.').join('');
                data.buy_cbm = $('#updt-buy_cbm').val().split('.').join('');
                data.margin_cbm = $('#updt-margin_cbm').val().split('.').join('');
                data.percent_cbm = $('#updt-percent_cbm').val();

                data.sell_ftl = $('#updt-sell_ftl').val().split('.').join('');
                data.buy_ftl = $('#updt-buy_ftl').val().split('.').join('');
                data.margin_ftl = $('#updt-margin_ftl').val().split('.').join('');
                data.percent_ftl = $('#updt-percent_ftl').val();

                if ($('#updt-status').prop('checked')) {
                    data.status = State.stts_conf.active;
                } else {
                    data.status = State.stts_conf.inactive;
                }

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitEdtRate').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitEdtRate').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_conf_edit_rate', '') }}/" + data.rid,
                        method: 'PUT',
                        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) => {
                            $('#btnSubmitEdtRate').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 update rate');
                            $('#mdlEdtRate').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitEdtRate').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'
                            });
                        }
                    })
                })
            },
        }

        const RDel = {
            activate: function() {
                RDel.event();
            },
            event: function() {
                // on table
                $('#tRates').on('click', '.btnDelRate', function(e) {
                    let row = $(e.target).closest('tr');
                    let rid = row.find('td[data-rid]').data('rid');
                    let code = row.find('td[data-code]').data('code');
                    RDel.passDataToView({
                        rid,
                        code,
                    });
                    $('#mdlDelRate').data('id', rid);
                    $('#mdlDelRate').modal('show');
                });
                $('#btnSubmitDelRate').on('click', function() {
                    let data = {
                        rid: $('#mdlDelRate').data('id'),
                    };
                    RDel.submitData(data);
                });
                // on modal update
                $('#btnDelRate_updt').on('click', function (e) {
                    let data = RUpdt.getData();
                    RDel.passDataToView({
                        rid: data.rid,
                        code: '',
                    });
                    $('#mdlDelRate').data('id', data.rid);
                    $('#mdlDelRate').modal('show');
                });
            },
            passDataToView: function(data) {
                $('#del-code').text(data.code);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelRate').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelRate').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_conf_del_rate', '') }}/" + data.rid,
                        method: 'DELETE',
                        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) => {
                            $('#btnSubmitDelRate').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 delete rate');
                            $('#mdlDelRate').modal('hide');
                            $('#mdlEdtRate').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelRate').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
