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

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="row">
                <div class="col-sm-6" id="">
                    <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">Detail Job</p>
                                </div>
                                <div class="col text-end">
                                    <button class="btn btn-secondary btn-sm" onclick="location.href='{{ route('view_transactions') }}'">Kembali</button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body pb-0">
                            {{-- <div class="row d-flex align-items-center"> --}}
                            <div class="row d-flex">
                                <div class="col-5 mb-3">
                                    <div class="row">
                                        {{-- <div class="col-sm-12 mb-3">
                                            <p class="text-danger text-bold mb-0">Penjemputan dan Pengantaran</p>
                                        </div> --}}
                                        <div class="col-sm-12 mb-3">
                                            <label for="" class="form-label">Date</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="mb-0"><span id="view-pickup_date_at"></span></p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-12 mb-3">
                                            <label for="" class="form-label">Time</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="mb-0"><span id="view-pickup_time_at"></span></p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-2"></div>
                                <div class="col-sm-5 mb-3">
                                    <div class="row">
                                        {{-- <div class="col-sm-12 col-12 mb-3">
                                            <p class="text-danger text-bold mb-0">Layanan Yang Dipilih</p>
                                        </div> --}}
                                        {{-- <div class="col-sm-12 col-6 mb-3">
                                            <label for="" class="form-label">Durasi Pengantaran</label>
                                            <div class="card bg-light border mb-0 w-100">
                                                <div class="card-body d-flex justify-content-between">
                                                    <p class="mb-0">{{ $order->lead_time }} Hari</p>
                                                    <p class="mb-0">
                                                        Rp{{ number_format($order->price, 0, ',', '.') }}
                                                    </p>
                                                </div>
                                            </div>
                                        </div> --}}
                                        <div class="col-sm-12 col-6 mb-3">
                                            <label for="" class="form-label">Vehicle</label>
                                            <div class="card bg-light border mb-0 w-100">
                                                <div class="card-body d-flex justify-content-between">
                                                    <p class="mb-0">{{ $order->prefer_truck_type_name }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row mb-3 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 class="text-bold mb-2">Gudang Pluit SiCepat (Jakarta)</p> --}}
                                            <p class="text-bold mb-2">{{ $order->pck_name }}</p>
                                            {{-- <p 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> --}}
                                            <p class="mb-0">{{ $order->pck_addr }}</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 class="text-bold mb-2">Kantor Pusat SiCepat (yogyakarta)</p> --}}
                                            <p class="text-bold mb-2">{{ $order->drop_name }}</p>
                                            {{-- <p class="mb-0">Jl. Prof. Herman Yohanes No.989, Terban, Gondokusuman, Kota Yogyakarta, Daerah Istimewa Yogyakarta 55223, Indonesia</p> --}}
                                            <p class="mb-0">{{ $order->drop_addr }}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                {{-- <div class="col-sm-6">
                    <div class="card">
                        <div class="card-body">
                            <div class="col-12 mb-3">
                                <p class="text-danger text-bold mb-0">Pilih Vendor Langsung</p>
                            </div>
                            <div class="col-sm-5 mb-3">
                                <label for="" class="form-label">Pilih Vendor</label>
                                <select name="inputChooseVendor" id="inputChooseVendor" class="select2 form-contro">
                                    <option value="none" selected disabled>Belum ada vendor yang dipilih</option>
                                    @foreach ($vendors as $vdr)
                                        <option value="{{ $vdr->vdr_id }}">{{ $vdr->first_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="text-end">
                                <button id="btnChooseVendor" class="btn btn-danger btn-sm">Pilih</button>
                                <div id="group_btnChooseVdrSpinner" class="d-none">
                                    <div class="spinner-border" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div> --}}
            </div>
        </div>
    </div>
@endsection

@section('customcss')
    <link rel="stylesheet" href="{{ asset('assets/vendor/Tiny-Vertical-Timeline-Plugin-with-jQuery-jQuery-UI/src/jquery.timeline.css') }}">
    <link rel="stylesheet" href="{{ asset('assets/vendor/leaflet-1.7.1/leaflet.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css" integrity="sha512-gc3xjCmIy673V6MyOAZhIW93xhM9ei1I+gLbmFjUHIjocENRsLX/QUE1htk5q1XV2D/iie/VQ8DXI6Vu8bexvQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        #mapsOrder {
            height: 50vh;
            border-radius: 8px
        }

        /* .leaflet-control-container .leaflet-left {
                                                                                                                    display: none;
                                                                                                                } */

        .leaflet-left .leaflet-draw-edit-remove {
            display: none;
        }
    </style>
@endsection

@section('customjs')
    <script src="{{ asset('assets/vendor/leaflet-1.7.1/leaflet-src.js') }}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js" integrity="sha512-ozq8xQKq6urvuU6jNgkfqAmT7jKN2XumbrX1JiB3TnF7tI48DPI4Gy1GXKD/V3EExgAs1V+pRO7vwtS1LHg0Gw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.jsdelivr.net/npm/leaflet-rotatedmarker@0.2.0/leaflet.rotatedMarker.min.js"></script>
    <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>
        // var map = L.map('mapsOrder').setView([-6.129036246308229, 106.78219675441427], 14);
        // // var Leaflet.map = L.map('mapsOrder').setView([-7.1451449, 109.9776078], 8);
        // L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
        //     attribution: 'Map data &copy; <a href="https://www.mapbox.com/feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
        //     // maxZoom: 20,
        //     // minZoom: 4,
        //     id: 'mapbox/streets-v11',
        //     tileSize: 512,
        //     zoomOffset: -1,
        //     accessToken: 'pk.eyJ1IjoibWV1c2luZmlybWFyeSIsImEiOiJja3lsd2xveDAydGhqMnVxaHJsZ2ZncG8yIn0.f7MJAyawHUdCegw7sWjrww',
        // }).addTo(map);

        // L.control.scale({
        //     position: 'bottomright'
        // }).addTo(map);

        // L.control.zoom({
        //     position: 'bottomright'
        // }).addTo(map);

        // var start = L.icon({
        //     iconUrl: "{{ asset('images/start.png') }}",
        //     iconSize: [30, 30],
        //     iconAnchor: [15, 15]
        // })

        // L.marker([-6.129036246308229, 106.78219675441427], {
        //     icon: start
        // }).addTo(map)

        // var Icon = L.icon({
        //     iconUrl: "{{ asset('images/2active.png') }}",
        //     iconSize: [30, 30],
        //     iconAnchor: [15, 15]
        // })

        // var circle = L.circle([-6.129036246308229, 106.78219675441427], {
        //     color: '#f26e6f',
        //     fillColor: '#f26e6f',
        //     fillOpacity: 0.25,
        //     radius: 2000
        // }).addTo(map);

        // var locations = [
        //     ["LOCATION_1", -6.121867602926203, 106.77043796424864],
        //     ["LOCATION_2", -6.130444326603234, 106.78245426001234],
        //     ["LOCATION_3", -6.132321800548507, 106.7950284564011],
        //     ["LOCATION_4", -6.1342419366973875, 106.77206874715978],
        //     ["LOCATION_5", -6.116491079013063, 106.78417087375102],
        //     ["LOCATION_6", -6.166285127910627, 106.78587951080148],
        //     ["LOCATION_7", -6.12234047404046, 106.74981074080921],
        //     ["LOCATION_8", -6.153648565612386, 106.72336031035826]
        // ];

        // for (var i = 0; i < locations.length; i++) {
        //     marker = new L.marker([locations[i][1], locations[i][2]], {
        //             icon: Icon
        //         })
        //         .bindPopup(locations[i][0])
        //         .addTo(map);
        // }
    </script>
    <script>
        'use strict'

        const State = {
            ord_id: "{{ $order->ord_id }}",
            set_pck_at: "{{ $order->set_pck_at }}",
            ord_confirm_at: "{{ $order->confirm_at }}",
            boundary_type: {
                circle: "{{ App\Models\Zone::ZONE_BOUNDARY_CIRCLE }}",
                polygon: "{{ App\Models\Zone::ZONE_BOUNDARY_POLYGON }}",
                rectangle: "{{ App\Models\Zone::ZONE_BOUNDARY_RECTANGLE }}",
            },
            boundary_type_choose: "{{ App\Models\Zone::ZONE_BOUNDARY_CIRCLE }}",

            boundary_radius: 2000, // in meters. only circle
            boundary_bounds: null, // {northEast:{lat,lng},southWest:{lat,lng}}. only polygon,rectangle
            default_boundary_hex: '#f26e6f',
            stts_engine: {
                idling: "{{ App\Models\Tracks::STTS_EN_IDLING }}",
                moving: "{{ App\Models\Tracks::STTS_EN_MOVING }}",
                stoping: "{{ App\Models\Tracks::STTS_EN_STOPING }}",
            },
            eventRemoveToolbarDraw: null,
            eventRemoveListTrucks: null,
        };

        const Icon = {
            vhcMoveIcon: function() {
                return L.icon({
                    iconUrl: "{{ asset('images/2active.png') }}",
                    iconSize: [30, 30],
                    iconAnchor: [15, 28], // lb, rt, bottom, rb. Positive
                    popupAnchor: [-3, -35],
                    // shadowUrl: 'my-icon-shadow.png',
                    // shadowSize: [68, 95],
                    // shadowAnchor: [22, 94]
                });
            },
            vhcIdleIcon: function() {
                return L.icon({
                    iconUrl: "{{ asset('images/2idle.png') }}",
                    iconSize: [30, 30],
                    iconAnchor: [15, 28], // lb, rt, bottom, rb. Positive
                    popupAnchor: [-3, -35],
                    // shadowUrl: 'my-icon-shadow.png',
                    // shadowSize: [68, 95],
                    // shadowAnchor: [22, 94]
                });
            },
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                OrdView.activate();
                if (State.ord_confirm_at == 0) {
                    Leaflet.activate();
                    OrdSearch.activate();
                };
                OrdChoose.activate();
            },
            event: function() {
                $('#view-pickup_at').text(moment.unix(State.set_pck_at).format('DD MMM YYYY HH:mm:ss'));
                $('#view-pickup_date_at').text(moment.unix(State.set_pck_at).format('DD MMM YYYY'));
                $('#view-pickup_time_at').text(moment.unix(State.set_pck_at).format('HH:mm:ss'));
            },
        };

        const OrdView = {
            activate: function() {
                OrdView.event();
            },
            event: function() {
                $('#btnDownloadPacking').on('click', async function(e) {
                    let click = $(e.target);
                    let ord_id = click.data('ord_id');
                    let packing_list = await OrdView.reqPackingList({
                        ord_id
                    });
                    if (packing_list.type != 'success') {
                        return false;
                    }
                    let package_list = packing_list.resp.data;
                    let download_package_list = package_list.map((row) => {
                        return {
                            'Item Code': row.item_code,
                            'Description': row.desc,
                            'Weight (kg)': row.weight,
                            'Qty': row.qty,
                            'Length (m)': row.length,
                            'Wide (m)': row.wide,
                            'Height (m)': row.height,
                            'Volume (m3)': row.volume,
                        };
                    });
                    downloadPackingList('package-list.xlsx', 'template_packing_list',
                        download_package_list);
                });
            },
            reqPackingList: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_download_package_list', '') }}/" + params
                            .ord_id,
                        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',
                                resp: 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'
                            });
                        }
                    })
                });
            },
        };

        const Leaflet = {
            map: null,
            activate: function() {
                // centering java archipelago => .setView([-7.1451449, 109.9776078], 6.5);
                // centering indonesia country => .setView([-1.38116, 117.6168817], 5.4);
                Leaflet.map = L.map('mapsOrder').setView([-7.1451449, 109.9776078], 6.5);
                L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
                    attribution: 'Map data &copy; <a href="https://www.mapbox.com/feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                    maxZoom: 20,
                    minZoom: 4,
                    id: 'mapbox/streets-v11',
                    tileSize: 512,
                    zoomOffset: -1,
                    accessToken: 'pk.eyJ1IjoibWV1c2luZmlybWFyeSIsImEiOiJja3lsd2xveDAydGhqMnVxaHJsZ2ZncG8yIn0.f7MJAyawHUdCegw7sWjrww',
                }).addTo(Leaflet.map);
                Leaflet.events();
            },
            events: function() {},
            addMarkers: function(locs = [], cb = null) {
                if (locs.constructor === Array) {
                    let markers = [];
                    for (let i = 0; i < locs.length; i++) {
                        let label = locs[i]?.label || '';
                        let marker = new L.marker([locs[i].lat, locs[i].lng], locs[i]?.options);
                        let popup = new L.Popup({
                            autoClose: false,
                            closeOnClick: true,
                        }).setContent(locs[i]?.label || '').setLatLng([locs[i].lat, locs[i].lng]);
                        // marker.bindPopup(locs[i]?.label || '');
                        marker.bindPopup(popup);
                        marker.bindTooltip(locs[i]?.label || '');
                        markers.push(marker);
                        if (cb) cb(marker);
                        marker.addTo(Leaflet.map);
                    }
                    return markers;
                } else if (locs.constructor === Object) {
                    let label = locs.label;
                    let marker = new L.marker([locs.lat, locs.lng], locs?.options);
                    let popup = new L.Popup({
                        autoClose: false,
                        closeOnClick: true,
                    }).setContent(locs?.label || '').setLatLng([locs.lat, locs.lng]);
                    // marker.bindPopup(locs?.label || '');
                    marker.bindPopup(popup);
                    marker.bindTooltip(locs?.label || '');
                    if (cb) cb(marker);
                    marker.addTo(Leaflet.map);
                    return marker;
                }
            },
            addCircles: function(locs = [], cb = null) {
                if (locs.constructor === Array) {
                    let circles = [];
                    for (let i = 0; i < locs.length; i++) {
                        let circle = L.circle([locs[i].lat, locs[i].lng], locs[i]?.options);
                        circle.bindPopup(locs[i]?.label || '');
                        circle.bindTooltip(locs[i]?.label || '');
                        circles.push(circle);
                        if (cb) cb(circle);
                        circle.addTo(Leaflet.map);
                    }
                    return circles;
                } else if (locs.constructor === Object) {
                    let circle = L.circle([locs.lat, locs.lng], locs?.options);
                    circle.bindPopup(locs?.label || '');
                    circle.bindTooltip(locs?.label || '');
                    if (cb) cb(circle);
                    circle.addTo(Leaflet.map);
                    return circle;
                }
            },
            addPolylines: function(locs = [], cb = null) {
                let latLngs = [];
                for (let i = 0; i < locs.length; i++) {
                    latLngs.push([locs[i].lat, locs[i].lng]);
                }
                let polyline = L.polyline(latLngs, locs[0]?.options).addTo(Leaflet.map);

                if (cb) cb(polyline);
                return polyline;
            },
            addPolygons: function(locs = [], cb = null) {
                let latLngs = [];
                for (let i = 0; i < locs.length; i++) {
                    latLngs.push([locs[i].lat, locs[i].lng]);
                }
                let polygon = L.polygon(latLngs, locs[0]?.options).addTo(Leaflet.map);

                if (cb) cb(polygon);
                return polygon;
            },
            drawPolygon: function(lat, lng, options = {}) {
                let polygon = L.polygon([
                    [lat, lng]
                ], options).addTo(Leaflet.map);
                return polygon;
            },
            // draw boundary by mouse
            createDrawLayer: function() {
                let drawnItems = new L.FeatureGroup().addTo(Leaflet.map);
                return drawnItems;
            },
            createDrawControl: function(options) {
                // example
                // let options = {
                //     edit: {
                //         featureGroup: drawnItems,
                //         poly: {
                //             allowIntersection: true, // draw while moving
                //         },
                //     },
                //     draw: {
                //         polygon: {
                //             allowIntersection: true, // draw while moving
                //             showArea: true,
                //         },
                //         marker: false,
                //         circlemarker: false,
                //         polyline: false,
                //     },
                // };

                let drawControl = new L.Control.Draw(options);
                return drawControl;
            },
            createDrawToolbar: function(drawnItems, drawControl) {
                // after finish not saved
                Leaflet.map.addControl(drawControl);

                Leaflet.map.on(L.Draw.Event.CREATED, function(e) {
                    // validate can create 1 shape only
                    if (!State.boundary_type_choose) { // if not null
                        drawnItems.addLayer(e.layer);
                        OrdSearch.handleBoundaryDraw(e);
                    }
                });

                Leaflet.map.on(L.Draw.Event.EDITED, function(e) {
                    OrdSearch.handleBoundaryDraw(e);
                });

                Leaflet.map.on(L.Draw.Event.DELETED, function(e) {
                    OrdSearch.handleBoundaryDraw(e);
                });

                // remove marker, circle, event listener and all about this marker
                State.eventRemoveToolbarDraw = new CustomEvent('eventRemoveToolbarDraw', {
                    drawnItems,
                    drawControl,
                });
                window.addEventListener('eventRemoveToolbarDraw', function handler(e) {
                    Leaflet.map.removeEventListener(L.Draw.Event.CREATED);
                    Leaflet.map.removeEventListener(L.Draw.Event.EDITED);
                    Leaflet.map.removeEventListener(L.Draw.Event.DELETED);
                    Leaflet.map.removeControl(drawControl);
                    Leaflet.map.removeLayer(drawnItems);
                    e.currentTarget.removeEventListener(e.type,
                        handler); // window.removeEventListener('remove', this.handler, true);
                    State.eventRemoveToolbarDraw = null;
                    State.boundary_type_choose = null;
                    State.boundary_latlngs = null;
                });
            },
            injectShapeToLDraw: function(obj) {
                /**@argument
                 * create shape / vector layer
                 * convert the layer toGeoJSON/toGeoJson with precision default is 6
                 * set L.Draw toolbar/control layer
                 * convert the geoJSON shape/vector layer to leaflet geoJSON format
                 * add the shape/vector leaflet geoJSON format layer to L.Draw toolbar/control layer
                 **/

                // for L.Draw
                let shapeOpts = {
                    color: obj.boundary_hex_color,
                    fillOpacity: 0.4,
                    showRadius: true,
                };
                let drawnItems = Leaflet.createDrawLayer();
                let drawControlOpts = {
                    edit: {
                        featureGroup: drawnItems,
                    },
                    draw: {
                        polygon: false,
                        marker: false,
                        circle: false,
                        rectangle: false,
                        circlemarker: false,
                        polyline: false,
                    },
                };
                // for layer (Shape / Vector)
                let fitBounds = [],
                    circle = null,
                    polygon = null,
                    shapeGeoJSON = null;
                let label = ``;
                let boundaryOpts = {
                    mdata: obj,
                    color: obj.boundary_hex_color,
                    fillColor: obj.boundary_hex_color,
                    radius: obj.boundary_radius,
                };
                // for geoJSON
                let style = {
                    color: obj.boundary_hex_color,
                    fillColor: obj.boundary_hex_color,
                    fillOpacity: 0.4,
                    radius: obj.boundary_radius,
                    showRadius: true,
                }

                // initDate
                State.boundary_latlngs = obj.boundary_latlngs
                State.boundary_radius = obj.boundary_radius
                State.boundary_bounds = obj.boundary_bounds

                // about shape/vector layer
                if (obj.boundary_type == State.boundary_type.circle) {
                    State.boundary_type_choose = State.boundary_type.circle;
                    circle = L.circle([obj.boundary_latlngs[0].lat, obj.boundary_latlngs[0]
                        .lng
                    ], boundaryOpts);
                    shapeGeoJSON = circle.toGeoJSON(6);
                    shapeGeoJSON.properties.radius = circle.getRadius();
                    let corner = L.latLng(obj.boundary_latlngs[0].lat, obj.boundary_latlngs[0]
                        .lng);
                    fitBounds.push(L.latLngBounds(corner, corner));
                    // drawControlOpts.draw.circle = {
                    //     shapeOptions: {
                    //         ...shapeOpts
                    //     },
                    // };
                } else if (obj.boundary_type == State.boundary_type.polygon) {
                    State.boundary_type_choose = State.boundary_type.polygon;
                    let latLngs = [];
                    for (let latLng of obj.boundary_latlngs) {
                        latLngs.push([latLng.lat, latLng.lng]);
                        let corner = L.latLng(latLng.lat, latLng.lng);
                        fitBounds.push(L.latLngBounds(corner, corner));
                    }
                    polygon = L.polygon(latLngs, boundaryOpts);
                    shapeGeoJSON = polygon.toGeoJSON(6);
                    drawControlOpts.draw.polygon = {
                        shapeOptions: {
                            ...shapeOpts
                        },
                    };
                } else if (obj.boundary_type == State.boundary_type.rectangle) {
                    State.boundary_type_choose = State.boundary_type.polygon;
                    let latLngs = [];
                    for (let latLng of obj.boundary_latlngs) {
                        latLngs.push([latLng.lat, latLng.lng]);
                        let corner = L.latLng(latLng.lat, latLng.lng);
                        fitBounds.push(L.latLngBounds(corner, corner));
                    }
                    polygon = L.polygon(latLngs, boundaryOpts);
                    shapeGeoJSON = polygon.toGeoJSON(6);
                    drawControlOpts.draw.rectangle = {
                        shapeOptions: {
                            ...shapeOpts
                        },
                    };
                } else {
                    Helper.toast('Error', 'just now', 'unknown boundary type');
                    return false;
                }

                // about L.Draw control/toolbar layer
                let drawControl = Leaflet.createDrawControl(drawControlOpts);
                Leaflet.createDrawToolbar(drawnItems, drawControl);

                // about convert shape/vector geoJSON to leaflet geoJSON format
                let layers = [];
                let geoJsonGroup = L.geoJSON(shapeGeoJSON, {
                    style: style,
                    pointToLayer: (feature, latlng) => {
                        if (feature.properties.radius) {
                            return new L.Circle(latlng, feature.properties.radius);
                        } else {
                            return new L.Marker(latlng);
                        }
                    },
                    onEachFeature: (feature, layer) => {
                        layers.push(layer);
                    },
                });

                // add shape/vector layer to L.Draw control/toolbar layer
                // Would benefit from https://github.com/Leaflet/Leaflet/issues/4461
                function addNonGroupLayers(sourceLayer, targetGroup) {
                    if (sourceLayer instanceof L.LayerGroup) {
                        sourceLayer.eachLayer(function(layer) {
                            addNonGroupLayers(layer, targetGroup);
                        });
                    } else {
                        targetGroup.addLayer(sourceLayer);
                    }
                }
                addNonGroupLayers(geoJsonGroup, drawnItems);

                // set center
                Leaflet.map.fitBounds(fitBounds);
                Leaflet.map.setZoom(13);
            },
            clearLayer: function(type = 'all', cb = null) {
                if (type == 'all') {
                    if (State.eventRemoveToolbarDraw) window.dispatchEvent(State.eventRemoveToolbarDraw);
                    if (State.eventRemoveListTrucks) window.dispatchEvent(State.eventRemoveListTrucks);
                    if (cb) cb();
                } else if (type == 'eventRemoveToolbarDraw') {
                    if (State.eventRemoveToolbarDraw) {
                        window.dispatchEvent(State.eventRemoveToolbarDraw);
                        if (cb) cb();
                    }
                } else if (type == 'eventRemoveListTrucks') {
                    if (State.eventRemoveListTrucks) {
                        window.dispatchEvent(State.eventRemoveListTrucks);
                        if (cb) cb();
                    }
                }
            }
        };

        const OrdSearch = {
            activate: async function() {
                OrdSearch.event();
                Leaflet.injectShapeToLDraw({
                    boundary_type: State.boundary_type_choose,
                    boundary_radius: State.boundary_radius,
                    boundary_hex_color: State.default_boundary_hex,
                    boundary_latlngs: State.boundary_latlngs,
                });
                let detail = await OrdSearch.reqData({
                    ord_id: State.ord_id,
                    get_current_track_vhcs: 1,
                    boundary_type: State.boundary_type_choose,
                    boundary_radius: State.boundary_radius,
                    boundary_hex_color: State.default_boundary_hex,
                    boundary_latlngs: State.boundary_latlngs,
                });
                if (detail.resp.meta.type == 'success') {
                    OrdSearch.showListCurrentTrackVhcs(detail.resp.list_current_track_vhcs);
                }
            },
            event: function() {
                $('#btnSearchDriver').on('click', function() {
                    let data = OrdSearch.getData();
                    OrdSearch.submitData(data);
                });
                setInterval(async () => {
                    Leaflet.clearLayer('eventRemoveListTrucks');
                    let detail = await OrdSearch.reqData({
                        ord_id: State.ord_id,
                        get_current_track_vhcs: 1,
                        boundary_type: State.boundary_type_choose,
                        boundary_radius: State.boundary_radius,
                        boundary_hex_color: State.default_boundary_hex,
                        boundary_latlngs: State.boundary_latlngs,
                    });
                    if (detail.resp.meta.type == 'success') {
                        OrdSearch.showListCurrentTrackVhcs(detail.resp.list_current_track_vhcs);
                    }
                }, 1 * (60 * 1000));
            },
            reqData: async function(data) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_show_order', '') }}/" + data.ord_id,
                        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: (data, textStatus, jqXHR) => {
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            // Helper.toast('Success', 'just now', 'success get detail order');
                            resolve({
                                type: 'success',
                                resp: 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'
                            });
                        }
                    })
                })
            },
            showListCurrentTrackVhcs: function(trucks) {
                let locations = [];
                for (let i = 0; i < trucks.length; i++) {
                    if (trucks[i]?.lst_lat == null || trucks[i]?.lst_lng == null) {
                        continue;
                    }
                    let icon_stts_engine = Icon.vhcMoveIcon(); // moving
                    if (trucks[i].stts_engine == State.stts_engine.idling) {
                        icon_stts_engine = Icon.vhcIdleIcon();
                    } else if (trucks[i].stts_engine == State.stts_engine.stoping) {
                        icon_stts_engine = Icon.vhcIdleIcon();
                    }
                    locations.push({
                        lat: trucks[i].lst_lat,
                        lng: trucks[i].lst_lng,
                        // label: `<b>${trucks[i].nopol1} ${trucks[i].nopol2} ${trucks[i].nopol3}</b><br>${moment.unix(trucks[i]?.lst_loc_crt).format('DD MMM YYYY HH:mm')}<br>Speed: ${(typeof trucks[i].lst_speed != 'undefined') ? trucks[i].lst_speed : '0'}<br>${Number(trucks[i].lst_lat).toFixed(5)},${Number(trucks[i].lst_lng).toFixed(6)}<br>${Helper.shortenText(decodeURIComponent(trucks[i]?.lst_fulladdress || 'address'), 25)}`,
                        label: `<b>${trucks[i].nopol1} ${trucks[i].nopol2} ${trucks[i].nopol3}</b>`,
                        options: {
                            mdata: trucks[i],
                            icon: icon_stts_engine,
                            // autoClose: false,
                        },
                    });
                }

                let markers = Leaflet.addMarkers(locations, function(marker) {
                    marker.on('click', function(e) {
                        // let markerDetail = e.target.options.mdata;
                        // Leaflet.map.invalidateSize();
                        // if (Leaflet.map.getZoom() <= 14) {
                        //     Leaflet.map.setView(e.target.getLatLng(), 14);
                        // }
                    });
                });

                // remove marker, circle, event listener and all about this marker
                State.eventRemoveListTrucks = new CustomEvent('eventRemoveListTrucks', {
                    detail: {
                        markers,
                    },
                });
                window.addEventListener('eventRemoveListTrucks', function handler(e) {
                    for (let marker of e.detail.markers) {
                        marker.removeEventListener('click');
                        marker.removeEventListener('moveend');
                        marker.remove();
                    }
                    e.currentTarget.removeEventListener(e.type,
                        handler); // window.removeEventListener('remove', this.handler, true);
                });
            },
            getData: function() {
                let data = {};
                data.ord_id = State.ord_id;
                data.boundary_hex_color = State.default_boundary_hex;
                data.boundary_type = State.boundary_type_choose;

                data.boundary_latlngs = [...State.boundary_latlngs];
                data.boundary_bounds = State.boundary_bounds;
                data.boundary_radius = State.boundary_radius;

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSearchDriver').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSearchDriver').attr('disabed', true);
                    OrdSearch.toggleBtnSearchSpinner(1);
                    $.ajax({
                        url: "{{ route('api_adm_find_driver', '') }}",
                        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) => {
                            $('#btnSearchDriver').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                OrdSearch.toggleBtnSearchSpinner(0);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success confirm order');
                            resolve({
                                type: 'success'
                            });
                            OrdSearch.toggleBtnSearchSpinner(0);
                            window.location.href = "{{ route('view_transactions') }}"
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSearchDriver').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'
                            });
                            OrdSearch.toggleBtnSearchSpinner(0);
                        }
                    })
                })
            },
            handleBoundaryDraw: function(e) {
                if (e.type == L.Draw.Event.CREATED) {

                } else if (e.type == L.Draw.Event.EDITED) {
                    e.layerType = State.boundary_type_choose;
                    e.layer = e.layers._layers[Object.keys(e.layers._layers)[0]];
                } else if (e.type == L.Draw.Event.DELETED) {
                    State.boundary_type_choose = null;
                    State.boundary_latlngs = null;
                    State.boundary_radius = null;
                    State.boundary_bounds = null;
                    return true;
                }

                if (e.layerType == State.boundary_type.circle) {
                    State.boundary_type_choose = State.boundary_type.circle;
                    State.boundary_latlngs = [{
                        lat: e.layer._latlng.lat,
                        lng: e.layer._latlng.lng,
                    }];
                    State.boundary_radius = e.layer._mRadius;
                } else if (e.layerType == State.boundary_type.polygon) {
                    State.boundary_type_choose = State.boundary_type.polygon;
                    State.boundary_latlngs = [];
                    for (let i in e.layer._latlngs[0]) {
                        State.boundary_latlngs.push({
                            lat: e.layer._latlngs[0][i].lat,
                            lng: e.layer._latlngs[0][i].lng,
                        })
                    }
                    State.boundary_bounds = {
                        northEast: {
                            lat: e.layer._bounds._northEast.lat,
                            lng: e.layer._bounds._northEast.lng,
                        },
                        southWest: {
                            lat: e.layer._bounds._southWest.lat,
                            lng: e.layer._bounds._southWest.lng,
                        },
                    };
                } else if (e.layerType == State.boundary_type.rectangle) {
                    State.boundary_type_choose = State.boundary_type.rectangle;
                    State.boundary_latlngs = [];
                    for (let i in e.layer._latlngs[0]) {
                        State.boundary_latlngs.push({
                            lat: e.layer._latlngs[0][i].lat,
                            lng: e.layer._latlngs[0][i].lng,
                        })
                    }
                    State.boundary_bounds = {
                        northEast: {
                            lat: e.layer._bounds._northEast.lat,
                            lng: e.layer._bounds._northEast.lng,
                        },
                        southWest: {
                            lat: e.layer._bounds._southWest.lat,
                            lng: e.layer._bounds._southWest.lng,
                        },
                    };
                }
            },
            toggleBtnSearchSpinner: function(isShow = 1) {
                if (isShow) {
                    $('#btnSearchDriver').addClass('d-none');
                    $('#group_btnSearchDrvSpinner').removeClass('d-none');
                } else {
                    $('#btnSearchDriver').removeClass('d-none');
                    $('#group_btnSearchDrvSpinner').addClass('d-none');
                }
            },
        }

        const OrdChoose = {
            activate: async function() {
                OrdChoose.event();
            },
            event: function() {
                $('#btnChooseVendor').on('click', function() {
                    let data = OrdChoose.getData();
                    OrdChoose.submitData(data);
                });
            },
            getData: function() {
                let data = {};
                data.ord_id = State.ord_id;
                data.vendor_id = $('#inputChooseVendor').val()

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnChooseVendor').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnChooseVendor').attr('disabed', true);
                    OrdChoose.toggleBtnSearchSpinner(1);
                    $.ajax({
                        url: "{{ route('api_adm_assign_vendor', '') }}",
                        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) => {
                            $('#btnChooseVendor').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                OrdChoose.toggleBtnSearchSpinner(0);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success confirm order');
                            resolve({
                                type: 'success'
                            });
                            OrdChoose.toggleBtnSearchSpinner(0);
                            window.location.href = "{{ route('view_transactions') }}"
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnChooseVendor').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'
                            });
                            OrdChoose.toggleBtnSearchSpinner(0);
                        }
                    })
                })
            },
            toggleBtnSearchSpinner: function(isShow = 1) {
                if (isShow) {
                    $('#btnChooseVendor').addClass('d-none');
                    $('#group_btnChooseVdrSpinner').removeClass('d-none');
                } else {
                    $('#btnChooseVendor').removeClass('d-none');
                    $('#group_btnChooseVdrSpinner').addClass('d-none');
                }
            },
        }

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