var appServer = null;
var Buffer = OSS.Buffer;
var currentDeleteKey = null;
var logoSize = '?x-oss-process=image/resize,w_200,h_200';
var OSS = OSS.Wrapper;
var region = 'oss-cn-shenzhen';
var STS = OSS.STS;

var addPic = function(client) {
	var file = document.getElementById('picFileId').files[0];
	var name = $('#mod-bc-picName').val();
	var key = null;
	if(name.length < 1){
		name = file.name;
	}
	key = 'ads/b/' + name;
	return client.multipartUpload(key, file, {
        progress: progress
    }).then(function(res) {
    	addPicSuccessCallBack(res, name, key);
    });
};

var applyTokenDo = function(func) {
    var url = appServer;
    $.ajax({
        type: "POST",
        url: url,
        data: "",
        dataType: "jsonp",
        success: function(e) {
            var client = new OSS({
                region: region,
                accessKeyId: e.AccessKeyId,
                accessKeySecret: e.AccessKeySecret,
                stsToken: e.SecurityToken,
                bucket: bucket
            });
            return func(client);
        },
        error: function(data) {
            console.log(data);
        }
    });
};

var deletePic = function(key) {
	currentDeleteKey = key;
	return applyTokenDo(deletePicFromOss);
};

var deletePicFromOss = function(client) {
	return client.delete(currentDeleteKey, {
        progress: progress
    }).then(function(res) {
    	deletePicSuccessCallBack(res);
    });
};

var progress = function(p) {//上传成功的进度条
	return function (done) {
		done();
	};
};

function addBc(){
	bcFormClear();
	$('#modal-bc').modal('toggle');
}

function addPicSuccessCallBack(res, name, path){
	$('#mod-bc-picName').val(name);
	var html = '<div style="text-align:center;display:inline-block;vertical-align:top;">';
	html += '<a href="' + logoUrl + '/' + path + '" target="_blank">';
	html += '<img class="lazy" src="' + contextPath +'/static/img/loading.gif" data-original="' + logoThum  + '/' + path + logoSize + '" height="100" width="100" />';
	html += '</a><br/><a href="javascript:void(0)" onclick="deletePic(\'' + path + '\')">删除</a>';
	html += '</div>&nbsp;';
	$('#mod-bc-picDiv').html(html);
	setTimeout(function () {
		$("img.lazy").lazyload({
			threshold : 200
		});
	}, 200);
	$('#mod-pic').modal('toggle');
}

function bcFormClear(){
	$('#mod-bc-bcId').val('');
	$('#mod-bc-picDiv').html('');
	document.getElementById('bcForm').reset();
}

//删除广告配置
function deleteBcs(ids){
	var url = contextPath + '/am/bc/deleteBcs';
	var names = [];
	var cell = null;
	for(var i in ids){
		cell = myGrid.jqGrid('getRowData',ids[i]);
		if(cell.picName.length > 0){
			names.push(cell.picName);
		}
	}
	var parameters = {'ids':ids.join(),'names':names.join()};
	postData(url, parameters, deleteBcsCallback, errorCallbackDefault);
}

function deleteBcsCallback(data){
	if(data.success){
		showMsg('删除成功');
		myGrid.trigger("reloadGrid");
	}else{
		showMsg(data.message);
	}
}

function deletePicSuccessCallBack(res){
	$('#mod-bc-picName').val('');
	$('#mod-bc-picDiv').html('');
}

function editBc(cellId){
	var cell = myGrid.jqGrid('getRowData',cellId);
	bcFormClear();
	var objs = {'mod-bc-code':'code','mod-bc-ad':'ad','mod-bc-adPic':'adPic','mod-bc-adText':'adText','mod-bc-picName':'picName',
			    'mod-bc-adLink':'adLink','mod-bc-adType':'adType','mod-bc-type':'type','mod-bc-sort':'sort','mod-bc-version':'version',
				'mod-bc-redirectUrl':'redirectUrl','mod-bc-intervalDays':'intervalDays','mod-bc-numberOfDay':'numberOfDay'};
	var ad = 'true';
	if(cell.ad == '禁用'){
		ad = 'false';
	}
	cell.ad = ad;
	for(var obj in objs){
		$('#' + obj).val(cell[objs[obj]]);
	}
	$('#mod-bc-bcId').val(cellId);
	var path = $('#mod-bc-picName').val();
	if(path.length > 0){
		path = 'ads/b/' + path;
		var html = '<div style="text-align:center;display:inline-block;vertical-align:top;">';
		html += '<a href="' + logoUrl + '/' + path + '" target="_blank">';
		html += '<img class="lazy" src="' + contextPath +'/static/img/loading.gif" data-original="' + logoThum  + '/' + path + logoSize + '" height="100" width="100" />';
		html += '</a><br/><a href="javascript:void(0)" onclick="deletePic(\'' + path + '\')">删除</a>';
		html += '</div>&nbsp;';
		$('#mod-bc-picDiv').html(html);
		setTimeout(function () {
			$("img.lazy").lazyload({
				threshold : 200
			});
		}, 200);
	}
	$('#modal-bc').modal('toggle');
}

function picNameCheck(){
	var url = contextPath + '/am/bc/picNameCheck';
	var file = document.getElementById('picFileId').files[0];
	var parameters = {'name':file.name};
	postData(url, parameters, picNameCheckCallback, errorCallbackDefault);
}

function picNameCheckCallback(data){
	if(data.success){
		applyTokenDo(addPic);
	}else{
		showMsg(data.message);
	}
}

//显示信息
function showMsg(msg){
	if(msg != undefined && msg.length > 0){
		alert(msg);
	}
}

function submitBc(){
	var url = contextPath + '/am/bc/saveBc';
	var parameters = {};
	var objs = {'mod-bc-bcId':'id','mod-bc-code':'code','mod-bc-ad':'ad','mod-bc-adPic':'adPic','mod-bc-adText':'adText','mod-bc-picName':'picName',
		    	'mod-bc-adLink':'adLink','mod-bc-adType':'adType','mod-bc-type':'type','mod-bc-sort':'sort','mod-bc-version':'version',
				'mod-bc-redirectUrl':'redirectUrl','mod-bc-intervalDays':'intervalDays','mod-bc-numberOfDay':'numberOfDay'};
	for(var obj in objs){
		parameters[objs[obj]] = $('#' + obj).val();
	}
	postData(url, parameters, submitBCallback, errorCallbackDefault);
}

function submitBCallback(data){
	if(data.success){
		showMsg('保存成功');
		myGrid.trigger("reloadGrid");
		$('#modal-bc').modal('toggle');
	}else{
		showMsg(data.message);
	}
}

function submitPic(){
	var picName = $('#mod-bc-picName').val();
	if(picName < 1){
		picNameCheck();
	}else{
		applyTokenDo(addPic);
	}
}