<?php $__env->startSection('css_page_level'); ?>
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.css')); ?>"/>
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css')); ?>" />
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/bootstrap-daterangepicker/daterangepicker.min.css')); ?>" />
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/bootstrap-select/bootstrap-select.min.css')); ?>"/>
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/select2/css/select2.css')); ?>"/>
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/select2/css/select2-bootstrap.min.css')); ?>"/>
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/jquery-multi-select/css/multi-select.css')); ?>"/>
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css')); ?>"/>
    <link rel="stylesheet" type="text/css" href="<?php echo e(asset('assets/global/plugins/jquery-ui/jquery-ui.min.css')); ?>"/>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('page-content-wrapper'); ?>
	<style type="text/css">
		.th_display_none { display: none;}
        .disableInput {
            background-color: #ffee88 !important;
        }
        .readOnlyInput {
            background-color: #ffee88 !important;
        }
        .loading {    
            background-color: #ffffff;
            background-image: url("<?php echo e(asset('assets/global/img/loading-spinner-grey.gif')); ?>");
            background-size: 15px 15px;
            background-position: 99% center;
            background-repeat: no-repeat;
        }
        #loadbox {
            display: none;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 999999;
            width: 100%;
            height: 100%;
            overflow: visible;
            background: rgba(255, 255, 255, 0.4);
            background-image: url("<?php echo e(asset('assets/global/img/loading_big.gif')); ?>");
            background-repeat: no-repeat;
            background-position: center center;
        }
	</style>
    <div id="loadbox"></div>
	<div class="page-content-wrapper" id="main">
		<div class="page-content">                               
			<!-- BEGIN PAGE HEADER-->
			<h3 class="page-title">
			<?php $setting = app('anlutro\LaravelSettings\Facade'); ?>
			<?php echo e($setting::get('system_name','全方位建築智慧化管理系統')); ?> <small><?php echo e($setting::get('company_name','新保科技')); ?></small>
			</h3>
			<div class="page-bar">
				<ul class="page-breadcrumb">
					<li>
						<i class="fa fa-home"></i>
						<a href="index.html">首頁</a>
						<i class="fa fa-angle-right"></i>
					</li>
					<li>
						<a href="#">取得資產領用建立</a>
						<i class="fa fa-angle-right"></i>
					</li>
					<li>
						<a href="#">資產領用列表</a>
					</li>
				</ul>
				<div class="page-toolbar">

				</div>
			</div>
			<!-- END PAGE HEADER-->
			<!-- BEGIN DASHBOARD STATS -->
			<div class="row">
				<div class="col-md-12">
					<!-- BEGIN EXAMPLE TABLE PORTLET-->
					<div class="portlet light bordered">
						<div class="portlet-body">
							<div class="table-toolbar" >
								<div class="row">
									<div class="col-md-6">
                                        <div class="btn-group">
											<a id="btn_add_picklist" href="javascript:;"  class="btn green">
											新增 <i class="fa fa-plus"></i>
											</a>
                                        </div>
                                        <!-- <button id="btn_mass_delete" class="btn red" style="display:none;"> 刪除 <i class="fa fa-trash"></i></button> -->
									</div>
								</div>
									
							</div>
							<table class="table table-striped table-bordered table-hover" id="table_list">

							</table>
						</div>
					</div>
					<!-- END EXAMPLE TABLE PORTLET-->
				</div>
			</div>
		</div>
        <div class="modal fade draggable-modal" id="modal_add_picklist" 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">新增資產領用</h4>
                    </div>
                    <form id="form_add" action="" class="form-horizontal">
                        <div class="modal-body">
                            <div class="form-body">

                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn dark btn-outline" data-dismiss="modal">關閉</button>
                            <button type="submit" class="btn green btn_query_submit" value="add">新增</button>
                        </div>
                    </form>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <div class="modal fade draggable-modal" id="modal_edit_picklist" 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">修改資產領用</h4>
                    </div>
                    <form id="form_edit" action="" class="form-horizontal">
                        <input type="hidden" name="id" value="" />
                        <div class="modal-body">
                            <div class="form-body">

                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn dark btn-outline" data-dismiss="modal">關閉</button>
                            <button type="submit" class="btn green btn_query_submit" value="add">修改</button>
                        </div>
                    </form>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <div id="formTemplate" style="display:none;">
            <div class="form-group">
                <label class="col-md-2 control-label">分類類別</label>
                <div class="col-md-10"> 
                    <select class="select2 category-column">
                        <option value="">未選擇</option>
                        <?php foreach($categories as $category): ?>
                            <option value="<?php echo e($category->id); ?>"><?php echo e($category->no); ?> - <?php echo e($category->name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">資產編號</label>
                <div class="col-md-10"> 
                    <select class="select2" name="target_id">
                        <option value="">未選擇</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">領用人</label>
                <div class="col-md-10">
                    <select name="consuming" class="form-control select2"> 
                        <?php foreach($staffs as $staff): ?>
                            <option value="<?php echo e($staff->id); ?>"><?php echo e($staff->employee_no.'  '.$staff->name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">備註</label>
                <div class="col-md-10">
                    <textarea name="remark" class="form-control"></textarea>  
                </div>
            </div>
            <input type="hidden" id="_token" name="_token" value="<?php echo e(csrf_token()); ?>">
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('plugins_page_level'); ?>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/jquery-validation/js/jquery.validate.min.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/jquery-validation/js/additional-methods.min.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/datatables/media/js/jquery.dataTables.min.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/moment.min.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/bootstrap-daterangepicker/daterangepicker.min.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/bootbox/bootbox.min.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/jquery-multi-select/js/jquery.multi-select.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/select2/js/select2.min.js')); ?>"></script>
    <script type="text/javascript" src="<?php echo e(asset('assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.js')); ?>"></script>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('js_page_level'); ?>
    <script>
        var tmp_target_id = '';
        $(document).ready(function(){
            callDataTable();
            $('#modal_add_picklist form').find('.form-body').html($('#formTemplate').html());
            $('#modal_edit_picklist form').find('.form-body').html($('#formTemplate').html());
            //$('#modal_edit_picklist form .assetNo').addClass('readOnlyInput');
            $(".select2").select2();
            $('.disableInput').prop('disabled', true);
            $('.readOnlyInput').prop('readonly', true);
            $('.show-tooltip').tooltip();
            $('#type').multiSelect();
            $('#source').multiSelect();
            $('.date-picker').datepicker({
                orientation: "left",
                autoclose: true
            });
            $(document).on('click','#btn_add_picklist',function(){
                $('#modal_add_picklist').modal('show');
            });
            $(document).on('click', '#btn_mass_delete', function(){
                var ids = [];
                $('.checkboxes:checked').each(function() {
                    ids.push($(this).val());                      
                });   
                deleteassets(ids);
            });
            $('#table_list tbody').on('click', '.btn_return', function(){
                var uid = $(this).attr('uid');
                $.ajax({
                    type : 'GET',
                    url  : "<?php echo e(route('manage::asset::return_picklist')); ?>",
                    data : {
                        'id' : uid
                    },
                    success :function(sendback){
                        toastr['success']('已成功歸還');
                        window.location.reload();
                    },
                    error : function(sendback){
                        toastr['error']('發生錯誤，請重新整理後再次使用');
                        window.location.reload();
                    }
                });
            });
            $('.btn_delete').click(function() {
                var id = $(this).attr('uid');
                deleteassets(id);
            });
            $('.btn_edit').click(function(){
                var uid = $(this).attr('uid');
                $.ajax({
                    type : 'GET',
                    url  : "<?php echo e(route('manage::asset::get_picklist')); ?>",
                    dataType : 'json',
                    data : {
                        'id' : uid
                    },
                    success: function(sendback){
                        var target_id = '';
                        $.each(sendback, function(key, value) {
                            var obj;
                            switch(key) {
                                case 'asset_no':
                                    obj = $("#form_edit .assetNo");
                                    break;
                                case 'asset_name':
                                    obj = $("#form_edit .assetName");
                                    break;
                                case 'c_id':
                                    obj = $('#form_edit .category-column');
                                    break;
                                case 'target_id':
                                    obj           = $("#form_edit [name='target_id']");
                                    tmp_target_id = value;
                                    break;
                                default:
                                    obj = $("#form_edit [name='" + key + "']");
                                    break;
                            }
                            if ($(obj).hasClass('select2')) {
                                $(obj).select2("val", value); 
                            } else {
                                $(obj).val(value);     
                            } 
                        });
                        $('#modal_edit_picklist').modal('show');
                    },
                    error: function(){
                        toastr['error']('發生錯誤，請重新整理後再嘗試');
                    }
                });
            });
            
            $('.category-column').change(function() {
                var form          = $(this).parents('form');
                var uid           = $(this).val();
                var target_id     = $('[name="target_id"]', form);
                if (uid == null || uid.length == 0) {
                    $(target_id).empty();
                    $(target_id).append('<option value="">未選擇</option>');
                    $(target_id).select2();
                    return;   
                }
                $.ajax({
                    type : 'GET',
                    url  : "<?php echo e(route('manage::asset::get_by_category')); ?>",
                    dataType : 'json',
                    data : {
                        'id' : uid
                    },
                    success: function(sendback){
                        $(target_id).empty();
                        $(target_id).append('<option value="">未選擇</option>');
                        for (var i in sendback) {
                            $(target_id).append('<option value="' + sendback[i].id + '">' + sendback[i].no + ' - ' + sendback[i].asset_name + '</option>');    
                        }
                        $(target_id).select2();
                        $(target_id).select2('val', tmp_target_id);
                        tmp_target_id = '';
                    },
                    error: function(){
                        $(target_id).empty();
                        $(target_id).append('<option value="">未選擇</option>');
                        $(target_id).select2();
                        toastr['error']('發生錯誤，請重新整理後再嘗試');
                    }
                });
            });
            /*
            $( ".assetNo" ).autocomplete({
                search: function(event, ui) {
                    $(this).addClass('loading');
                },
                response(event, ui){
                    $(this).removeClass('loading');    
                },
                source:  function (request, response) {
                    jQuery.get("<?php echo e(route('manage::asset::search_assets_no_list')); ?>", {
                        no: request.term
                    }, function (data) {
                        // assuming data is a JavaScript array such as
                        // ["one@abc.de", "onf@abc.de","ong@abc.de"]
                        // and not a string
                        response(data);
                    });
                },
                select: function(e, ui){
                    var value = ui.item.value.split('  ');
                    var no    = value[0];
                    var form  = $(this).parents('form');
  
                    $.ajax({
                        type : 'GET',
                        url  : "<?php echo e(route('manage::asset::get_assets_by_no')); ?>",
                        dataType : 'json',
                        data : {
                            'no' : no
                        },
                        success: function(sendback){
                            $('[name="target_id"]', form).val(sendback.id);
                            //$('.assetName', form).val(sendback.asset_name);
                        },
                        error: function(){
                            toastr['error']('發生錯誤，請重新整理後再嘗試');
                        },
                        beforeSend: function( xhr ) {
                            //$('#loadbox').css('display', 'block');
                        }
                    }).done(function() {
                        //$('#loadbox').css('display', 'none');   
                    });
                },
            });
            */
            
            //$( ".assetNo" ).autocomplete( "option", "appendTo", "form" );
           
            $('#form_add').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block help-block-error', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",  // validate all fields including form hidden input
                rules:{
                    target_id:{
                        required:true
                    },
                    consuming:{
                        required:true
                    },
                },
                messages:{
                    target_id:{
                        required:'未輸入資產'
                    },
                    consuming:{
                        required:'領用人未選擇'
                    },
                },

                invalidHandler: function (event, validator) { //display error alert on form submit
                    $('#form_success_alert').hide();
                    $('#form_error_alert').show();
                    $('.modal').scrollTop($('#form_error_alert'));
                },

                highlight: function (element) { // hightlight error inputs
                   $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change done by hightlight
                    $(element)
                        .closest('.form-group').removeClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    label
                        .closest('.form-group').removeClass('has-error'); // set success class to the control group
                },

                submitHandler: function (form) {
                    $('#form_success_alert').show();
                    $('#form_error_alert').hide();
                    
                    var data = $("#form_add").serialize();
                    
                    //確認表單正確，Ajax送出
                    $.ajax({
                        type: 'POST',
                        dataType: 'json',
                        url: "<?php echo e(route('manage::asset::add_picklist')); ?>",
                        data: data,
                        success: function(sendback){
                            $('#modal_add_picklist').modal('hide');
                            window.location.reload();
                        },
                        error   : function ( data )
                        {
                            var errors = data.responseJSON;
                            //以下是目前測試到的可行解，但還是要實際嘗試才知道怎麼使用。
                            $.each(errors, function (key, data) {
                                console.log(key);
                                if( key == 'errors'){
                                    $.each(data, function (index, data) {
                                        $( "input[name='"+index+"']").closest('.form-group').addClass('has-error');
                                        $( "input[name='"+index+"']").closest('.form-control').after( '<span class="help-block help-block-error">'+data+'</span>' )
                                    });
                                } else if (key == 'message') {
                                    toastr['error'](data);    
                                }
                            });
                            $('#form_success_alert').hide();
                            $('#form_error_alert').show();
                            $('.modal').scrollTop($('#form_error_alert'));

                        }
                    });
                }
            });
            $('#form_edit').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block help-block-error', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",  // validate all fields including form hidden input
                rules:{
                    target_id:{
                        required:true
                    },
                    consuming:{
                        required:true
                    },
                },
                messages:{
                    target_id:{
                        required:'未輸入資產'
                    },
                    consuming:{
                        required:'領用人未選擇'
                    },
                },

                invalidHandler: function (event, validator) { //display error alert on form submit
                    $('#form_success_alert').hide();
                    $('#form_error_alert').show();
                    $('.modal').scrollTop($('#form_error_alert'));
                },

                highlight: function (element) { // hightlight error inputs
                   $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change done by hightlight
                    $(element)
                        .closest('.form-group').removeClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    label
                        .closest('.form-group').removeClass('has-error'); // set success class to the control group
                },

                submitHandler: function (form) {
                    $('#form_success_alert').show();
                    $('#form_error_alert').hide();
                    
                    var data = $("#form_edit").serialize();
                    
                    //確認表單正確，Ajax送出
                    $.ajax({
                        type: 'POST',
                        dataType: 'json',
                        url: "<?php echo e(route('manage::asset::update_picklist')); ?>",
                        data: data,
                        success: function(sendback){
                            $('#modal_edit_picklist').modal('hide');
                            window.location.reload();
                        },
                        error   : function ( data )
                        {
                            var errors = data.responseJSON;
                            //以下是目前測試到的可行解，但還是要實際嘗試才知道怎麼使用。
                            $.each(errors, function (key, data) {
                                console.log(key);
                                if( key == 'errors'){
                                    $.each(data, function (index, data) {
                                        $( "input[name='"+index+"']").closest('.form-group').addClass('has-error');
                                        $( "input[name='"+index+"']").closest('.form-control').after( '<span class="help-block help-block-error">'+data+'</span>' )
                                    });
                                } else if (key == 'message') {
                                    toastr['error'](data);    
                                }
                            });
                            $('#form_success_alert').hide();
                            $('#form_error_alert').show();
                            $('.modal').scrollTop($('#form_error_alert'));

                        }
                    });
                }
            });
        });

        var deleteassets = function(id) {
            bootbox.confirm("您確定要刪除指定的資產領用?", function(result) {
                if(result == true){
                    $.ajax({
                        type : 'DELETE',
                        dataType : 'json',
                        url  : "<?php echo e(route('manage::asset::delete_picklist')); ?>",
                        data : {
                            _token : $('#_token').val(),
                            id     : id
                        },
                        success : function(sendback){
                            window.location.reload();
                        },
                        error : function(sendback){
                            toastr['error']('刪除失敗，請重新整理後再試');
                        }
                    })
                }
            }); 
        }
        
        var callDataTable = function () {
            var table = $('#table_list');

            var oTable = table.dataTable({
                // Internationalisation. For more info refer to http://datatables.net/manual/i18n
                "language": {
                    "aria": {
                        "sortAscending": ": activate to sort column ascending",
                        "sortDescending": ": activate to sort column descending"
                    },
                    "emptyTable": "此列表目前沒有資料",
                    "info": "顯示第 _START_ 到第 _END_ 則 共有 _TOTAL_ 則",
                    "infoEmpty": "沒有找到符合的資料",
                    "infoFiltered": "(從 _MAX_ 筆資料中過濾)",
                    "lengthMenu": "顯示 _MENU_ 則",
                    "search": "快速篩選:",
                    "zeroRecords": "目前沒有任何資料",
                    "paginate": {
                        "previous":"上一頁",
                        "next": "下一頁",
                        "last": "最後",
                        "first": "最前"
                    }
                },
                "lengthMenu": [
                    [10, 20, 50, -1],
                    [10, 20, 50, "All"] // change per page values here
                ],
                // set the initial value
                "pageLength": 10,
                "aoColumns":[
                    {"sTitle":"<input type=\"checkbox\" class=\"group-checkable\" data-set=\"#table_list .checkboxes\"/>", "sClass" : "table-checkbox"},
                    {"sTitle":"領用編號"},
                    {"sTitle":"資產名稱"},
                    {"sTitle":"領用數量"},
                    {"sTitle":"領用人"},
                    {"sTitle":"領用時間"},
                    {"sTitle":"狀態"},
                    {"sTitle":"動作"},
                ],
                "aaData":[<?php echo $dataArray; ?>]
            });

            $('.group-checkable', table).change(function () {
                var set     = jQuery(this).attr("data-set");
                var checked = jQuery(this).is(":checked");
                jQuery(set).each(function () {
                    if (checked) {
                        $('#btn_mass_delete').show();
                        $(this).attr("checked", true);
                    } else {
                        $('#btn_mass_delete').hide();
                        $(this).attr("checked", false);
                    }
                });
                jQuery.uniform.update(set);
            });

            $('.checkboxes', table).change(function(){
                var checkedNum = $('.checkboxes:checked').length;
                if(checkedNum > 0){
                    $('#btn_mass_delete').show();
                }else{
                    $('#btn_mass_delete').hide();
                }
            });
        }
    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layout.manage', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>