@extends('layout')


@section('content')

<div class="page-header page-header-default">
	<div class="breadcrumb-line">
		<ul class="breadcrumb">
			<li><a href="index.html"><i class="icon-home2 position-left"></i> Produksi</a></li>
			<li class="active">Bon Bahan</li>
		</ul>
	</div>
</div>

<div class="content">
	<div class="panel panel-flat">
		<div class="panel-heading">
			<h5 class="panel-title">Form Bon Bahan</h5>
			<div class="heading-elements">
				<ul class="icons-list">
		      		<li><a data-action="collapse"></a></li>
		      	</ul>
	       	</div>
	    </div>
	    <div class="panel-body">
	    	<form class="form-horizontal" action="{{url('barangkeluar/simpan')}}" method="post" autocomplete="off" enctype="multipart/form-data">
	    	<input type="hidden" name="_token" value="{{ csrf_token() }}">
	    	<input type="hidden" name="id_barangkeluar" value="{{ $data['data']['id_barangkeluar']}}">
        	<div class="col-sm-6">
        		<div class="form-group">
        			<label class="control-label col-sm-4">Tanggal Pengambilan</label>
        			<div class="col-sm-8">
        				<input class="form-control datepicker" type="text" name="tanggal" value="{{ ($data['data']['tanggal'] == '') ? date('d-m-Y'):date('d-m-Y', strtotime($data['data']['tanggal'])) }}" placeholder="Tanggal" required/>
        			</div>
        		</div>
        	
        		
        		<div class="form-group">
        			<label class="control-label col-sm-4">No.Order</label>
        			<div class="col-sm-8">
        				@php if($data['data']['id_barangkeluar']!=""){@endphp
        				<input type="hidden" name="workorder" value="{{$data['data']['id_workorder']}}">
        				<select class="form-control select-search" disabled="">
        					<option value="">-- Pilih Order --</option>
        					@php foreach($data['workorder'] as $row){ 
        					$sel = $data['data']['id_workorder'];
        					@endphp
        					<option value="{{ $row->id_workorder }}" {{ ($row->id_workorder == $sel) ? "selected":"" }}  > {{ $row->no_workorder }}
        					</option>
        					@php } @endphp
        				</select>
        				@php }else{ @endphp
        				<select class="form-control select-search" name="workorder" required>
        					<option value="">-- Pilih Order --</option>
        					@php foreach($data['workorder'] as $row){ 
        					$sel = $data['data']['id_workorder'];
        					@endphp
        					<option value="{{ $row->id_workorder }}" {{ ($row->id_workorder == $sel) ? "selected":"" }}  > {{ $row->no_workorder }}
        					</option>
        					@php } @endphp
        				</select>
        				@php } @endphp
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Proses Produksi</label>
        			<div class="col-sm-8">
        				@php if($data['data']['id_barangkeluar']!=""){ @endphp
        				<input type="hidden" name="proses" value="{{$data['data']['id_proses']}}">
        				<select class="form-control select-search" disabled="">
        					<option value="">-- Pilih Produksi --</option>
        					@php foreach($data['proses'] as $row){ 
        					$sel = $data['data']['id_proses'];
        					$old = old('proses');
        					@endphp
        					<option value="{{ $row->id_proses }}" {{ ($row->id_proses == $sel) ? "selected":"" }}  > {{ $row->nama_proses2.' - '.$row->nama_proses }}
        					</option>
        					@php } @endphp
        				</select>
        				@php }else{ @endphp
        				<select class="form-control select-search" name="proses" required>
        					<option value="">-- Pilih Produksi --</option>
        					@php foreach($data['proses'] as $row){ 
        					$sel = $data['data']['id_proses'];
        					$old = old('proses');
        					@endphp
        					<option value="{{ $row->id_proses }}" {{ ($row->id_proses == $sel) ? "selected":"" }}  > {{ $row->nama_proses2.' - '.$row->nama_proses }}
        					</option>
        					@php } @endphp
        				</select>
        				@php } @endphp
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Tanggal Perkiraan Selesai</label>
        			<div class="col-sm-8">
        				<input class="form-control datepicker" type="text" name="tanggal_perkiraan" value="{{ ($data['data']['tanggal_perkiraan'] == '') ? old('tanggal_perkiraan') : date('d-m-Y',strtotime($data['data']['tanggal_perkiraan'])) }}" placeholder="Tanggal" required/>
        			</div>
        		</div>
        	</div>
        	<div class="col-sm-6">
        		<div class="form-group">
        			<label class="control-label col-sm-4">Rekanan</label>
        			<div class="col-sm-8">
        				<select class="form-control select-search" name="rekanan">
        					<option value="">-- Pilih Rekanan --</option>
        					@php foreach($data['rekanan'] as $row){
        					$sel = $data['data']['id_rekanan']; @endphp
        					<option value="@php echo $row->id_rekanan @endphp" {{ ($row->id_rekanan == $sel) ? "selected":"" }}>
        						{{$row->nama}}
        					</option>
        					@php } @endphp
        				</select>
        			</div>
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Pegawai</label>
        			<div class="col-sm-8">
        				<select name="pegawai" class="form-control select-search" id="id_pegawai">
        					<option value="">--- Pilih Pegawai ---</option>
        					@php $no=1; foreach($data['pegawai'] as $row){
        					$sel = $data['data']['id_pegawai'];
        					@endphp
        						<option value="{{ $row->id_pegawai }}" {{ ($row->id_pegawai == $sel) ? "selected":""}}>{{ $row->nama_pegawai }}</option>
        					@php } @endphp
        				</select>
        			</div>
        		</div>
        		
        		<!-- <div class="form-group">
        			<label class="control-label col-sm-4">Pegawai</label>
        			<div class="col-sm-8">
        				<select name="pegawai" class="form-control select-search" id="id_pegawai">
        					<option value="">--- Pilih Pegawai ---</option>
        					@php $no=1; foreach($data['pegawai'] as $row){
        					$sel = $data['data']['id_pegawai'];
        					@endphp
        						<option value="{{ $row->id_pegawai }}" {{ ($row->id_pegawai == $sel) ? "selected":""}}>{{ $row->nama_pegawai }}</option>
        					@php } @endphp
        				</select>
        			</div>
        		</div> -->
        		<!-- <select class="form-control hidden" name="satuan" >
        					<option value="">-- Pilih Satuan --</option>
        					@php foreach($data['satuan'] as $row){ 
        					
        					@endphp
        					<option value="{{ $row->id_satuan }}"> {{ $row->nama_satuan }}
        					</option>
        					@php } @endphp
        				</select> -->
        		<div class="form-group" id="btnworkorder">
        			@if (old('proses'))
				    <div class="alert alert-warning">
				    	<button type="button" class="close" data-dismiss="alert"><span>×</span><span class="sr-only">Close</span></button>
				        <i><b>*Rekanan atau Pegawai belum di isi</b></i>
				    </div>
				@endif
				  
        		</div>
        	</div>
        	

        	<!-- <div class="col-sm-6">
        		<div class="form-group">
        			<label class="control-label col-ms-12"></label>
        		</div>
        		<div class="form-group">
        			
        		</div>
        		<div class="form-group">
        			<label class="control-label col-sm-4">Pegawai</label>
        			<div class="col-sm-8">
        				<select name="popup_pegawai" class="form-control select-search">
        					
        				</select>
        			</div>
        		</div>
        		
        	</div> -->

        	
        	<div class="col-sm-12 form-group">
        	<h5 class="panel-title">Detail Barang</h5>
        	<br><a href="#" class="btn btn-success" style="margin-bottom: 1%;" id="btn_tambah_item">Tambah Barang</a></div>
        	<div class="col-ms-12">
        	<table class="table table-stripped" id="table_barang">
	    	<thead>
				<tr>
					<th>No</th>
					<th>Kode Barang</th>
					<th>Nama Barang</th>
					<th>Gudang</th>
					<th>Stok <b id="detail_satuanawal"></b> <input type="hidden" name="nilai_detail_satuanawal" id="nilai_detail_satuanawal"> <input type="hidden" name="popup_idsatuanawal" id="popup_idsatuanawal"></th>
					<th>Jumlah <b id="detail_satuanawal2"></b></th>
					<th>jumlah konversi <b id="detail_satuanakhir"></b> <input type="hidden" name="nilai_detail_satuanakhir" id="nilai_detail_satuanakhir"> <input type="hidden" name="popup_idsatuanakhir" id="popup_idsatuanakhir"></th>
					<th class="text-center">Aksi</th>
				</tr>
			</thead>
			<tbody>
				
			</tbody>
	    </table>
        	</div>
        	
        	
             <div class="col-md-6"></div>
             <br>
             <div class="col-md-12">
             <a href="{{url('barangkeluar')}}" class="btn bg-warning-400">Kembali</a>
             <div class="form-group pull-right">
             	<button class="btn btn-primary" type="submit">Simpan</button> 
             	<!-- <button class="btn btn-primary" type="submit">Simpan</button> -->
             </div>
         </div>
	    </div>


		<input type="hidden" name="td_total" class="form-control">
		<input type="hidden" name="td_netto" class="form-control">
	    </form>
	</div>
</div>

<!---Modal--->
<div class="modal fade" id="exampleModal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg" role="document">
	    <div class="modal-content">
	    	<div class="modal-header">
	    		<h5 class="modal-title" id="exampleModalLabel">Data</h5>
	    		<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></button>
	      	</div>
	      	<div class="modal-body">
	      		<form class="form-horizontal" autocomplete="off">
	      			<input type="hidden" name="popup_id_table">
	      			<div class="form-group">
	      				<label class="control-label col-sm-4">Gudang</label>
	      				<div class="col-sm-8">
	      					<select class="form-control select-search" name="popup_gudang">
	      						|<option value="">-- Pilih Gudang --</option>
	      						@php foreach($data['gudang'] as $row){
	      						
	      						@endphp
	      						<option value="{{$row->id_gudang}}" id="{{$row->id_gudang}}" nama="{{$row->nama_gudang}}">{{$row->nama_gudang}}</option>
	      						@php } @endphp
	      					</select>
	      				</div>
	      			</div>
	      			<div class="form-group">
	      				<label class="control-label col-sm-4">Barang</label>
	      				<div class="col-sm-8">
	      					<select class="form-control select-search" name="popup_barang">
	      						
	      					</select>
	      				</div>
	      			</div>
	      			<div class="form-group">
	      				<label class="control-label col-sm-4">Jumlah Stok</label>
	      				<div class="col-sm-8">
	      					<label class="control-label" name="popup_stok"></label>
	      				</div>
	      			</div>
	      			<div class="form-group">
	      				<label class="control-label col-sm-4">Jumlah <b id="popup_satuanawal"></b></label>
	      				<div class="col-sm-8">
	      					<input type="text" name="popup_jumlah" class="form-control number-only" onkeyup="maksimal($(this))">
	      				</div>
	      			</div>
	      			<div class="form-group" id="div_konversi">
	      				<label class="control-label col-sm-4">Jumlah Konversi <b id="popup_satuanakhir"></b></label>
	      				<div class="col-sm-8">
	      					<input type="text" name="popup_jumlah_konv" class="form-control number-only" onkeyup="maksimal($(this))">
	      				</div>
	      			</div>
	      			<div class="form-group" id="div_kualitas">
	      				<label class="control-label col-sm-4">Kualitas</label>
	      				<div class="col-sm-8">
	      					<select class="form-control select-search" name="popup_kualitas">
	      						<option value="">-- Pilih Kualitas --</option>
	      						@php foreach($data['kualitas'] as $d){@endphp
	      						<option value="{{$d->id_kualitas}}">{{ $d->nama_kualitas}}</option>
	      						@php } @endphp
	      					</select>
	      				</div>
	      			</div>
	      		</form>
	      	</div>
	      	<div class="modal-footer">
	        	<button type="button" class="btn btn-primary" id="btn_popup_simpan">Simpan</button>
	      	</div>
	    </div>
	</div>
</div>

<input type="hidden" name="store_konversi">


<!----Modal---->
<script type="text/javascript">
	var table_barang;
	var tb_no = parseInt(10000);
	$(document).ready(function(){
		table_barang = $("#table_barang").DataTable();
		table_barang.on( 'order.dt search.dt', function () {
            table_barang.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
                cell.innerHTML = i+1;
            } );
        } ).draw();


		/*get_barang();*/

		var id = '{{ $data['data']['id_barangkeluar']}}';
		if(id != ''){
			get_edit(id);
			readonly('[name=tanggal]', true);
			readonly('[name=tanggal_perkiraan]', true);
		}
		var pegawai = $("[name=pegawai]").val();
		if(pegawai > 0){
			disabled('[name=rekanan]', true);	
		}else{
			disabled('[name=rekanan]', false);
		}

		var rekanan = $("[name=rekanan]").val();
		if(rekanan > 0){
			disabled('[name=pegawai]',true);	
		}else{
			disabled('[name=pegawai]',false);
		}
	})


	$("#btn_tambah_item").click(function(){
		$("[name=popup_id_table]").val('');
		$("[name=popup_gudang]").val(null).trigger('change');
		$("[name=popup_barang]").html('');
		$("[name=popup_stok]").text('');
		$("[name=popup_jumlah]").val('');

		$("#div_konversi").addClass('hide');

		$("[name=popup_jumlah_konv]").val('');
		$("#popup_satuanawal").text('');
		$("#popup_satuanakhir").text('');

		$("#exampleModal").modal('show');
	})

	

	$("[name=pegawai]").change(function(){
		var pegawai = $("[name=pegawai]").val();

		if(pegawai > 0){
			disabled('[name=rekanan]', true);
			
		}else{
			disabled('[name=rekanan]', false);
		}
	});

	$("[name=rekanan]").change(function(){
		var rekanan = $("[name=rekanan]").val();

		if(rekanan > 0){
			disabled('[name=pegawai]',true);
			
		}else{
			disabled('[name=pegawai]',false);
		}
	});

	$("[name=popup_jumlah]").keyup(function(){
		var jum = parseFloat($("[name=popup_jumlah]").val());
		if(isNaN(jum) || jum == 0 || jum == ''){
			jum = parseFloat(0);
		}
		var nilai = parseFloat($("[name=store_konversi]").val());

		var tot = jum*nilai;
		$("[name=popup_jumlah_konv]").val(tot);
	})

	$("[name=popup_jumlah_konv]").keyup(function(){
		var jum = parseFloat($("[name=popup_jumlah_konv]").val());
		if(isNaN(jum) || jum == 0 || jum == ''){
			jum = parseFloat(0);
		}
		var nilai = parseFloat($("[name=store_konversi]").val());

		var tot = jum/nilai;
		$("[name=popup_jumlah]").val(tot);
	})

	
	$("[name=proses]").change(function(){
		var id_proses = $(this).val();
		var id_workorder = $("[name=workorder]").val();
		var gudang = $('[name=popup_gudang]').html();
		var satuan = $('[name=satuan]').html();
		$.ajax({
			url: "{{url('barangkeluar/cek_proses')}}",
			type: "post",
			dataType: "json",
			data: {id_proses : id_proses,id_workorder : id_workorder},
			headers : {
				'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			},
			success: function(result){
				if(result.length > 0){
						table_barang.clear().draw();
						$('#btnworkorder').html('<div class="alert alert-warning" id="alert_work">'+
						    	'<button type="button" class="close" data-dismiss="alert"><span>×</span><span class="sr-only">Close</span></button>'+
						        '<i><b>*Proses '+result[0].nama_proses+' sudah dilakukan</b></i>'+
						    '</div>');
				}else{
						$("#alert_work").hide();
						$.ajax({
						url: "{{url('barangkeluar/get_workorder_detail')}}",
						type: "post",
						dataType: "json",
						data: {id_workorder : id_workorder},
						headers : {
							'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
						},
						success : function(respon){
							if(respon.length > 0){
								table_barang.clear().draw();
								for(i in respon){
									table_barang.row.add(['<div><center></center></div>',
										'<div id="list_kode'+respon[i].id+'">'+respon[i].kode_barang+'</div>',
										'<div id="list_nama'+respon[i].id+'">'+respon[i].nama_barang+'</div>',
										'<div id="list_gudang'+respon[i].id+'"><select class="select-search form-control id_proses_gudang" name="tabel_idgudang[]" id="tabel_idgudang'+respon[i].id+'">'+gudang+'</select></div>',
										'<div id="list_stok'+respon[i].id+'"><input type="text" class="form-control number-only tabel_stok" name="tabel_stok[]" id="tabel_stok'+respon[i].id+'" readonly><p id="tabel_d_stok'+respon[i].id+'" class="tabel_d_stok"></p></div>',
										'<div id="list_jumlah'+respon[i].id+'"><input type="text" class="form-control number-only" name="tabel_jumlah[]" id="tabel_jumlah'+respon[i].id+'" onkeyup="maksimal($(this))"></div>',
										'<div id="list_jumlah_konv'+respon[i].id+'"><input type="text" class="form-control number-only tabel_jumlah_konv" name="tabel_jumlah_konv[]" id="tabel_jumlah_konv'+respon[i].id+'" readonly></div>',
										'<div><button type="button" id="btnedit'+respon[i].id+'" class="btn bg-warning-400" onclick="edit_table('+respon[i].id+')"><i class="icon-pencil"></i> </button><button id="btnhapus'+respon[i].id+'" class="btn bg-danger-800" type="button" onclick="hapus($(this))"><i class="icon-eraser"></i></button></div>'+
										'<input type="hidden" name="tabel_id[]" class="tabel_id" id="tabel_id'+respon[i].id+'" value="'+respon[i].id+'">'+
										'<input type="hidden" name="tabel_idbarangkeluar[]" id="tabel_idbarangkeluar'+respon[i].id+'" value="'+respon[i].id_barang+'">'+
										'<input type="hidden" name="tabel_idbarang[]" class="id_proses_barang" id="tabel_idbarang'+respon[i].id+'" value="'+respon[i].id_barang+'">'
										]).draw(false);
									$('.select-search').select2();
									$('#tabel_idgudang'+respon[i].id).change(function(){
									var id_gudang = $(this).parents('tr').find('.id_proses_gudang').val();
									var id_barang = $(this).parents('tr').find('.id_proses_barang').val();
									var tabel_id =  $(this).parents('tr').find('.tabel_id').val();
									var tr = $(this);
									get_proses_jml(id_gudang,id_barang,tabel_id,tr);
									
								})
									$("#tabel_jumlah"+respon[i].id).keyup(function(){
										var jumlah = $(this).val();
										var konversi = $("[name=nilai_detail_satuanakhir]").val();
										var total = parseFloat(jumlah)*parseFloat(konversi);
										var stok = $(this).parents('tr').find('.tabel_stok').val();
										if(isNaN(total) || total == 0 || total == ""){
											total = parseFloat(0);
										}
										
										var d_stok = parseFloat(stok)-parseFloat(jumlah);
										if(isNaN(d_stok) || d_stok == 0 || d_stok == ""){
											d_stok = parseFloat(0);
										}
										/*$("#tabel_stok"+respon[i].id).val(d_stok);*/
										$(this).parents('tr').find('.tabel_d_stok').text(d_stok);
										console.log(d_stok);
										
										// $('[name=tabel_jumlah]').each(function() {      
								  //       var jum = ($(this).val());
								  //       var j_stok = $("[name=tabel_stok]").val();
									 //    var s_total = parseInt(stok)-parseFloat(jum);
										// if(isNaN(s_total) || s_total == "" || s_total == 0){
										// 	s_total = parseFloat(0);
										// }
										// $(this).parents('tr').find('.tabel_stok').val(s_total);  
										 

								  //   });
										$(this).parents('tr').find('.tabel_jumlah_konv').val(total); 
										
									});

								}

							}else{
								table_barang.clear().draw();
							}
						}
					})
				}
			}
		})


	})

	
	function get_proses_jml(gudang,barang,id,tr){
		var n = parseInt(0);
		$.ajax({
			url: "{{url('barangkeluar/get_barang')}}",
			type: 'post',
			dataType: "json",
			data: {id : gudang, id_barang : barang},
			headers : {
				'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			},
			success: function(respon){
				
				if(respon.length > 0){
					var stok = parseInt(respon[0].stok);
					$('#tabel_stok'+id).val(stok);
				}else{
					var stok = parseInt(0);
					$('#tabel_stok'+id).val(stok);
					hapus(tr);
					$('#btnworkorder').html('<div class="alert alert-warning">'+
				    	'<button type="button" class="close" data-dismiss="alert"><span>×</span><span class="sr-only">Close</span></button>'+
				        '<i><b>*Pesan terlebih dahulu</b></i>'+
				    '</div>')
				    
				}
				$.ajax({
					url: "{{ url('barangkeluar/get_proses_konversi')}} ",
					type: 'post',
					data: {id : barang},
					headers : {
						'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
					},
					success: function(result){

						if(result.length > 0){							
							var n = parseInt(result[0].nilai_akhir)/parseInt(result[0].nilai_awal);
							var b = n*stok;
							$('#tabel_jumlah_konv'+id).val(b);
							$("#detail_satuanawal").text(result[0].satuan_awal);
							$("#detail_satuanawal2").text(result[0].satuan_awal);
							$("#detail_satuanakhir").text(result[0].satuan_akhir);
							$("#nilai_detail_satuanawal").val(result[0].nilai_awal);
							$("#nilai_detail_satuanakhir").val(result[0].nilai_akhir);
							$("#popup_idsatuanawal").val(result[0].id_satuanawal);
							$("#popup_idsatuanakhir").val(result[0].id_satuanakhir);
						}else{
							var b = parseInt(0);
							$('#tabel_jumlah_konv'+id).val(b);
							$("[name=popup_jumlah_konv]").val('');
							$("#detail_satuanawal").text(result.satuan_awal);
							$("#detail_satuanawal2").text(result.satuan_awal);
							$("#detail_satuanakhir").text('');	
							$("#nilai_detail_satuanawal").val(parseInt(0));
							$("#nilai_detail_satuanakhir").val(parseInt(0));
							$("#popup_idsatuanawal").val("");
							$("#popup_idsatuanakhir").val("");
						}

						var total = parseInt(0);
						$('input[id^="tabel_jumlah'+id+'"]').each(function() {      
				        var val = ($(this).attr('id'));
				        val = val.replace('tabel_stok'+id, '');
				        if($("#tabel_idbarang"+val).val() == barang){
				        	var jum = $("#tabel_stok"+val).val();
					        total += parseInt(jum);
				        }

				    });

						if(respon.length > 0){
							if($("[name=popup_id_table]").val() == ''){
								nilai = respon[0].stok-total;
								// var n = parseInt(result[0].nilai_akhir)/parseInt(result[0].nilai_awal);
							}else{
								nilai = (respon[0].stok-total)+parseInt($("#tabel_jumlah"+id).val());
								// var n = parseInt(0);
							}
							$("#tabel_jumlah"+id).attr('min', 0);
							$("#tabel_jumlah"+id).attr('max', nilai);
							
							$("#tabel_jumlah_konv"+id).attr('min', 0);
							$("#tabel_jumlah_konv"+id).attr('max', nilai*n);

							// $("#tabel_stok"+id).val('');
							$("#tabel_stok"+id).val(nilai);


						}
						
					}

				})


			}
		})

		// alert(id2);
	}
	

	$("[name=popup_gudang]").change(function(){
		var id_gudang = $(this).val();
		$.ajax({
			url: '{{ url('barangkeluar/get_barang') }}',
			type: 'post',
			dataType: 'json',
			data: {id : id_gudang, id_barang : ''},
			headers : {
				'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			},
			success: function(respon){
				$("[name=popup_barang]").html('');
				$("[name=popup_stok]").text('');
				if(respon.length > 0){
					$("[name=popup_barang]").append('<option value=""> -- Pilih Barang --</option>');
					for(i in respon){
						if(respon[i].stok > 0){
							$("[name=popup_barang]").append('<option value="'+respon[i].id_barang+'" barang="'+respon[i].nama_barang+'" kode="'+respon[i].kode_barang+'" satuan="'+respon[i].satuan+'">'+respon[i].kategori+' - '+respon[i].sub_kategori+' - '+respon[i].kode_barang+' - '+respon[i].nama_barang+'</option>');
						}
					}
				}else{
					$("[name=popup_barang]").html('');
					$("[name=popup_barang]").append('<option value=""> Stok Kosong </option>');
				}
			}
		})
	})

	$("[name=popup_barang]").change(function(){
		var id_gudang = $("[name=popup_gudang]").val();
		var id_barang = $(this).val();
		var nilai = parseInt(0);
		$.ajax({
			url: '{{ url('barangkeluar/get_barang') }}',
			type: 'post',
			dataType: 'json',
			data: {id : id_gudang, id_barang : id_barang},
			headers : {
				'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			},
			success: function(respon){

				$.ajax({
					url: "{{ url('barangkeluar/get_konversi')}} ",
					type: 'post',
					data: {id : id_barang},
					headers : {
						'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
					},
					success: function(result){
						if(result.length > 0){
							$("#div_konversi").removeClass('hide');

							$("#popup_satuanawal").text(result[0].satuan_awal);
							$("#popup_satuanakhir").text(result[0].satuan_akhir);
							var n = parseInt(result[0].nilai_akhir)/parseInt(result[0].nilai_awal);
							$("[name=store_konversi]").val(n);
						}else{
							$("#div_konversi").addClass('hide');
							$("[name=popup_jumlah_konv]").val('');
							$("#popup_satuanawal").text(result.satuan_awal);
							$("#popup_satuanakhir").text('');				
						}

						var total = parseInt(0);
						$('input[id^="tabel_jumlah"]').each(function() {
				              
				        var val = ($(this).attr('id'));
				        val = val.replace('tabel_jumlah', '');
				        if($("#tabel_idbarang"+val).val() == id_barang){
				        	var jum = $("#tabel_jumlah"+val).val();
					        total += parseInt(jum);
				        }
				              
				        });
						if(respon.length > 0){
							if($("[name=popup_id_table]").val() == ''){
								nilai = respon[0].stok-total;
							}else{
								nilai = (respon[0].stok-total)+parseInt($("[name=popup_jumlah]").val());
							}
							$("[name=popup_stok]").text(nilai+' '+respon[0].nama_satuan);
							$("[name=popup_jumlah]").attr('min', 0);
							$("[name=popup_jumlah]").attr('max', nilai);

							$("[name=popup_jumlah_konv]").attr('min', 0);
							$("[name=popup_jumlah_konv]").attr('max', nilai*$("[name=store_konversi]").val());
						}
					}
				})
			}
		})
	})



	$("#btn_popup_simpan").click(function(){
		var id_data = $("[name=popup_id_table]").val();
		var id_barang = $("[name=popup_barang]").val();
		var id_gudang = $("[name=popup_gudang]").val();
		var kode_barang = $("[name=popup_barang] :selected").attr('kode');
		var nama_barang = $("[name=popup_barang] :selected").attr('barang');
		var nama_gudang = $("[name=popup_gudang] :selected").attr('nama');
		var jumlah = $("[name=popup_jumlah]").val();
		var jumlah_konv = $("[name=popup_jumlah_konv]").val();
		if(isNaN(jumlah_konv) || jumlah_konv == "" || jumlah_konv == 0){
			jumlah_konv = jumlah;
		}
		var total = parseInt(jumlah);
		if(id_barang != '' && jumlah != ''){
			if(id_data == ''){
				table_barang.row.add(['<div><center></center></div>',
					'<div id="list_kode'+tb_no+'">'+kode_barang+'</div>',
					'<div id="list_nama'+tb_no+'">'+nama_barang+'</div>',
					'<div id="list_gudang'+tb_no+'">'+nama_gudang+'</div>',
					'<div id="list_jumlah'+tb_no+'">'+jumlah+'</div>',
					'<div id="list_jumlah_konv'+tb_no+'">'+jumlah_konv+'</div>',
					'<div><button type="button" class="btn bg-warning-400" onclick="edit_table('+tb_no+')"><i class="icon-pencil"></i> </button><button class="btn bg-danger-800" type="button"  onclick="hapus($(this))""><i class="icon-eraser"></i></button></div>'+
					'<input type="hidden" id="tabel_id'+tb_no+'" name="tabel_id[]" value="">'+
					'<input type="hidden" id="tabel_idbarang'+tb_no+'" name="tabel_idbarang[]" value="'+id_barang+'">'+
					'<input type="hidden" id="tabel_idgudang'+tb_no+'" name="tabel_idgudang[]" value="'+id_gudang+'">'+
					// '<input type="hidden" id="tabel_kodebarang'+tb_no+'" name="tabel_kodebarang[]" value="'+kode_barang+'">'+
					'<input type="hidden" id="tabel_jumlah'+tb_no+'" name="tabel_jumlah[]" value="'+jumlah+'">'+
					'<input type="hidden" id="tabel_jumlah_konv'+tb_no+'" name="tabel_jumlah_konv[]" value="'+jumlah_konv+'">'+
					'<input type="hidden" id="tabel_total'+tb_no+'" name="tabel_total[]" value="'+total+'">'
					]).draw(false);
			}else{
				$("#list_kode"+id_data).text(kode_barang);
				$("#list_nama"+id_data).text(nama_barang);
				$("#list_gudang"+id_data).text(nama_gudang);
				$("#list_jumlah"+id_data).text(jumlah);

				$("#tabel_id"+id_data).val(id_data);
				$("#tabel_idbarang"+id_data).val(id_barang);
				$("#tabel_namabarang"+id_data).val(nama_barang);				
				$("#tabel_jumlah"+id_data).val(jumlah);
				$("#tabel_total"+id_data).val(total);
			}
		
		$("#exampleModal").modal('hide');
		tb_no++;/*
		get_jum();*/
		}
	//	console.log(id_barang+"\n"+nama_barang+"\n"+jumlah+"\n"+harga);
	})

	function edit_table(id){

		var id_barang = $("#tabel_idbarang"+id).val();
		var id_gudang = $("#tabel_idgudang"+id).val();
		var jumlah = $("#tabel_jumlah"+id).val();
		var jumlah_konv = $("#tabel_jumlah_konv"+id).val();
		var harga = $("#tabel_harga"+id).val();

		$("[name=popup_id_table]").val(id);

		var FunctionOne = function () {
		  var r = $.Deferred();

		  $("[name=popup_gudang]").val(id_gudang).trigger('change');

		  setTimeout(function () {
		    r.resolve();
		  }, 1500);
		  return r;
		};

		var FunctionTwo = function () {
			$("[name=popup_barang]").val(id_barang).trigger('change');
			$("[name=popup_jumlah]").val(jumlah);
			$("[name=popup_jumlah_konv]").val(jumlah_konv);
			$("#exampleModal").modal('show');
		};

		FunctionOne().done(FunctionTwo);
	}


	function hapus(d){
	table_barang.row(d.parents('tr')).remove().draw();
	// get_jum();
	//  alert(d);
	}

	function get_edit(id){
		$.ajax({
			url: "{{ url('barangkeluar/get_edit')}} ",
			type: 'post',
			data: {id : id,},
			headers : {
				'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			},
			success: function(respon){
				console.log(respon);
				if(respon.length > 0){
					for(i in respon){
						table_barang.row.add(['<div><center></center></div>',
							'<div id="list_kode'+respon[i].id+'">'+respon[i].kode_barang+'</div>',
							'<div id="list_nama'+respon[i].id+'">'+respon[i].nama_barang+'</div>',
							'<div id="list_gudang'+respon[i].id+'">'+respon[i].nama_gudang+'</div>',
							'<div id="list_stok'+respon[i].id+'"></div>',
							'<div id="list_jumlah'+respon[i].id+'">'+respon[i].jumlah+'</div>',
							'<div id="list_jumlah_konv'+respon[i].id+'">'+respon[i].jumlah_konv+'</div>',
							'<div><button type="button" class="btn bg-warning-400" onclick="edit_table('+respon[i].id+')"><i class="icon-pencil"></i> </button><button class="btn bg-danger-800" type="button" onclick="hapus($(this))"><i class="icon-eraser"></i></button></div>'+
							'<input type="hidden" name="tabel_id[]" id="tabel_id'+respon[i].id+'" value="'+respon[i].id+'">'+
							'<input type="hidden" name="tabel_idbarangkeluar[]" id="tabel_idbarangkeluar'+respon[i].id+'" value="'+respon[i].id_barangkeluar+'">'+
							'<input type="hidden" name="tabel_idbarang[]" id="tabel_idbarang'+respon[i].id+'" value="'+respon[i].id_barang+'">'+
							'<input type="hidden" name="tabel_idgudang[]" id="tabel_idgudang'+respon[i].id+'" value="'+respon[i].id_gudang+'">'+
							'<input type="hidden" name="tabel_jumlah[]" id="tabel_jumlah'+respon[i].id+'" value="'+respon[i].jumlah+'">'+
							'<input type="hidden" name="tabel_jumlah_konv[]" id="tabel_jumlah_konv'+respon[i].id+'" value="'+respon[i].jumlah_konv+'">'
							]).draw(false);
					}

					// get_jum();
				}
				
			}
		})
	}


</script>

@endsection