<script type="text/javascript">
function clearText(field){	
	if (field.defaultValue == field.value) 
		field.value = '';	
	else if (field.value == '') 
		field.value = field.defaultValue;
}
</script>
	<script src="<?php echo $this->baseUrl ?>assets/thema/apk/js/zxing_library.min.js"></script>

		<img id="pilihKamera" src="<?php echo $this->baseUrl."assets/thema/apk/img/"; ?>iconmonstr-qr-code-2.png" style="width: 50px;">
		<div style="text-align: center; margin-left: -20px">
			<video id="previewKamera" style="width: 400px;height: 300px; margin-left: -50"></video>
		</div>
		<div>
			<input type="text" id="bar" name="bar" style="text-align: center" onfocus="clearText(this)" onblur="clearText(this)" value="KETIK-BARCODE" autocomplete="off">
			<div style="margin-top: -44px; text-align: right; margin-right: 0px;">
				<img src="<?php echo $this->baseUrl ?>assets/thema/apk/img/cari.png" id="_btnCariBar" style="width: 37px;">
			</div>
		</div>
		<div>
		<form method="POST" id="formAjaxDefault">
			<input type="text" id="kd_inv" name="kd_inv" readonly style="background-color: #e8fdff; text-align: center">
			<input type="text" id="nm_inv" name="nm_inv" readonly style="background-color: #e8fdff; text-align: center">
			<input type="number" id="qty" name="qty" style="text-align: center" onfocus="clearText(this)" onblur="clearText(this)" value="QTY">
			<input type="submit" value="SIMPAN" id="_simpan">
			<input type="hidden" value="<?php echo $_GET['gudang'] ?>" name="gudang" id="gudang">
			<input type="hidden" value="<?php echo $_GET['lok'] ?>" name="lok" id="lok">
		</div>
		</form>
		<div id="errorDisplay"></div>
		<?php for($i = 1; $i <= 8; $i++){ ?>
		<div>&nbsp;</div>
		<?php } ?>


<script type="text/javascript">
$(document).ready(function(){
	let selectedDeviceId = null;
    const codeReader = new ZXing.BrowserMultiFormatReader();
    const sourceSelect = $("#pilihKamera");

    $(document).on('click','#pilihKamera',function(){
        selectedDeviceId = $(this).val();
        if(codeReader){
            codeReader.reset()
            initScanner()
        }
    })
	
	_makeLoadDetMut = false;
	$('#bar').keyup(function(e){
		if(e.which === 13){
			makeLoadItem('bar')
		}
	})
	$('#_btnCariBar').click(function(e){
		makeLoadItem('bar')
	})
	
	$('#_simpan').click(function(e){
		e.preventDefault();
		_conf = confirm("Yakin Simpan?");
		if(_conf){
			$('#_loadingSimpan').html('Proses...');
			if(_makeLoadDetMut != false){
				_makeLoadDetMut.abort();
			}

			_makeLoadDetMut = $.ajax({
			type: 'POST',
				url: '<?php echo $this->baseUrl; ?>sopcb/proses/',
				data: $('#formAjaxDefault').serialize(),
				success: function(data) {
					$('#_loadingSimpan').html('www.rasio.id');
					$('#errorDisplay').html(data);
				}
			})
		}
	})
	
	function makeLoadItem(_mode){
		$('#nm_inv').val('Loading...');
		if(_makeLoadDetMut != false){
			_makeLoadDetMut.abort();
		}
		_bar = $('#bar').val();
		_url = '<?php echo $this->baseUrl; ?>sopcb/cek_nama/&mode='+_mode+'&bar='+_bar;
		_makeLoadDetMut = $.ajax({
		type: 'POST',
			url: _url,
			data: $('#formAjaxDefault').serialize(),
			success: function(data) {
				$('#errorDisplay').html(data);
			}
		})
	}

    function initScanner() {
        codeReader
        .listVideoInputDevices()
        .then(videoInputDevices => {
            videoInputDevices.forEach(device =>
                console.log(`${device.label}, ${device.deviceId}`)
            );

            if(videoInputDevices.length > 0){
                 
                if(selectedDeviceId == null){
                    if(videoInputDevices.length > 1){
                        selectedDeviceId = videoInputDevices[1].deviceId
                    } else {
                        selectedDeviceId = videoInputDevices[0].deviceId
                    }
                }
                 
                 
                if (videoInputDevices.length >= 1) {
                    sourceSelect.html('');
                    videoInputDevices.forEach((element) => {
                        const sourceOption = document.createElement('option')
                        sourceOption.text = element.label
                        sourceOption.value = element.deviceId
                        if(element.deviceId == selectedDeviceId){
                            sourceOption.selected = 'selected';
                        }
                        sourceSelect.append(sourceOption)
                    })
             
                }

                codeReader
                    .decodeOnceFromVideoDevice(selectedDeviceId, 'previewKamera')
                    .then(result => {

                            //hasil scan
                            console.log(result.text)
                            $("#kd_inv").val(result.text);
							makeLoadItem('scan');
							
                            if(codeReader){
                                codeReader.reset()
                            }
                    })
                    .catch(err => console.error(err));
                 
            } else {
                alert("Camera not found!")
            }
        })
        .catch(err => console.error(err));
    }

    if (navigator.mediaDevices) {
        initScanner()
    } else {
        alert('Cannot access camera.');
    }
})	
</script>
