@extends('admin2')

@section('styles')

    <link href="/assets/global/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.css" rel="stylesheet" type="text/css"/>
    <link href="/assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css" rel="stylesheet"
          type="text/css"/>
    <link href="/assets/global/plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet"
          type="text/css"/>
    <link href="/assets/global/plugins/bootstrap-editable/bootstrap-editable/css/bootstrap-editable.css"
          rel="stylesheet" type="text/css"/>
    <link href="/assets/global/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.css" rel="stylesheet" type="text/css"/>
    <link href="/assets/global/plugins/bootstrap-editable/inputs-ext/address/address.css" rel="stylesheet"
          type="text/css"/>
    <link href="/assets/global/plugins/bootstrap-lightbox/lightbox.css" rel="stylesheet" type="text/css"/>

    <style>

        .pac-container {
            z-index: 10052 !important;
        }

        #map {
            width: auto !important;
            height: 500px !important;
        }

        #map_edit {
            width: auto !important;
            height: 500px !important;
        }

        tfoot {
            display: table-header-group;
        }

        tfoot input {
            font-weight: normal !important;
        }

        tfoot select {
            font-weight: normal !important;
        }

        .dataTables_filter {
            display: none;
        }

        #orders-table_length {
            display: none;
        }

        .ws-nr {
            width: 100% !important;
        }
    </style>

@endsection
@section('content')
    @if (session()->has('error'))
        <div class="alert alert-danger">{{ session()->get('error') }}</div>
    @endif
    @if (session()->has('success'))
        <div class="alert alert-success">{{ session()->get('success') }}</div>
    @endif
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <h1 class="page-title">
        Danh sách chốt điện nước
    </h1>

    <div class="modal fade" id="add-ew" tabindex="-1" role="basic" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                    <h4 class="modal-title">Nhập file excel</h4>
                </div>

                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <div class="modal-body" id="add-lead-content">
                    <form action="{{ url('admin/lead/excel') }}" method="post" id="form-add-lead"
                          enctype="multipart/form-data">
                        <div class="form-group">
                            <label>Chọn file<span class="required" aria-required="true"> (*) </span></label>
                            <input type="file" id="nhap-mvd-input" name="file">
                            <p class="help-block"> (.xls, .xlsx) </p>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">

                    <button type="button" class="btn dark btn-outline" data-dismiss="modal">Đóng</button>
                    <button type="submit" class="btn green" id="btn-save-lead">Lưu</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
    </div>

    <div class="row" style="margin-bottom: 15px">
        <div class="col-md-6 col-md-offset-6">
            <div class="row">
                <div class="col-md-12">

                    <a class="btn green-meadow pull-right" href="{{ url('admin2/ew/export-excel') }}" download="">
                        <i class="fa fa-file-excel"></i> Xuất Excel</a>
                    @if(auth('backend')->user()->can('add-ew'))
                        <button class="btn green-meadow fileinput-button pull-right" style="margin-right: 10px"
                                id="btn-add-excel" data-toggle="modal" href="#add-ew">
                            <i class="fa  fa-upload"></i> Nhập excel
                        </button>
                    @endif

                    <a class="btn red pull-right" id="btn-download" style="margin-right: 10px" href="#sample-ew"
                       data-toggle="modal">
                        <i class="fa  fa-download"></i> Tải file mẫu
                    </a>

                </div>
            </div>
        </div>
    </div>
    @if(auth('backend')->user()->can('add-ew'))
        <div class="row">
            <div class="col-md-12">
                <div class="portlet box red">
                    <div class="portlet-title">
                        <div class="caption">
                            <i class="fa fa-edit"></i>Thêm điện nước
                        </div>
                        <div class="tools">
                            <a href="javascript:;" class="collapse" data-original-title="" title=""> </a>
                        </div>
                    </div>
                    <div class="portlet-body">

                        <form action="#" id="form-add-ew">

                            <div class="row">
                                <div class="col-md-2 col-md-offset-1">
                                    <div class="form-group">
                                        <label class="control-label">Chọn nhà <span class="required"
                                                                                        aria-required="true"> (*) </span></label>
                                        <select class="form-control" id="hostels_form" name="hostel_id">
                                            @php
                                                $firstHostel = null;
                                                    $hostelArrs = \App\Models\Hostel::where('owner_id', auth('backend')->user()->id)->pluck('id')->toArray();

                                                    if(auth('backend')->user()->type == \App\User::STAFF)
            {
                $hostelArrs = \App\Components\Functions::getHostelArrStaff();
            }

                                                    $hostels = \App\Models\Hostel::whereIn('id', $hostelArrs)->get();

                                            @endphp
                                            @foreach($hostels as $hostel)

                                                @if($loop->index == 0)
                                                    @php    $firstHostel = $hostel; @endphp
                                                @endif

                                                <option value="{{ $hostel->id }}">{{ $hostel->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="control-label">Chọn phòng <span class="required"
                                                                                          aria-required="true"> (*) </span></label>
                                        <select class="form-control select2" id="room_id" name="room_id">
{{--                                            @if(!empty($firstHostel))--}}
{{--                                                @php    $rooms = \App\Models\Room::query()->where('hostel_id', $firstHostel->id)->get()->sortBy(function($item) {--}}
{{--	        return $item->name;--}}
{{--        });--}}
{{--                                                $firstRoom = $rooms->first();--}}
{{--                                                @endphp--}}

{{--                                                @foreach($rooms as $room)--}}
{{--                                                    <option value="{{ $room->id }}">{{ $room->name }}</option>--}}
{{--                                                @endforeach--}}
{{--                                            @endif--}}

                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="control-label">Chọn tháng <span class="required"
                                                                                      aria-required="true"> (*) </span></label>
                                        <input type="text" class="form-control monthpicker" id="month"
                                               name="date_action" value="{{ \Carbon\Carbon::now()->format('m/Y') }}">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="control-label">Chọn hợp đồng</label>
                                        <select class="form-control select2" name="contract_id" id="contracts">
                                            <option value="">Vui lòng chọn</option>
                                            @if(!empty($firstHostel))
                                                @php    $contracts = \App\Models\Contract::query()->where('hostel_id', $firstHostel->id);
                                                if(!empty($firstRoom))
                                                {
                                                $contracts = $contracts->where('room_id', $firstRoom->id);
                                                }

                                                $contracts = $contracts->where('status', '<>', \App\Models\Contract::LIQUIDATED)->get();

                                                @endphp
                                                @foreach($contracts as $contract)
                                                    <option value="{{ $contract->id }}">{{ $contract->code }}
                                                        - {{ $contract->name }}</option>
                                                @endforeach
                                            @endif
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="control-label">Ngày chốt <span class="required"
                                                                                     aria-required="true"> (*) </span></label>
                                        <input type="text" class="form-control datepicker" name="date_execution"
                                               value="{{ \Carbon\Carbon::now()->format('d/m/Y') }}"></div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-2 col-md-offset-1">
                                    <div class="form-group">
                                        <label class="control-label">Số điện đầu <span class="required"
                                                                                       aria-required="true"> (*) </span></label>
                                        <input type="text" class="form-control" id="start_electric"
                                               name="start_electric" value="0"/>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="control-label">Số điện cuối <span class="required"
                                                                                        aria-required="true"> (*) </span></label>
                                        <input type="text" class="form-control" name="end_electric" value="0"></div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="control-label">Số nước đầu <span class="required"
                                                                                       aria-required="true"> (*) </span></label>
                                        <input type="text" class="form-control" id="start_water" name="start_water"
                                               value="0"></div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="control-label">Số nước cuối <span class="required"
                                                                                        aria-required="true"> (*) </span></label>
                                        <input type="text" class="form-control" name="end_water" value="0"></div>
                                </div>
                                <div class="col-md-2">
                                    <a href="#" data-repeater-delete class="btn btn-success" id="save-ew"
                                       style="margin-top: 1.8em; width: 100%;">Hoàn thành</a>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-2 col-md-offset-1">
                                    <label class="control-label">Hình ảnh (nếu có) </label>
                                    <div class="fileinput fileinput-new" data-provides="fileinput">
                                        <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                            <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image"
                                                 alt=""></div>
                                        <div class="fileinput-preview fileinput-exists thumbnail"
                                             style="max-width: 200px; max-height: 150px;"></div>
                                        <div>
                                                                <span class="btn default btn-file">
                                                                    <span class="fileinput-new"> Chọn ảnh </span>
                                                                    <span class="fileinput-exists"> Thay đổi </span>
                                                                    <input type="file"
                                                                           name="start_electric_image"> </span>
                                            <a href="javascript:;" class="btn red fileinput-exists remove-image"
                                               data-dismiss="fileinput"> Xóa </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <label class="control-label">Hình ảnh (nếu có) </label>
                                    <div class="fileinput fileinput-new" data-provides="fileinput">
                                        <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                            <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image"
                                                 alt=""></div>
                                        <div class="fileinput-preview fileinput-exists thumbnail"
                                             style="max-width: 200px; max-height: 150px;"></div>
                                        <div>
                                                                <span class="btn default btn-file">
                                                                    <span class="fileinput-new"> Chọn ảnh </span>
                                                                    <span class="fileinput-exists"> Thay đổi </span>
                                                                    <input type="file"
                                                                           name="end_electric_image"> </span>
                                            <a href="javascript:;" class="btn red fileinput-exists remove-image"
                                               data-dismiss="fileinput"> Xóa </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <label class="control-label">Hình ảnh (nếu có) </label>
                                    <div class="fileinput fileinput-new" data-provides="fileinput">
                                        <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                            <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image"
                                                 alt=""></div>
                                        <div class="fileinput-preview fileinput-exists thumbnail"
                                             style="max-width: 200px; max-height: 150px;"></div>
                                        <div>
                                                                <span class="btn default btn-file">
                                                                    <span class="fileinput-new"> Chọn ảnh </span>
                                                                    <span class="fileinput-exists"> Thay đổi </span>
                                                                    <input type="file" name="start_water_image"> </span>
                                            <a href="javascript:;" class="btn red fileinput-exists remove-image"
                                               data-dismiss="fileinput"> Xóa </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <label class="control-label">Hình ảnh (nếu có) </label>
                                    <div class="fileinput fileinput-new" data-provides="fileinput">
                                        <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
                                            <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image"
                                                 alt=""></div>
                                        <div class="fileinput-preview fileinput-exists thumbnail"
                                             style="max-width: 200px; max-height: 150px;"></div>
                                        <div>
                                                                <span class="btn default btn-file">
                                                                    <span class="fileinput-new"> Chọn ảnh </span>
                                                                    <span class="fileinput-exists"> Thay đổi </span>
                                                                    <input type="file" name="end_water_image"> </span>
                                            <a href="javascript:;" class="btn red fileinput-exists remove-image"
                                               data-dismiss="fileinput"> Xóa </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>

                    </div>
                </div>
            </div>
        </div>
        <div class="row"
             style="margin-right: 0px; margin-left: 0px; padding-top: 15px; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #e7ecf1; background-color: #EFF2F5">
            <div class="col-md-9">
                <div class="row">


                    <div class="col-md-2">
                        <label class="control-label">Chọn nhà</label>
                        <select class="form-control" id="hostels">
                            <option value="">Tất cả nhà</option>
                            @foreach($hostels as $hostel)
                                <option
                                        value="{{ $hostel->id }}">{{ $hostel->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="control-label">Chọn phòng</label>
                        <select class="form-control select2" id="select-rooms">
                            <option value=" " selected>Tất cả phòng</option>
                        </select>
                    </div>


                    <div class="col-md-2">
                        <label class="control-label">Ngày bắt đầu</label>
                        <input class="form-control date-picker" type="text" name="start_date" id="start_date" readonly="readonly">
                    </div>


                    <div class="col-md-2">
                        <label class="control-label">Ngày kết thúc</label>
                        <input class="form-control date-picker" type="text" name="end_date" id="end_date" readonly="readonly">
                    </div>

                </div>
            </div>


        </div>
        <div class="row" id="stat">

        </div>
    @endif
    <div class="row">
        {{--<div class="col-md-12" style="margin-bottom: 12px; ">--}}
        {{--<a href="#add-hostel" data-toggle="modal" class="btn btn-success" id="btn-add-hostel" style="float: right">Thêm nhà</a>--}}
        {{--</div>--}}
        <div class="col-md-12">
            <table class="table table-striped table-bordered table-hover" id="orders-table">
                <thead>
                <tr style="background-color: #5376B9; color: white">
                    <th>STT</th>
                    <th>Nhà</th>
                    <th>Phòng</th>
                    <th>Hợp đồng</th>
                    <th>Tháng</th>
                    <th>Ngày chốt</th>
                    <th>Số điện đầu</th>
                    <th>Số điện cuối</th>
                    <th style="color: white">Chênh lệch điện</th>

                    <th>Số nước đầu</th>
                    <th>Số nước cuối</th>
                    <th>Chênh lệch nước</th>
                    <th style="width: 10%">Ảnh</th>
                    <th>Thao tác</th>
                </tr>
                </thead>
                <tfoot>
                <tr>
                    <th></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th><input type="text" class="form-control"></th>
                    <th></th>
                    <th></th>
                    {{--<th><input type="text" class="form-control"></th>--}}
                </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12" id="detail">
        </div>
    </div>

    <div class="modal fade" id="sample-ew" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                    <h4 class="modal-title">
                        Tải file nhập điện nước mẫu
                    </h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Tháng </label>
                                <input type="text" class="form-control" placeholder="" id="month-sample"
                                       value="{{ Carbon\Carbon::now()->format('m/Y') }}">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Ngày chốt </label>
                                <input type="text" class="form-control datepicker" placeholder="" id="date-sample"
                                       value="{{ Carbon\Carbon::now()->format('d/m/Y') }}">
                            </div>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn dark btn-outline" data-dismiss="modal" id="dismiss-modal">Đóng
                    </button>
                    <button type="button" class="btn red" id="btn-download-sample-ew">Tải xuống</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>

@endsection

@push('scripts')
    <script src="/assets/global/plugins/dropzone/dropzone.min.js" type="text/javascript"></script>
    <script src="/assets/pages/scripts/form-dropzone.min.js" type="text/javascript"></script>
    <script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
    <script src="/assets/global/plugins/jquery-validation/js/additional-methods.min.js" type="text/javascript"></script>
    <script type="text/javascript"
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCydLs7dhJPuozABFQjJO-uk1PITW18oo8&libraries=places&region=vi&language=vi&sensor=false"></script>
    <script type="text/javascript" src="/js/gmap.js"></script>
    <script src="/assets/global/plugins/bootstrap-lightbox/lightbox.js" type="text/javascript"></script>

    <script>
        $(document).on('click', '[data-toggle="lightbox"]', function (event) {
            event.preventDefault();
            $(this).ekkoLightbox();
        });

        $.validator.addMethod("greaterThan",
            function (value, element, param) {
                var $otherElement = $(param);
                return parseInt(value, 10) >= parseInt($otherElement.val(), 10);
            }
        );
        $.validator.addMethod("minDate", function (value, element) {
            var now = moment();
            var myDate = moment(value, "MM/YYYY");
            return this.optional(element) || myDate.isBefore(now);

            // else alert('Das passt nicht!' + mD +  '   ' + nowdate);

        });
    </script>


@endpush

@push('scripts')

    <script>


        var table;

        $('#hostels').on('change', function () {
            $.ajax({
                url: '{{ url('admin2/hostel/select-rooms') }}',
                type: 'get',
                data: {
                    hostel_id: $(this).val()
                },
                dataType: 'json',
                success: function (response) {
                    $('#select-rooms').html(response.data);
                }
            })

            getPostByAttr();
        });

        $('#select-rooms').on('change', function () {

            getPostByAttr();
        });


        $('.datepicker').datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true
        });

        $('#month-sample').datepicker({
            format: 'mm/yyyy',
            autoclose: true,
            viewMode: "months",
            minViewMode: "months",
        });

        $('.monthpicker').datepicker({
            format: 'mm/yyyy',
            autoclose: true,
            viewMode: "months",
            minViewMode: "months",
        }).on('changeDate', function (e) {
            var room_id = $('#room_id').val();
            var hostel_id = $('#hostels_form').val();
            get_rooms(hostel_id);
            var date = e.format();
            get_ew_previous(hostel_id, room_id, date);
        });

        $('#contracts').change(function () {
            var room_id = $('#room_id').val();
            var hostel_id = $('#hostels_form').val();
            var date = $('.monthpicker').val();

            get_ew_previous(hostel_id, room_id, date);
        });

        $('#save-ew').click(function () {
            var formStatus = $('#form-add-ew').validate({
                errorElement: "span",
                errorClass: "help-block help-block-error",

                highlight: function (e) {
                    $(e).closest(".form-group").addClass("has-error")
                },
                unhighlight: function (e) {
                    $(e).closest(".form-group").removeClass("has-error")
                },
                success: function (e) {
                    e.closest(".form-group").removeClass("has-error")
                },
                rules: {
                    'date_action': {
                        required: true,
                    },
                    'room_id': {
                        required: true,
                    },
                    'hostel_id': {
                        required: true,
                    },
                    'start_electric': {
                        required: true,
                        number: true,
                    },
                    'end_electric': {
                        required: true,
                        number: true,
                    },
                    'start_water': {
                        required: true,
                        number: true,
                    },
                    'end_water': {
                        required: true,
                        number: true,
                    },

                },
                messages: {
                    'date_action': {
                        required: 'Không được bỏ trống tháng',
                        minDate: 'Tháng không được lớn hơn tháng hiện tại'
                    },
                    'room_id': {
                        required: 'Không được bỏ trống phòng',
                    },
                    'hostel_id': {
                        required: 'Không được bỏ trống nhà trọ',
                    },
                    'start_electric': {
                        required: 'Không được bỏ trống số điện đầu',
                    },
                    'end_electric': {
                        required: 'Không được bỏ trống số điện cuối',
                    },
                    'start_water': {
                        required: 'Không được bỏ trống số nước đầu',
                    },
                    'end_water': {
                        required: 'Không được bỏ trống số nước cuối',
                    },
                }
            }).form();

            if (formStatus) {

                var data = new FormData($('#form-add-ew')[0]);
                $.ajax({
                    url: '{{ url('admin2/ew/create') }}',
                    type: 'post',
                    data: data,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    success: function (response) {

                        if (response.status == 1) {
                            table.ajax.reload();
                            swal('Thành công', '', 'success');
                            $('.remove-image').click()
                        } else if (response.status == 2) {
                            swal('Thông báo', response.message, 'info');
                        } else {
                            swal('Thông báo', response.message, 'info');
                        }
                    }
                });
            }
        });


        function get_ew_previous(hostel_id, room_id, date) {
            var contract_id = $('#contracts').val();
            $.ajax({
                url: '{{ url('admin2/ew/get-ew-previous') }}',
                type: 'get',
                data: {
                    'date': date,
                    'room_id': room_id,
                    'hostel_id': hostel_id,
                    'contract_id': contract_id
                },
                dataType: 'json',
                success: function (response) {

                    if (response.status == 1) {
                        $('#start_electric').val(response.data.start_electric);
                        $('#start_water').val(response.data.start_water);
                    }
                }
            });
        }

        function get_contract(hostel_id, room_id) {
            $.ajax({
                url: '{{ url('get-contracts') }}',
                type: 'get',
                data: {
                    'room_id': room_id,
                    'hostel_id': hostel_id
                },
                dataType: 'html',
                success: function (response) {
                    $('#contracts').html(response);
                    $('#contracts').select2();
                }
            });
        }

        $('#room_id').on('change', function () {
            var room_id = $('#room_id').val();
            var hostel_id = $('#hostels_form').val();
            var date = $('#month').val();
            get_ew_previous(hostel_id, room_id, date);
            get_contract(hostel_id, room_id);
        });

        function get_rooms(id)
        {
            $.ajax({
                url: '{{ url('get-sub-hostel') }}',
                type: 'get',
                data: {
                    'id': $('#hostels_form').val(),
                    'type': 'ew',
                    'month': $('#month').val()
                },
                dataType: 'html',
                success: function (response) {
                    $('#room_id').html(response);
                    $('#room_id').select2();

                    var room_id = $('#room_id').val();
                    var date = $('#month').val();
                    get_ew_previous(id, room_id, date);
                    get_contract(id, room_id);

                }
            });
        }
        $('#hostels_form').on('change', function () {
            var id = $(this).val();
            //var type = $(this).attr('data-type');
            get_rooms(id);
        });

        $(document).ready(function() {
            var id = $('#hostels_form').val();
            //var type = $(this).attr('data-type');
            get_rooms(id);
        });


        function getPostByAttr() {

            get_stat();
            table.ajax.reload();
        }

        function get_stat() {
            $.ajax({
                url: '{!! url('admin2/ew/ew.data') !!}',
                data: {
                    hostel_id: $('#hostels').val(),
                    start_date: $('#start_date').val(),
                    end_date: $('#end_date').val(),
                    room_id: $('#select-rooms').val(),
                    is_stat: 1,
                },
                beforeSend: function () {
                    $('#stat').addClass('ht-on-loading');
                },
                dataType: 'json',
                success: function (response) {
                    $('#stat').removeClass('ht-on-loading').html(response.data);
                }
            });
        }

        $('.date-picker').datepicker({
            format: 'mm/yyyy',
            autoclose: true,
            viewMode: "months",
            minViewMode: "months",
        }).on('changeDate', function (ev) {
            getPostByAttr();
        });

        $(function () {

            //        $('#orders-table tfoot th').each( function (index) {
            //            if(index != 0 && index != 9) {
            //                $(this).html('<input type="text" class="form-control" />');
            //            }
            //        } );
            get_stat();
            table = $('#orders-table').DataTable({
                "bDestroy": true,
                processing: true,
                searching: true,
                "aaSorting": [[2, 'asc'], [4, 'desc']],
                serverSide: true,
                ajax: {
                    url: '{!! url('admin2/ew/ew.data') !!}',
                    data: function (d) {
                        d.hostel_id = $('#hostels').val();
                        d.start_date = $('#start_date').val();
                        d.end_date = $('#end_date').val();
                        d.room_id = $('#select-rooms').val();
                    }
                },
                columns: [

                    {data: 'DT_Row_Index', name: 'DT_Row_Index', orderable: false, searchable: false},
                    {data: 'hostel_id', name: 'hostel_id'},
                    {data: 'room_id', name: 'room_id'},
                    {data: 'contract_id', name: 'contract_id'},
                    {data: 'date_action', name: 'date_action'},
                    {data: 'date_execution', name: 'date_execution'},
                    {data: 'start_electric', name: 'start_electric'},
                    {data: 'end_electric', name: 'end_electric'},
                    {data: 'delta_electric', name: 'delta_electric'},
                    {data: 'start_water', name: 'start_water'},
                    {data: 'end_water', name: 'end_water'},
                    {data: 'delta_water', name: 'delta_water'},
                    {data: 'image', name: 'image', orderable: false, searchable: false},
                    {data: 'action', name: 'action', 'orderable': false, searchable: false},
                ],
            });


            table.columns().every(function (index) {
                if (index !== 0 && index !== 9) {
                    var that = this;
                    $('input', this.footer()).on('keyup', function () {
                        if (that.search() !== this.value) {
                            that
                                .search(this.value)
                                .draw();
                        }
                    });

                    $('select', this.footer()).on('change', function () {
                        if (that.search() !== this.value) {
                            that
                                .search(this.value)
                                .draw();
                        }
                    });
                }
            });

        });

        function getCoor(id, type) {
            $.ajax({
                url: '{{ url('get-location-coor') }}',
                type: 'get',
                data: {
                    'id': id,
                    'type': type
                },
                dataType: 'json',
                success: function (response) {
                    if (map) {
                        map.setCenter(
                            response.lat,
                            response.lng
                        );
                    }

                    cur_lat = response.lat;
                    cur_lng = response.lng;

                }
            });
        }

        $(document).on('change', '#province_id', function (e) {
            var id = $(this).val();
            $.ajax({
                url: '{{ url('get-sub-location') }}',
                type: 'get',
                data: {
                    'id': $(this).val(),
                    'type': 'province',
                },
                dataType: 'html',
                success: function (response) {
                    $('#district_id').html(response);
                    $('#ward_id').html('');
                    getCoor(id, 'province');


                }
            });
        });

        $(document).on('change', '#district_id', function (e) {
            var id = $(this).val();
            $.ajax({
                url: '{{ url('get-sub-location') }}',
                type: 'get',
                data: {
                    'id': $(this).val(),
                    'type': 'district'
                },
                dataType: 'html',
                success: function (response) {
                    $('#ward_id').html(response);
                    getCoor(id, 'district');
                }
            });
        });

        $(document).on('click', '.btn-paid', function (e) {
            var that = this;
            var money_info_id = $(this).attr('data-money-info');
            $.ajax({
                url: '{{ url('admin2/room/paid-form') }}',
                type: 'get',
                data: {
                    money_info_id: money_info_id
                },
                dataType: 'json',
                success: function (response) {
                    $('#form-paid-' + money_info_id).html(response.data);
                    $('.datepicker').datepicker({
                        format: 'dd/mm/yyyy',
                        autoclose: true
                    });

                    //                $(that).parent().parent().find('.col-md-12').first().next().html(response.data);
                }
            })
        });

        $(document).on('click', '.btn-save-payment', function (e) {
            e.preventDefault();

            var data = $(this).closest('form').serialize();

            $.ajax({
                url: '{{ url('admin2/room/spend') }}',
                type: 'post',
                data: data,
                dataType: 'json',
                beforeSend: function () {
                    $('#payment-items').addClass('ht-on-loading');
                },
                success: function (response) {
                    $('#payment-items').removeClass('ht-on-loading');
                    if (response.status == 1) {
                        swal('Thành công', 'Thanh toán thành công', 'success');
                        $('#detail-money-info').modal('hide');
                        table.ajax.reload();
                    } else {
                        swal('Thông báo', response.message, 'warning');
                    }
                }
            });

        });

        $(document).on('click', '.btn-cancel-paid', function (e) {
            e.preventDefault();

            $(this).parent().parent().parent().parent().remove();

        });

        $(document).on('click', '#btn-download-sample-ew', function (e) {
            e.preventDefault();

            var url = '{{ url('admin2/ew/sample-ew') }}';
            var month = $('#month-sample').val();
            var date = $('#date-sample').val();
            window.location.href = url + '?month=' + month + '&date=' + date;
            return;

        });

        $(document).on('click', '.btn-edit-payment', function (e) {
            e.preventDefault();
            var transaction_id = $(this).attr('data-payment');
            var that = this;

            $.ajax({
                url: '{{ url('admin2/room/get-edit-payment') }}',
                type: 'get',
                data: {
                    transaction_id: transaction_id
                },
                dataType: 'json',
                success: function (response) {
                    $(that).closest('td').prev().html(response.html);
                    $(that).closest('td').html(response.button);
                }
            });


        });


        $(document).on('click', '.btn-save-edit-payment', function (e) {
            e.preventDefault();
            var transaction_id = $(this).attr('data-transaction');
            var amount = $(this).closest('td').prev().find('input').val();
            var that = this;

            $.ajax({
                url: '{{ url('admin2/room/edit-payment') }}',
                type: 'post',
                data: {
                    transaction_id: transaction_id,
                    amount: amount
                },
                dataType: 'json',
                success: function (response) {
                    if (response.status == 1) {
                        swal('Thành công', '', 'success');
                    } else {
                        swal('Thông báo', response.message, 'warning');
                    }
                    $(that).closest('td').prev().html(response.html);
                    $(that).closest('td').html(response.button);
                }
            });
        });

        $(document).on('click', '.btn-cancel-edit-payment', function (e) {
            e.preventDefault();
            var transaction_id = $(this).attr('data-transaction');
            var that = this;

            $.ajax({
                url: '{{ url('admin2/room/cancel-edit-payment') }}',
                type: 'get',
                data: {
                    transaction_id: transaction_id,
                },
                dataType: 'json',
                success: function (response) {
                    $(that).closest('td').prev().html(response.html);
                    $(that).closest('td').html(response.button);
                }
            });
        });

        $(document).on('click', '.btn-delete-ew', function (e) {
            e.preventDefault();

            var id = $(this).attr('data-id');

            bootbox.confirm({
                message: "Bạn có chắc chắn muốn xóa",
                buttons: {
                    confirm: {
                        label: 'Có',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: 'Không',
                        className: 'btn-danger'
                    }
                },


                callback: function (result) {
                    if (result == true) {
                        $.ajax({
                            url: '{{ url('admin2/ew/delete') }}',
                            type: 'post',
                            data: {
                                id: id
                            },
                            dataType: 'json',
                            success: function (response) {
                                if (response.status == 1) {
                                    swal('Xóa thành công', '', 'success');
                                    table.ajax.reload();
                                } else {
                                    swal('Thông báo', response.message, 'info');
                                }
                            }
                        });
                    }
                }
            });
        });

        //    $(document).on('Thay đổi', '#ward_id', function (e) {
        //        var id = $(this).val();
        //        getCoor(id, 'ward');
        //    });

        $('#btn-save-lead').click(function (e) {
            e.preventDefault();

            var formStatus = $('#form-add-lead').validate({
                errorElement: "span",
                errorClass: "help-block help-block-error",

                highlight: function (e) {
                    $(e).closest(".form-group").addClass("has-error")
                },
                unhighlight: function (e) {
                    $(e).closest(".form-group").removeClass("has-error")
                },
                success: function (e) {
                    e.closest(".form-group").removeClass("has-error")
                },
                rules: {
                    'file': "required",
                },
                messages: {
                    'file': "Không được bỏ trống file",
                }
            }).form();

            if (formStatus) {
                let data = new FormData($('#form-add-lead')[0]);
                $.ajax({
                    url: '{{ url('admin2/ew/excel') }}',
                    type: 'post',
                    data: data,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    beforeSend: function () {
                        $('#add-lead-content').addClass('ht-on-loading');
                    },
                    success: function (response) {
                        $('#add-lead-content').removeClass('ht-on-loading');
                        $('#add-ew').modal('hide');
                        if (response.status == 1) {
                            swal('Thành công', response.message, 'success');

                        } else if (response.status == 0) {
                            swal('Thông báo', response.message, 'warning');
                        } else if (response.status == 2) {
                            swal('Thông báo', response.message, 'info');
                        }
                        table.ajax.reload();
                    }
                });
            }
        });

    </script>
@endpush