var upload_pic = [];
var upload_pic_info = [];
var upload_file = [];
var upload = [];
var showUploadE = false;
var showUploadFilesUploadE = false;
var showUploadFilesSearchE = false;
var showUploadFilesSearchState = 1;
var showUploadFilesSearchAll = false;
var upload_search_default = '';
var showUploadUrl;
var showUploadType = 1;
var showUploadCall = false;
var showUploadThis = false;
var showUploadIndex = false;
var picManageE = false;
var picManageI = false;
var picManageV = false;
var picManageLayer = false;
var showUploadFilesValue = [];
//创建监听函数
 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 showUploadCover(i,e,key,url,assets,type)
 {
	layui.use(['upload','layer','element'], function() {
		var html = '';
		var layer = layui.layer;
		var cover = e.attr('data-cover');
		var layerConfig = {
		  type: 1,
		  title: e.attr('value'),
		  shade: 0.1,
		  shadeClose : true,
		  content: html,
		  area: ['800px', '500px'],
		  btn: ['保存', '关闭'],
		  btnAlign: 'c',
		  yes: function(index, layero){
		  	var pic = $('#cover_pic').attr('src');
		  	var num = $('#cover_num').val();
		  	var key = $('#cover_key').val();
		  	var video = $('#cover_cur').val();
		  	var copy = url.replace('save.videoCover', 'view.copy');
		  	var i = layer.load(0, {shade: false});
		  	$.getJSON(copy, {json:1,file:pic,num:num,key:key,video:video}, function(t)
			{
				pic = t.data;
				$('#update_' + cover + '_' + cover).val(pic);
				$('#show_update_' + cover + '_' + cover).attr('src', pic);
				layer.close(i);
				layer.close(index);
			})
			
		  },
		  btn2: function(index, layero){
		    layer.close(index);
		  },
		};
		e.unbind('click').bind('click', function()
		{
			var view = url.replace('save', 'view');
			showUploadE = e;
			if (!type) {
				type = 1;
			}
			showUploadType = type;
			showUploadUrl = url;
			var cur = $('#' + showUploadE.attr('v')).val();
			
			$.getJSON(view, {json:1,key:key,cur:cur,cover:cover}, function(t)
			{
				if (showUploadIndex) {
					layer.close(showUploadIndex);
				}
				//layer.closeAll();
				layerConfig.content = t.data;
				layerConfig.end = function() {
					if (showUploadFilesUploadE) {
						showUploadFilesUploadE = false;
					}
				}
				showUploadIndex = layer.open(layerConfig);
			})
		})
	});
 }

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

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 layerConfig = {
		  type: 1,
		  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)
		{
			layerConfig.content = t.data;
			showUploadIndex = layer.open(layerConfig);
		})
	});
}

//删除
function showUploadFilesSetState(e, url)
{
	if (confirm('确定进行此项操作吗？')) {
		$.getJSON(url, {json:1}, function(t)
		{
			if (!showUploadFilesSearchE) {
				showUploadFilesSearchE = $('#showUploadFilesSearch');
			}
			showUploadFilesSearch(showUploadFilesSearchE, showUploadFilesSearchState,showUploadFilesSearchAll);
		})
	}
}

function showUploadFilesShowValue(e)
{
	var html = e.html();

	layer.alert(html);
}

function showUploadFilesSetValue(e, url, id, value)
{
	if (showUploadFilesValue[id]) {
		value = showUploadFilesValue[id];
	}
	layer.prompt({
	  formType: 2,
	  value: value,
	  title: '请输入附加值，例子：key1=value1&key2=value2',
	  area: ['300px', '150px'] //自定义文本域宽高
	}, function(value, index, elem){
		showUploadFilesValue[id] = value;
	  	$.getJSON(url, {value:value}, function(t){});
	  	layer.close(index);
	});
}

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');
		var key = showUploadE.attr('key');
		loadUploadSet(showUploadE, value, {name:name,url:url}, key);
	} else if (showUploadType == 2) {
		showUploadCall.call(showUploadThis, url, name, id);
	} 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 showUploadFilesUpload(e)
{
	showUploadFilesUploadE = e;
	showUploadE.parent().find('.image_upload').click();
}

function showUploadFilesSearch(e, state, all, pg)
{
	showUploadFilesSearchE = e;
	showUploadFilesSearchState = state;
	var p = e.parent();
	if (!pg) {
		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 upload_search = p.find('.upload_search').val();
	var state = state;

	var url = showUploadUrl;

	if (upload_search) {
		upload_search_default = upload_search;
	}

	upload_search = upload_search_default;
	
	if (all) {
		upload_search = '';
		showUploadFilesSearchAll = true;
	} else {
		showUploadFilesSearchAll = false;
	}

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

function showUploadFiles(url, name, key, cate, tag, cur, pg, upload_search, state)
{
	if (!pg) {
		pg = 1;
	}
	$.getJSON(url, {json:1,key:key, name:name,cate:cate, tag:tag, pg:pg, cur:cur, upload_search:upload_search,state:state}, 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_pic_info[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 bucket = e.attr('bucket');
	var path = e.attr('path');
	var cover = e.attr('cover');
	var type = e.attr('m');
	var search = '';
	if (e.attr('upload_search_value')) {
		search = e.attr('upload_search_value');
	}
	if (!cover) {
		cover = 1;
	}
	var uploadUrl = url;
	url = domain;

    
    layui.use(['layer','element'], function() {
    	var layer = layui.layer;
		var element = layui.element;
		$("#" + id).unbind("change").bind("change",function() {
		    var file = this.files[0];
		    
		    if (file) {

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

				var filename = file.name;
				var temp = filename.split('.');
				var 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) {
					//请求异常回调
					layer.alert('文件上传错误');
					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) {
							if (search.indexOf('#') != -1) {
								var temp = search.split('#');
								search = temp[0];
								if (temp[1]) {
									temp[1] = $('#update_'+temp[1]+'_value').val();
									if (temp[1] > 0) {
										search = search + '_' + temp[1];
									}
								}
							}

							$.getJSON(uploadUrl.replace('save.start', 'yun.addFile'), {source:file.name,file:res.key, key:key, search:search});
							data.status = 1;
							data.name = res.key;
							data.url = host + res.key;

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

				if (type == 'qiniu') {
					qiniuHandle(id, name, token, domain, bucket, file, filename, element, error, complete);
				} else if(type == 'oss') {
					ossHandle(id, name, token, domain, bucket, file, filename, element, error, complete);
				}
	     	}
	  	});
	});
}

function ossHandle(id, name, token, domain, bucket, file, filename, element, error, complete)
{
	var temp = token.split('||');
	if (temp[0]) {
		token = temp[0];
	} else {
		token = '';
	}

	let ossConfig = {
	  // region以杭州为例（oss-cn-hangzhou），其他region按实际情况填写。
	  region: 'oss-' + domain,
	  // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
	  accessKeyId: temp[1],
	  accessKeySecret: temp[2],
	  bucket: bucket,
	}

	if (token) {
		ossConfig.stsToken = token;
	}

	let client = new OSS(ossConfig);

	let tempCheckpoint;

	// 定义上传方法。
	async function multipartUpload () {
	  try {
	    // object-key可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
	    let result = await client.multipartUpload(filename, file, { 
	      progress: function (p, checkpoint) {
	      	$('#' + id + '_progress').show();
			element.progress(id + '_progress', parseInt(p*100)+'%')
	        // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
	        tempCheckpoint = checkpoint;
	        if (p >= 1) {
	      		complete({key:filename,hash:true});
	      	}
	      },
	      //meta: { year: 2020, people: 'test' },
	      //mime: 'image/jpeg'
	   })
	  } catch(e){
	    console.log(e);
	    error();
	  }
	}

	// 开始分片上传。
	multipartUpload();
}

function qiniuHandle(id, name, token, domain, bucket, file, filename, element, error, complete)
{
	// eslint-disable-next-line
	var finishedAttr = [];
	// eslint-disable-next-line
	var compareChunks = [];
	var observable;
	var subscription;
	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
	};
	// 调用sdk上传接口获得相应的observable，控制上传和暂停
	var layerConfig = {
		useCdnDomain: true,
		disableStatisticsReport: false,
		retryCount: 6
    };
    var putExtra = {
		fname: "",
		params: {"x:name":name},
		mimeType: null
    };
	observable = qiniu.upload(file, filename, token, putExtra, layerConfig);
	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_pic_info[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');
	data.search = '';
	if (e.attr('upload_search_value')) {
		data.search = e.attr('upload_search_value');
	}
	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+'%')//设置页面进度条
			}
			,before: function(obj){
				if (this.data.search.indexOf('#') != -1) {
					var temp = this.data.search.split('#');
					this.data.search = temp[0];
					if (temp[1]) {
						temp[1] = $('#update_'+temp[1]+'_value').val();
						if (temp[1] > 0) {
							this.data.search = this.data.search + '_' + temp[1];
						}
					}
				}
            }
			,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,key);
				} 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,key)
{
	if (showUploadFilesUploadE) {
		showUploadFilesSearch(showUploadFilesUploadE, showUploadFilesSearchState, showUploadFilesSearchAll);
		return;
	}
	var mul = e.attr('mul');
	var place = e.attr('place');
	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 {
			var i = e.attr('i');
			var info = '';
			if (data.width) {
				info = data.width + '_' + data.height + '_' +data.size + '_' + data.fid;
			}
			
			if (upload_pic[value].length <= 0 && $("#" + value).val()) {
				upload_pic[value] = $("#" + value).val().split(',');
			}
			if ($('#'+i).length) {
				upload_pic_info[value] = $("#" + i).val().split(',');
			}
			var m = $('.' +value+'_mul');
			var index = m.find('img').eq(upload_pic[value].length);
			var set = index.length;
			var place = m.find('.place');
			if (place.length) {
				set = false;
			}

			if (set) {
				index.attr('src', data.url);
				index.attr('data-src', data.url);
				index.attr('info', info);
			} else {
				m.append('<a href="javascript:;" title="打开图片管理工具" onclick="picManage($(this), \''+value+'\', \''+key+'\', 2, \''+i+'\', \''+place+'\')"><img src="'+data.url+'"  data-src="'+data.url+'" info="'+info+'" width="150" class="cropper_img" style="margin-left:5px;" alt="打开图片管理工具"/></a>');
			}
			upload_pic[value].push(data.url);
			$("#" + value).val(upload_pic[value].join(','));

			if ($('#'+i).length && info) {
				upload_pic_info[value].push(info);
				$('#'+i).val(upload_pic_info[value].join(','));
			}
		}
		
	} else {
		if (e.attr('t') == 'file') {
			
		} else {
			var i = e.attr('i');
			if ($('#show_'+value).length) {
				$('#show_'+value).parent().show();
				$('#show_'+value).attr('src',data.url).show();
				$('#show_'+value).attr('data-src',data.url);
				if (!checkClick($('#show_'+value))) {
					$('#show_'+value).unbind('click').bind('click', function()
					{
						picManage($(this), value, key, 1, i, place);
					})
				}
			}
		}
		
		$('#'+value).val(data.url);
		if ($('#'+i).length && data.width) {
			var info = data.width + '_' + data.height + '_' +data.size + '_' + data.fid;
			$('#'+i).val(info);
		}
	}
}

function picSet(pic, s, info)
{
	if (picManageE) {
		//$('#'+value).val(data.url);
		var img = picManageE.find('img');
		var old = img.attr('src');
		img.attr('src', pic);
		var value = $("#" + picManageV);
		value.val(value.val().replace(old, pic));
		if (s != 1) {
			upload_pic[picManageV].replaceOne(old,pic);
		}
		
		var i = picManageI;
		if ($('#'+i).length) {
			if (s == 1) {
				$('#'+i).val(info);
			} else {
				var old = img.attr('info');
				if (old) {
					upload_pic_info[picManageV].replaceOne(old,info);
					$("#" + i).val(upload_pic_info[picManageV].join(','));
				}
			}
		}
	}
	layer.close(picManageLayer);
}

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

			if ($('#'+i).length) {
				var info = e.find('img').attr('info');
				upload_pic_info[v].remove(info);
				$("#" + i).val(upload_pic_info[v].join(','));
			}
		}
	}
	layer.close(picManageLayer);
}

function picManage(e,v,k,s,i,wh)
{
	if (!s) {
		s = 2;
	}
	if (!wh) {
		wh = '160*90';
	}
	picManageE = e;
	picManageV = v;
	picManageI = i;
	var param = '';
	var img = e.find('img');
	if (img.attr('data-src')) {
		var pic = img.attr('data-src');
		param = img.attr('src');
	} else {
		var pic = img.attr('src');
		img.attr('data-src', pic);
	}

	if (pic.indexOf('temp.im') != -1) {
		return;
	}

	if (pic.indexOf('?t=') != -1) {
		var temp = pic.split('?');
		pic = temp[0];
	} else if (pic.indexOf('?') != -1) {
		return;
	}
	

	var url = config.upload.replace('save', 'view') + '.manage&state='+s+'&key='+k+'&pic=' + pic + '&param=' + param+'&wh='+wh;
	var layerConfig = {
	  type: 2,
	  title: '图片裁剪工具',
	  content : [url, 'no'],
	  shade: 0.1,
	  shadeClose : true,
	  area: ['1000px','550px']
	};
	picManageLayer = layer.open(layerConfig);
}


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(','));
	}
}

