(function(KDApi,$,_){
    function MyComponent(model){
        this._setModel(model);
    }

    var isUpdate = false;
	var pwyWebsocket =null;
	var pwyScanFiles;
	var scannerIndex = '';
	var fullScanSources = '';
	function appendToList(sources){
        if ($('#dialog-selectsourceBox').length === 0) {
            var cssStr = '<style style="text/css">.dialog-selectsourceBox{display:none;position:absolute;width:100vw;height:100vh;left:0;top:0;z-index:99999999999}.dialog-selectsourceBox .mask{z-index:2;position:absolute;background:#333;opacity:.5;left:0;top:0;width:100%;height:100%}.dialog-selectsource{z-index:5;position:absolute;top:30%;left:0;right:0;margin:auto auto;font-size:14px;background-color:#eee;border:2px solid #777;border-left:2px solid #ddd;border-top:2px solid #ddd;padding:15px 20px 0 20px;width:300px}.dialog-selectsource p{padding:0;margin:0;font-weight:bold}.dialog-selectsource-sourcelist{height:60px;padding:0;background-color:#fff;border:2px solid #777;border-right:2px solid #ddd;border-bottom:2px solid #ddd;overflow-y:auto;overflow-x:hidden;min-width:240px;-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.dialog-selectsource-sourcelist ul{list-style:none;margin:0;padding:0}.dialog-selectsource-sourcelist li{padding:2px 0 2px 2px;margin:0;list-style:none;cursor:pointer;line-height:18px}.dialog-selectsource-sourcelist li:hover{background-color:#eff6fd}.dialog-selectsource-sourcelist li.dialog-selectsource-sourcelist-li-selected{background-color:#c7defc}.dialog-selectsource-sourcelist-ul{list-style:none;margin:0;padding:0}.dialog-selectsource-buttons>input{min-width:80px;height:20px;margin:10px 10px 20px 0;line-height:0}</style>';
            $('head').append(cssStr);
            var liStr = '';
            for (var i = 0; i < sources.length; i++) {
                scannerIndex = 0;
                var cls = '';
                if (i === 0) {
                    cls = 'dialog-selectsource-sourcelist-li-selected';
                }
                liStr +='<li data="' + i + '" class="' + cls +'">' + sources[i] + '</li>';
            }
            var boxHtml = '<div id="dialog-selectsourceBox" class="dialog-selectsourceBox">';
            boxHtml +='<div class="mask"></div>';
            boxHtml +='<div class="dialog-selectsource">';
            boxHtml +='<p>选择扫描仪类型</p>';
            boxHtml +='<div class="dialog-selectsource-sourcelist">';
            boxHtml +='<ul id="dialog-selectsource-sourcelist-ul">' + liStr + '</ul>';
            boxHtml +='</div>';
            boxHtml +='<div class="dialog-selectsource-buttons">';
            boxHtml +='<input type="button" value="确定" class="startScanBtn" />';
            boxHtml +='<input type="button" value="取消" class="cacelScanBtn" />';
            boxHtml +='</div></div></div>';
            $('body').prepend(boxHtml);
            $('#dialog-selectsourceBox').css({'display': 'block'});
        }
	}

	function startScan(model,props){
		console.log('-----startScan',props);
		if (scannerIndex === '' && fullScanSources.length > 0) {
			scannerIndex = 0;
			$('#dialog-selectsourceBox ul li').eq(0).addClass('dialog-selectsource-sourcelist-li-selected');
			$('#dialog-selectsourceBox').css({'display': 'block'});
			return;
		}
		showLoading('#'+model.pageId, ["扫描上传中.."]);
		var popsData=props.data; 
		var savePath=popsData['savePath']; 
		var operate=popsData['operate']; 
		pwyScanFiles.startScan({
			sourceInfo: {
				sourceIndex: scannerIndex
			},
			data: {},
			onConnected: function(scanSources) {
				if (scanSources && scanSources.length > 0) {
					fullScanSources = scanSources;
					if (scanSources.length === 1) {
						scannerIndex = 0;
					} else {
						appendToList(scanSources);
					}					
				}				
			},
			stepUploadStart: async (item) => {
                console.log('stepUploadStart', item)
				return {
                    errcode: '0000',
                    otherData: { // 需要上传时添加的数据
                    url: savePath+item.name 
					}
                };
            },
			stepUploadFinish: function(itemData, fileInfo) { // 每一步上传处理完成后的回调
                var filePath = fileInfo.localUrl;  
                console.log('上传成功',itemData);
				model.invoke('scanner_success', {"operate":operate,"data":itemData});   
            },
			uploadFinish: (res) => {
				if(res.errcode&&'0000'!=res.errcode){
					console.log('-----scanner_fail',res);
					hideLoading('#'+model.pageId);
					model.invoke('scanner_fail', res);  
				}else{
					hideLoading('#'+model.pageId);
					model.invoke('scanner_uploadFinish', res);  
				}
				console.log(res);
			}
		});
	}
    MyComponent.prototype = {
        _setModel: function(model) {
            this.model = model;
        },
        init:function(props){
			console.log('-----init',props);
			isUpdate = false;  
			var mode=this.model;		
			$(document).on('click', '#dialog-selectsourceBox ul li',function(){
				scannerIndex = parseInt($(this).attr('data'));
				$('#dialog-selectsourceBox ul li').removeClass('dialog-selectsource-sourcelist-li-selected');
				$(this).addClass('dialog-selectsource-sourcelist-li-selected');
			});
			$(document).on('click', '#dialog-selectsourceBox ul li',function(){
				scannerIndex = parseInt($(this).attr('data'));
				$('#dialog-selectsourceBox ul li').removeClass('dialog-selectsource-sourcelist-li-selected');
				$(this).addClass('dialog-selectsource-sourcelist-li-selected');
			});
			$(document).on('click', '#dialog-selectsourceBox .startScanBtn',function(){
				$('#dialog-selectsourceBox').css({'display': 'none'});
				startScan(mode,props);
			});
			$(document).on('click', '#dialog-selectsourceBox .cacelScanBtn',function(){
				scannerIndex = '';
				$('#dialog-selectsourceBox').css({'display': 'none'});
				$('#dialog-selectsourceBox ul li').removeClass('dialog-selectsource-sourcelist-li-selected');
			});
            
        },
        update:function(props){
			console.log('-----update',props);
            isUpdate = true; 
			setHtml(this.model,props,isUpdate); 
        },
        destoryed:function(){
            console.log('-----destoryed',this.model);
			document.getElementById('outDwtcontrolContainer').remove();
        }

    }
	var setHtml = function(model,props,isUpdate){
		var data={};
		var uploadUrl='';
		var operate=null;
		if(props!=null&&props.data!=null){
			var popsData=props.data;
			uploadUrl=popsData['uploadUrl'];
			  operate=popsData['operate']; 
		}
		if(operate){ 
			if (!pwyScanFiles) { 
				KDApi.loadFile(['./rq-scanner/pwyPolyfill.js', './rq-scanner/lib/JsScanner-min.js','./rq-scanner/scanFiles.js','./dialog.css'], model, () => {
					pwyScanFiles = new ScanFiles.scanFiles({
						limit: 2, // 上传时的并发控制
						staticUrl: '', // 指定加载扫描仪库文件的根路径
						uploadUrl: uploadUrl, // 上传路径
						downloadUrl: './JsScanner.msi',
						scanFileStaticJs: [],
						version: 16 // 目前16是最新版本,不传默认还是15.若更新到17则需要新增v17的文件夹
					}); 
					dialog('#'+model.pageId);
					console.log('-----loadFile',props); 
					startScan(model,props); 
				});
			}else{
				startScan(model,props);
			}
		
		}
    }
	
	
	
	// Other Code
    var destoryedFunc = function() {
		console.log('destoryedFunc。。。')
		if (loading) {
		    hideLoading();
			loading = false;
		}
    }
	
	function dialog(divname) {
		this.html = "<div class='loadModal'>" + 
			"<div class='dialog'>" + 
				"<div class='loading'>" +
					"<div class='round0'><a class='cirle col1'></a></div>" +
					"<div class='round1'><a class='cirle col2'></a></div>" +
					"<div class='round3'><a class='cirle col3'></a></div>" +
					"<div class='round2'><a class='cirle col4'></a></div>" +
				"</div>" + 
				"<div class='contentTxt'></div>" +
			"</div></div>";
		$(divname).append(this.html);
	}

	function showLoading(divname, content){
		var length=$(divname).find('.loadModal').length;
		if(length<1){
			dialog(divname);
		} 
		var contentHtml = '';
		if (content) {
		   for (var j=0; j< content.length; j++) {
			contentHtml += '<p>'+ content[j] +'<p>';
		   }
		}
		$(divname).find('.dialog').find('.contentTxt').empty().append(contentHtml);
		this.index = 0;
		this.animateObj = setInterval(() => {
			var current = $('.loading') .find('.round' + this.index) .find('.cirle');
			this.index +=1;
			scaleRound(current);
			if (this.index == 4) {
				this.index = 0;
			}
		}, 400);
		
		function scaleRound(name){
			name.animate({
			width: '20px',
			height: '20px',
			}, 300, () => {
				name.animate({
					width: '16px',
					height: '16px',
				}, 200);
			});
		}
	}

	function hideLoading(divname) {
		clearInterval(this.animateObj);
		$(divname).find('.loadModal').remove();
	}
    KDApi.register('scanner', MyComponent)
})(window.KDApi,jQuery);
