
// 长银保单管理-详情按钮(进入某公司处理详情页面)
function viewWarrantyDetails(type,id){
	var localdata={'insuranceId':id};
	localStorage.setItem('localdata',JSON.stringify(localdata));
	$(".yk_rightcontent").load('/underlyingAssetInsurance/list?insuranceId='+id)
};

//授信变更
function creditChangefn(id){
	$(".addWarrantyBox").load('/importerQuota/eci/update?id='+id,function(){
		$("#myModal-updateImporter").modal('show');
	})
	
}

// 进口方额度管理-到期日维护按钮
function fn1(id){
	$("#myModal-effectiveDay").modal('show');
	$("#myModal-effectiveDay input[name='expiringDate']").val('');
	$("#myModal-effectiveDay").off('shown.zui.modal').on('shown.zui.modal', function() {
		$("#myModal-effectiveDay input[name='expiringDate']").datetimepicker({
			weekStart: 1,
		    autoclose: 1,
		    todayHighlight: 0,
		    startView: 2,
		    minView:2,
		    forceParse: 0,
		    startDate:'1970-01-01',
		    endDate:'2116-12-31',
		    format: "yyyy-mm-dd"
		});
		$("#myModal-effectiveDay").find("#effectiveDayId").val(id);
		$("#myModal-effectiveDay input[name='effectiveDate']").change(function(){
			if( $("#myModal-effectiveDay input[name='effectiveDate']").val()!='' ){
				$("#myModal-effectiveDay input[name='expiringDate']").val(caculateDeadlineDate($("#myModal-effectiveDay input[name='effectiveDate']").val(),180))
			}else{
				$(".expiringDate").val('');
			}
		});
		$("[name=expiringDate]").change(function(){
			if( $("[name=expiringDate]").val()!='' ){
				$("[name=expiringDate]").removeClass('error');
				$("#expiringDate-error").hide();
			}
		});
		$("#myModal-effectiveDay").find(".colorbtn").unbind('click').bind('click',function(){
			$("#handlePremiumForm").submit();
		});
		$("#handlePremiumForm").validate({
			promptPosition : "bottomLeft",
			submitHandler : function(form) {
				$(form).ajaxSubmit({
					success : function(e) {
						if (e && e.success == true) {
							new $.zui.Messager('保存成功', {
								type : 'success',
								time : 2000
							}).show();
							$("#myModal-effectiveDay").modal('hide');
							$("#myModal-effectiveDay").off('hidden.zui.modal').on('hidden.zui.modal', function() {
								$("#customerList2").trigger('reloadGrid');
							});
						}else {
							new $.zui.Messager('保存失败:'+e.msg, {
								type : 'danger',
								time : 2000
							}).show();
						}
					}
				});
			},
			rules : {
				'effectiveDate' : {//限额生效日
					required : true
				},
				'expiringDate':{//限额到期日
					required : true
				},
				
			},
			messages : {
				'effectiveDate' : {//限额生效日
					required : "限额生效日不能为空",
				},
				'expiringDate':{//限额到期日
					required : '限额到期日不能为空'
				}
			}
		});
	});
};

//进口方额度管理-历史授信记录按钮
function fn2(id){
	exportCreditInsuranceQuery.importerHistoryId = id;
	$(".yk_rightcontent").load('/importerQuota/eci/listHistoric')
};

//进口方额度管理-限额占用统计按钮
function fn3(id){
	$.ajax({
		url:'/importerQuota/eci/doStatistic?id='+id,
		type:'get',
		data:{},
		success:function(data){
			if( data.success ){
				$("#myModal-occupyCount").find(".limitAmount").html((data.data.limitAmount!=undefined?commaDelimiter(data.data.limitAmount.toString())+' '+(data.data.currencyType?data.data.currencyType.code:''):''));
				$("#myModal-occupyCount").find(".effectiveDate").html(data.data.effectiveDate);
				$("#myModal-occupyCount").find(".expiringDate").html(data.data.expiringDate);
				$("#myModal-occupyCount").find(".desire_limitAmount").html((data.data.preoccupiedLimitAmount!=undefined?commaDelimiter(data.data.preoccupiedLimitAmount.toString())+' '+(data.data.currencyType?data.data.currencyType.code:''):''));
				$("#myModal-occupyCount").find(".desire_limitBalance").html((data.data.preoccupiedLimitBalance!=undefined?commaDelimiter(data.data.preoccupiedLimitBalance.toString())+' '+(data.data.currencyType?data.data.currencyType.code:''):''));
				$("#myModal-occupyCount").find(".real_limitAmount").html((data.data.actualLimitAmount!=undefined?commaDelimiter(data.data.actualLimitAmount.toString())+' '+(data.data.currencyType?data.data.currencyType.code:''):''));
				$("#myModal-occupyCount").find(".real_limitBalance").html((data.data.limitBalance!=undefined?commaDelimiter(data.data.limitBalance.toString())+' '+(data.data.currencyType?data.data.currencyType.code:''):''));
			}
			$("#myModal-occupyCount").modal('show')
		},
		error:function(status){
			new $.zui.Messager('获取数据失败:'+status.msg, {
				type : 'danger',
				time : 2000
			}).show();
			$("#myModal-occupyCount").modal('show')
		}
	})
	
};


$(function(){
	// 新增中信保长银保单
	$("#addWarranty").click(function(){
		$(".addWarrantyBox").load('/inkassonPolicy/eci/add',function(){
			$("#myModal-addWarranty").modal('show')
		})
	});
	
	// 长银保单管理-综合险历史授信记录
	$("#recordWarranty").click(function(){
		$.get('/inkassonPolicy/eci/historicList',function(data){
			$(".yk_rightcontent").empty().append(data);
		})
	});
	
	// 进口方额度管理-新增
	$("#addImporter").click(function(){
		$(".addImporterBox").load('/importerQuota/eci/add',function(){
			$("#myModal-addImporter").modal('show')
		})
	});
	
	// 获取最新有效的长银保单信息
	function getNewPolicyNews(){
		$.ajax({
			url:'/inkassonPolicy/eci/doView',
			type:'get',
			data:{},
			success:function(data){
				$('.notFormTable .statisticalAmount').text('');
				if( data.success ){
					$('.notFormTable .statisticalAmount').eq(0).text(data.data.comprehensiveAmount?commaDelimiter(data.data.comprehensiveAmount.toString())+' '+data.data.currencyType.code:'');//综合险额度
					$('.notFormTable .statisticalAmount').eq(1).text(data.data.effectiveDate?data.data.effectiveDate:'');//综合险生效日
					$('.notFormTable .statisticalAmount').eq(2).text(data.data.expiringDate?data.data.expiringDate:'');//综合险到期日
					$('.notFormTable .statisticalAmount').eq(3).text(data.data.maxCompensationAmount?commaDelimiter(data.data.maxCompensationAmount.toString())+' '+data.data.currencyType.code:'');//最高赔偿额
					
					$('.notFormTable .statisticalAmount').eq(4).text(data.data.preoccupiedComprehensiveAmount?commaDelimiter(data.data.preoccupiedComprehensiveAmount.toString())+' '+data.data.currencyType.code:'');//预占综合险额度
					$('.notFormTable .statisticalAmount').eq(5).text(data.data.preoccupiedComprehensiveBalance?commaDelimiter(data.data.preoccupiedComprehensiveBalance.toString())+' '+data.data.currencyType.code:'');//预占综合险余额
					if( $('.notFormTable .statisticalAmount').eq(5).text().indexOf('-')>=0 ){
						$('.notFormTable .statisticalAmount').eq(5).css('color','red');
					}else{
						$('.notFormTable .statisticalAmount').eq(5).css('color','green');
					};
					$('.notFormTable .statisticalAmount').eq(6).text(data.data.preoccupiedMaxCompensationAmount?commaDelimiter(data.data.preoccupiedMaxCompensationAmount.toString())+' '+data.data.currencyType.code:'');//预占最高赔偿额
					$('.notFormTable .statisticalAmount').eq(7).text(data.data.preoccupiedMaxCompensationBalance?commaDelimiter(data.data.preoccupiedMaxCompensationBalance.toString())+' '+data.data.currencyType.code:'');//预占最高赔偿额余额
					if( $('.notFormTable .statisticalAmount').eq(7).text().indexOf('-')>=0 ){
						$('.notFormTable .statisticalAmount').eq(7).css('color','red');
					}else{
						$('.notFormTable .statisticalAmount').eq(7).css('color','green');
					};
					
					$('.notFormTable .statisticalAmount').eq(8).text(data.data.actualComprehensiveAmount?commaDelimiter(data.data.actualComprehensiveAmount.toString())+' '+data.data.currencyType.code:'');//实占综合险额度
					$('.notFormTable .statisticalAmount').eq(9).text(data.data.comprehensiveBalance?commaDelimiter(data.data.comprehensiveBalance.toString())+' '+data.data.currencyType.code:'');//实占综合险余额
					if( $('.notFormTable .statisticalAmount').eq(9).text().indexOf('-')>=0 ){
						$('.notFormTable .statisticalAmount').eq(9).css('color','red');
					}else{
						$('.notFormTable .statisticalAmount').eq(9).css('color','#F3B061');
					};
					$('.notFormTable .statisticalAmount').eq(10).text(data.data.actualMaxCompensationAmount?commaDelimiter(data.data.actualMaxCompensationAmount.toString())+' '+data.data.currencyType.code:'');//实占最高赔偿额
					$('.notFormTable .statisticalAmount').eq(11).text(data.data.maxCompensationBalance?commaDelimiter(data.data.maxCompensationBalance.toString())+' '+data.data.currencyType.code:'');//实占最高赔偿额余额
					if( $('.notFormTable .statisticalAmount').eq(11).text().indexOf('-')>=0 ){
						$('.notFormTable .statisticalAmount').eq(11).css('color','red');
					}else{
						$('.notFormTable .statisticalAmount').eq(11).css('color','#F3B061');
					};
				}else{}// 无数据, 不展示错误提示
			},
			error:function(status){
				new $.zui.Messager('获取长银保单信息出错:'+status, {
				    type: 'danger'
				}).show();
			}
		})
	};
	getNewPolicyNews()
	
	
	$("#searchNameWarranty").val(exportCreditInsuranceQuery.warrantyKeyValue);
	$("#searchNameImporter").val(exportCreditInsuranceQuery.importerKeyValue);
	
	function loadSendData(listid,postdata){
		$(listid).setGridParam({
			mtype:'GET',
			url : '/quotaDisburseInsurance/doList',
			datatype : 'json',
			postData: postdata,
			page : 1
		});
		$(listid).trigger('reloadGrid');
	};
	
	// 长银保单管理的操作按钮
	function operateFn(cellValue,options,rowObject){
		var btnstr = '';
		if( $('#listDetailInkassonPolicy').length>0 ){
			btnstr += '<p><span>详情</span><i class="operateIconfont operateIcon-xiangqing" onclick="viewWarrantyDetails(\''+rowObject.businessType+'\','+rowObject.id+')"></i></p>';
		};
		return '<div class="operateIcon noHover">'+btnstr+'</div>';
	};
	
	// 进口方额度管理的操作按钮
	function operateFn2(cellValue,options,rowObject){
		var btnstr = '';
		if( $('#updateImporterQuota').length>0 ){
			btnstr += '<p><span>授信变更</span><i class="operateIconfont operateIcon-shouxinbiangeng" onclick="creditChangefn('+rowObject.id+')"></i></p>';
		};
		if( $('#updateExpiringImporterQuota').length>0 ){
			btnstr += '<p><span>到期日维护</span><i class="operateIconfont operateIcon-weihu" onclick="fn1('+rowObject.id+')"></i></p>';
		}
		if( $('#listHistoricImporterQuota').length>0 ){
			btnstr += '<p><span>历史授信记录</span><i class="operateIconfont operateIcon-shouxinjilu" onclick="fn2('+rowObject.id+')"></i></p>';
		}
		if( $('#occupancyStatisticImporterQuota').length>0 ){
			btnstr += '<p><span>限额占用统计</span><i class="operateIconfont operateIcon-zhanyongtongji" onclick="fn3('+rowObject.id+')"></i></p>';
		};
		return '<div class="operateIcon noHover">'+btnstr+'</div>';
	};
	
	// 展示保险金额
	function showInsuranceAmount(cellValue,options,rowObject){
		if( rowObject.insuranceAmount ){
			return commaDelimiter(rowObject.insuranceAmount.toString())+' '+rowObject.currencyType.code;
		}else{
			return ''
		}
	};
	
	// 展示最高赔偿额
	function showMaxAmount(cellValue,options,rowObject){
		if( rowObject.maxCompensationAmount ){
			return commaDelimiter(rowObject.maxCompensationAmount.toString())+' '+rowObject.currencyType.code;
		}else{
			return ''
		}
	};
	
	// 进口方额度-展示限额额度
	function showLimitAmount(cellValue,options,rowObject){
		if( rowObject.limitAmount ){
			return commaDelimiter(rowObject.limitAmount.toString())+' '+rowObject.currencyType.code;
		}else{
			return ''
		}
	};
	
	// 展示 oa 账期
	function showOa(cellValue,options,rowObject){
		if( rowObject.oaBilling ){
			return rowObject.oaBilling+' 天'
		}else{
			return '';
		}
	}
	
	function tablefunction(tableid,jumpTaskId){
		var tipword = '',pageid = '',pageNo = 1,url = '',colNamesArray = [],colModelArray = [];
		switch( tableid ){
			case '#customerList':tipword ='长银保单';pageid = 'customerListPage';pageNo = underlyingAssetsQuery.domesticListPage;url = '/quotaDisburseInsurance/doList';postData = {'ename':'exportCreditInsuranceCorp','importer':$(".warrantySelect option:selected").attr('value'),'entName':$("#searchNameWarranty").val()};
				 colNamesArray = ['ID','序号','出口方','进口方','保险金额','最高赔偿额度','操作'];
				 colModelArray = [
					{name: 'id', label: 'ID', hidedlg:true, hidden:true,sortable:false,title:false},
					{name: 'orderNumber', label: '序号', hidedlg:true, width:60,sortable:false,title:false},
					{name: 'entBusinessName', label: '出口方',sortable:false,align:'left',width:150,title:false},
					{name: 'foreignEntName', label: '进口方',sortable:false,align:'left',width:150,title:false},
					{name: 'insuranceAmount', label: '保险金额',sortable:false,align:'left',width:150,title:false,formatter:showInsuranceAmount},
					{name: 'maxCompensationAmount', label: '最高赔偿额度',sortable:false,align:'center',width:150,title:false,formatter:showMaxAmount},
					{name: 'operate', label: '操作',sortable:false,align:'left',width:200,title:false,formatter:operateFn}
				 ];
				 break;
			case '#customerList2':tipword ='进口方额度';pageid = 'customerListPage2';pageNo = underlyingAssetsQuery.exportListPage;url = '/importerQuota/eci/doList';postData = jumpTaskId?{'importerId':jumpTaskId}:{};
			 	 colNamesArray = ['ID','序号','进口方','进口方编号','国别','限额额度','限额生效日','限额到期日','OA账期','操作'];
			 	 colModelArray = [
					{name: 'id', label: 'ID', hidedlg:true, hidden:true,sortable:false,title:false},
					{name: 'orderNumber', label: '序号', hidedlg:true, width:60,sortable:false,title:false},
					{name: 'foreignEnt.enterpriseName', label: '进口方',sortable:false,align:'left',width:120,title:false},
					{name: 'foreignEnt.enterpriseNum', label: '进口方编号',sortable:false,align:'left',width:120,title:false},
					{name: 'foreignEnt.countryName', label: '国别',sortable:false,align:'left',width:100,title:false},
					{name: 'limitAmount', label: '限额额度',sortable:false,align:'left',width:120,title:false,formatter:showLimitAmount},
					{name: 'effectiveDate', label: '限额生效日',sortable:false,align:'left',width:120,title:false},
					{name: 'expiringDate', label: '限额到期日',sortable:false,align:'center',width:110,title:false},
					{name: 'oaBilling', label: 'OA账期',sortable:false,align:'center',width:80,title:false,formatter:showOa},
					{name: 'operate', label: '操作',sortable:false,align:'left',width:200,title:false,formatter:operateFn2}
				 ];
				 break;
		};
		sxUtil.jqGrid(tableid,{
			colNames:colNamesArray,
			colModel:colModelArray, 
			height:'auto',
			mtype:'GET',
			url :  url,
			pager : pageid,
			multiselect: false,
			rownumbers:false,
			postData :postData,
			page:pageNo,
			loadError:function(){
				new $.zui.Messager(tipword+'列表加载失败', {
				    type: 'warning'
				}).show();
			}
		},true);
		$(tableid).trigger('reloadGrid');
	};
	
	//切换表格
	$(".projectListTab li").click(function(){
		$(".projectListTab .active").removeClass("active");
		$(this).addClass("active");
		$(".customerMarketingList").css('left',"100%");
		var indexlist = $(".projectListTab li").index($(this));
		$(".customerMarketingList").eq(indexlist).css({"padding":"0.1rem 0.2rem 0 0.2rem",'left':'0'});
		if( indexlist==0 ){
			tablefunction('#customerList');
			$("#searchNameWarranty").val(exportCreditInsuranceQuery.warrantyKeyValue)
		}else{
			tablefunction('#customerList2');
			$("#searchNameImporter").val(exportCreditInsuranceQuery.importerKeyValue)
		};
	});
	
	if( messageJumpLeastPrevId!='' ){// 从消息跳转过来的
		if( messageJumpLeastEname == 'inkassonPolicyManagement' ){//长银保单管理
			$('.projectListTab li.inkassonPolicyManagement').click();
			underlyingAssetsQuery.source = 'domestic_factoring';
		};
		if( messageJumpLeastEname == 'importerQuotaManagement' ){//进口方额度管理
			$('.projectListTab li.importerQuotaManagement').click();
			underlyingAssetsQuery.source = 'export_factoring';
		};
	}else{
		// 要改...
		if( underlyingAssetsQuery.source == 'domestic_factoring' ){
			$(".projectListTab li:first").click();
		}else{
			$(".projectListTab li:last").click();
		};
	}
	
	
	// 刷新长银保单按钮
	$("#refreshWarranty").click(function(){
		getNewPolicyNews();
		$('.warrantySelect').val('');
		$("#searchNameWarranty").val('');
		$('#customerList').setGridParam({
			mtype:'GET',
			url : '/quotaDisburseInsurance/doList',
			datatype : 'json',
			postData: {'ename':'exportCreditInsuranceCorp','importer':'','entName':''},
			page : 1
		});
		$('#customerList').trigger('reloadGrid');
	});
	// 刷新进口方按钮
	$("#refreshImporter").click(function(){
		$('.importerSelect').val('');
		$("#searchNameImporter").val('');
		$('#customerList2').setGridParam({
			mtype:'GET',
			url : '/importerQuota/eci/doList',
			datatype : 'json',
			postData: {'ename':'exportCreditInsuranceCorp','deadline':$('.importerSelect option:selected').attr('value'),'importerName':$("#searchNameImporter").val()},
			page : 1
		});
		$('#customerList2').trigger('reloadGrid');
	});
	
	// 进口方出口方切换(查询)
	$('.warrantySelect').change(function(){
		$('#customerList').setGridParam({
			mtype:'GET',
			url : '/quotaDisburseInsurance/doList',
			datatype : 'json',
			postData: {'ename':'exportCreditInsuranceCorp','importer':$('.warrantySelect option:selected').attr('value'),'entName':$("#searchNameWarranty").val()},
			page : 1
		});
		$('#customerList').trigger('reloadGrid');
	});
	// 已到期未到期切花(查询)
	$('.importerSelect').change(function(){
		$('#customerList2').setGridParam({
			mtype:'GET',
			url : '/importerQuota/eci/doList',
			datatype : 'json',
			postData: {'ename':'exportCreditInsuranceCorp','deadline':$('.importerSelect option:selected').attr('value'),'importerName':$("#searchNameImporter").val()},
			page : 1
		});
		$('#customerList2').trigger('reloadGrid');
	});
	
	
	// 查询按钮点击	
	$("#searchBtnWarranty").click(function(){
		$('#customerList').setGridParam({
			mtype:'GET',
			url : '/quotaDisburseInsurance/doList',
			datatype : 'json',
			postData: {'ename':'exportCreditInsuranceCorp','importer':$('.warrantySelect option:selected').attr('value'),'entName':$("#searchNameWarranty").val()},
			page : 1
		});
		$('#customerList').trigger('reloadGrid');
	});
	$("#searchBtnImporter").click(function(){
		exportCreditInsuranceQuery.importerKeyValue = $("#searchNameImporter").val();
		exportCreditInsuranceQuery.importerListPage = 1;
		$('#customerList2').setGridParam({
			mtype:'GET',
			url : '/importerQuota/eci/doList',
			datatype : 'json',
			postData: {'ename':'exportCreditInsuranceCorp','deadline':$('.importerSelect option:selected').attr('value'),'importerName':$("#searchNameImporter").val()},
			page : 1
		});
		$('#customerList2').trigger('reloadGrid');
	});
	
})