var upload_pic = [];
var upload_file = [];
var upload = [];
var showUploadE;
var showUploadUrl;
var showUploadType = 1;
var showUploadCall = false;
var showUploadThis = false;
var showUploadIndex = false;
//创建监听函数
 var xhrOnProgress=function(fun) {
    xhrOnProgress.onprogress = fun; //绑定监听
     //使用闭包实现监听绑
    return function() {
        //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
        var xhr = $.ajaxSettings.xhr();
         //判断监听函数是否为函数
          if (typeof xhrOnProgress.onprogress !== 'function')
               return xhr;
           //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
            if (xhrOnProgress.onprogress && xhr.upload) {
                  xhr.upload.onprogress = xhrOnProgress.onprogress;
            }
            return xhr;
     }
 }

function showUpload(i,e,key,url,assets,type)
{
	layui.use(['upload','layer','element'], function() {
		var html = '';
		var layer = layui.layer;
		var config = {
		  type: 0,
		  title: e.attr('value'),
		  shade: 0.1,
		  shadeClose : true,
		  content: html,
		  area: '800px'
		};
		e.click(function()
		{
			url = url.replace('save', 'view');
			showUploadE = e;
			if (!type) {
				type = 1;
			}
			showUploadType = type;
			showUploadUrl = url;
			var cur = $('#' + showUploadE.attr('v')).val();
			$.getJSON(url, {json:1,key:key,cur:cur}, function(t)
			{
				config.content = t.data;
				showUploadIndex = layer.open(config);
			})
		})
	});
}

function editorShowUpload(cur, url, title, func, self)
{
	showUploadType = 2;
	showUploadCall = func;
	showUploadThis = self;
	layui.use(['upload','layer','element'], function() {
		var html = '';
		var layer = layui.layer;
		var config = {
		  type: 0,
		  title: title,
		  shade: 0.1,
		  shadeClose : true,
		  content: html,
		  area: '800px'
		};
		url = url.replace('save', 'view');
		showUploadUrl = url;
		$.getJSON(url, {json:1,cur:cur}, function(t)
		{
			config.content = t.data;
			showUploadIndex = layer.open(config);
		})
	});
}

function showUploadFilesSet(e, name, url, id)
{
	$('.layui-anim-yes').addClass('layui-anim-no');
	$('.layui-anim-yes').removeClass('layui-anim-yes');
	e.parent().removeClass('layui-anim-no');
	e.parent().addClass('layui-anim-yes');

	$('.file_cur').val(url);
	if (showUploadType == 1) {
		var value = showUploadE.attr('v');
		loadUploadSet(showUploadE, value, {name:name,url:url});
	} else if (showUploadType == 2) {
		showUploadCall.call(showUploadThis, url, name, id);
		if (showUploadIndex) {
			layer.close(showUploadIndex);
			showUploadIndex = false;
		} else {
			layer.closeAll();
		}
	} else if (showUploadType == 3) {
		var value = showUploadE.attr('editor_id');
		var key = showUploadE.attr('key');
		//KindEditor.insertHtml('#' + value, '<div class="dever-video"><embed src="'+url+'" type="video/x-ms-asf-plugin" width="450" height="300" autostart="false" loop="true" data-id="'+id+'" data-key="'+key+'"/><div style="width:450px;height:20px;">'+name+':'+id+'(请勿修改)</div></div>');
		KindEditor.insertHtml('#' + value, '<img src="'+url+'" style="width:450px;height:300px;" data-id="'+id+'" data-key="'+key+'"/>');
		if (showUploadIndex) {
			layer.close(showUploadIndex);
			showUploadIndex = false;
		} else {
			layer.closeAll();
		}
	}
}

function showUploadFilesSearch(e)
{
	var p = e.parent();
	var pg = p.find('.file_pg').val();
	var key = p.find('.file_key').val();
	var name = p.find('.file_filename').val();
	var tag = p.find('.file_tag').val();
	var cate = p.find('.file_cate').val();
	var cur = p.find('.file_cur').val();

	var url = showUploadUrl;

	showUploadFiles(url, name, key, cate, tag, cur, pg);
}

function showUploadFiles(url, name, key, cate, tag, cur, pg)
{
	if (!pg) {
		pg = 1;
	}
	$.getJSON(url, {json:1,key:key, name:name,cate:cate, tag:tag, pg:pg, cur:cur}, function(t)
	{
		var t = '<div>' + t.data + '</div>';
        html = $(t).find('#component-anim').html();
		$("#component-anim").html(html);
	})
}

function loadUploadL(i,e,key,url,assets)
{
	var value = e.attr('v');
	if (typeof(upload[value]) != "undefined") {
		//return;
	}
	upload[value] = true;
	upload_pic[value] = [];
	upload_file[value] = [];

	var id = e.attr('id');
	var token = e.attr('token');
	var host = e.attr('host');
	var domain = e.attr('domain');
	var path = e.attr('path');
	var cover = e.attr('cover');
	if (!cover) {
		cover = 1;
	}
	var uploadUrl = url;
	url = domain;

	var config = {
      useCdnDomain: true,
      disableStatisticsReport: false,
      retryCount: 6
    };
    var putExtra = {
      fname: "",
      params: {},
      mimeType: null
    };
    layui.use(['layer','element'], function() {
    	var layer = layui.layer;
		var element = layui.element;
		$("#" + id).unbind("change").bind("change",function() {
		    var file = this.files[0];
		    // eslint-disable-next-line
		    var finishedAttr = [];
		    // eslint-disable-next-line
		    var compareChunks = [];
		    var observable;
		    if (file) {

		    	element.progress(id + '_progress', '0%')
				layer.load(); 

		      var filename = file.name;
		      var temp = filename.split('.');
		      putExtra.params["x:name"] = temp[0];

		      filename = path + hex_md5(file.name) + '.' + temp[temp.length-1];

		      //不覆盖
		      if (cover == 2) {
		      		var timestamp = Date.parse(new Date());
		      		filename = path + hex_md5(file.name + '_' + timestamp) + '.' + temp[temp.length-1];
		      }

		      // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
		      var error = function(err) {
		        //请求异常回调
		        console.log(err);
				layer.alert('文件上传错误1');
				element.progress(id + '_progress', '0%')
				$('#' + id + '_progress').hide();
				layer.closeAll('loading');
		      };

		      var complete = function(res) {
		      //&& res.key.match(/\.(jpg|jpeg|png|gif)$/)
		        if (res.key) {
		        	 element.progress(id + '_progress', '0%')
					$('#' + id + '_progress').hide();
					layer.closeAll('loading');
					var data = {};
			      if (res.hash) {
			      	$.getJSON(uploadUrl.replace('save.start', 'qiniu.addFile'), {source:file.name,file:res.key, key:key});
						data.status = 1;
						data.name = res.key;
						data.url = host + res.key;

						loadUploadSet(e,value,data);
					} else {
						layer.alert('文件上传错误2');
						return false;
					}
		        }
		      };

		      var next = function(response) {
		        var chunks = response.chunks||[];
		        var total = response.total;
		        // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
		        for (var i = 0; i < chunks.length; i++) {
		          if (chunks[i].percent === 0 || finishedAttr[i]){
		            continue;
		          }
		          if (compareChunks[i].percent === chunks[i].percent){
		            continue;
		          }
		          if (chunks[i].percent === 100){
		            finishedAttr[i] = true;
		          }
		      }
		      $('#' + id + '_progress').show();
				  element.progress(id + '_progress', parseInt(total.percent)+'%')
		        compareChunks = chunks;
		      };

		      var subObject = { 
		        next: next,
		        error: error,
		        complete: complete
		      };
		      var subscription;
		      // 调用sdk上传接口获得相应的observable，控制上传和暂停
		      observable = qiniu.upload(file, filename, token, putExtra, config);

		      subscription = observable.subscribe(subObject);
	     }
	  })
	});
}

function loadUpload(i,e,key,url,assets)
{
	var value = e.attr('v');
	if (typeof(upload[value]) != "undefined") {
		//return;
	}
	upload[value] = true;
	upload_pic[value] = [];
	upload_file[value] = [];

	var data = {};
	data.key = key;
	var token = e.attr('token');
	var host = e.attr('host');
	var domain = e.attr('domain');
	var path = e.attr('path');
	var cover = e.attr('cover');
	if (!cover) {
		cover = 1;
	}
	if (token) {
		data.token = token;
	}
	var uploadUrl = url;
	if (domain) {
		url = domain;
		delete data.key;
		//data.key = 2;
	}

	var id = e.attr('id');
	layui.use(['upload','layer','element'], function() {
		var layer = layui.layer;
		var layuiUpload = layui.upload;
		var element = layui.element;
		var uploadInst = layuiUpload.render({
			elem: '#' + id
			,data: data
			,field: 'file'
			,url: url
			,multiple: true
			,accept:'file'
			//,auto:false
			,xhr:xhrOnProgress
			,progress:function(value){//上传进度回调 value进度值
				$('#' + id + '_progress').show();
			    element.progress(id + '_progress', value+'%')//设置页面进度条
			}
			,choose: function(obj, self){
				if (domain) {
					obj.editFile(path, cover);
				}
				element.progress(id + '_progress', '0%')
				//layer.load();
			}
			,done: function(data, file) {
				if (data.hash) {
					data.status = 1;
					data.name = data.key;
					data.url = host + data.key;

					$.getJSON(uploadUrl.replace('save.start', 'qiniu.addFile'), {source:file.name,file:data.key, key:key});
				}
				element.progress(id + '_progress', '0%')
				$('#' + id + '_progress').hide();
				layer.closeAll('loading');
				if (data.status == 1) {
					loadUploadSet(e,value,data);
				} else {
					element.progress(id + '_progress', '0%')
					layer.alert(data.message);
					return false;
				}
			}
			,error: function(){
				//请求异常回调
				layer.alert('文件上传错误');
				element.progress(id + '_progress', '0%')
				$('#' + id + '_progress').hide();
				layer.closeAll('loading');
			}
		});
	});
}

function loadUploadSet(e,value,data)
{
	var mul = e.attr('mul');
	if (mul == 'yes') {
		if (e.attr('t') == 'file') {
			if (upload_file[value].length <= 0 && $("#" + value).val()) {
				upload_file[value] = $("#" + value).val().split(',');
			}

			var m = $('.' +value+'_mul');
			var i = m.find('li').eq(upload_file[value].length);
			if (i.length) {
				i.find('a').eq(0).html(data.name);
			} else {
				m.append('<li><a href="'+data.url+'" target="_blank" title="点此下载" >'+data.name+'</a>&nbsp;&nbsp;<a href="javascript:;" title="点此删除" style="color:red;" onclick="fileDel($(this), \''+value+'\')">[删除]</a></li>');
			}

			upload_file[value].push(data.url);

			$("#" + value).val(upload_file.join(','));
		} else {
			if (upload_pic[value].length <= 0 && $("#" + value).val()) {
				upload_pic[value] = $("#" + value).val().split(',');
			}
			var m = $('.' +value+'_mul');
			var i = m.find('img').eq(upload_pic[value].length);
			if (i.length) {
				i.attr('src', data.url);
			} else {
				m.append('<a href="javascript:;" title="点此删除" onclick="picDel($(this), \''+value+'\')"><img src="'+data.url+'" width="150" style="margin-left:5px;" alt="点此删除"/></a>');
			}
			upload_pic[value].push(data.url);
			$("#" + value).val(upload_pic[value].join(','));
		}
		
	} else {
		if (e.attr('t') == 'file') {
			
		} else {
			$('#show_'+value).attr('src',data.url).show();
			$('#show_'+value).unbind('click').bind('click', function()
			{
				picDel($(this), value, 1);
			})
		}
		$('#'+value).val(data.url);
	}
}

function picDel(e,v,s)
{
	if (confirm('确定要删除图片吗？')) {
		if (s == 1) {
			e.hide();
			$("#" + v).val('');
		} else {
			if (upload_pic[v].length <= 0 && $("#" + v).val()) {
				upload_pic[v] = $("#" + v).val().split(',');
			}
			var p = e.find('img').attr('src');
			e.remove();
			upload_pic[v].remove(p);
			$("#" + v).val(upload_pic[v].join(','));
		}
	}
}


function fileDel(e,v)
{
	if(confirm('确定要删除文件吗？'))
	{
		if(upload_file[v].length <= 0 && $("#" + v).val())
		{
			upload_file[v] = $("#" + v).val().split(',');
		}

		var parent = e.parent();
		var p = parent.find('a').eq(0).attr('href');
		
		parent.remove();
		upload_file[v].remove(p);
		//console.info(pic);
		$("#" + v).val(upload_file[v].join(','));
	}
}

