<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>

<%@include file="/WEB-INF/page/header.jsp" %>
<script>changeMenu(5,2);//左边菜单active</script>
<div class="row white-bg border-bottom white-bg page-heading">
	<div class="col-lg-12">
		<h2>保单信息</h2>
		<ol class="breadcrumb">
			<li>主页</li>
			<li><a>保单信息</a></li>
			<li class="active"><strong>待出函</strong></li>
		</ol>
	</div>
</div>

<div class="wrapper wrapper-content">
	<div class="row">
		<div class="col-lg-12">
			<div class="ibox float-e-margins">
				<div class="ibox-content">
					<div class="row">
                        <div class="col-sm-2">
                        	<div class="input-group m-b"><span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        	<input type="text" class="input-sm form-control" placeholder="订单日期" id="searchDate">
                        	</div>
                        </div>
                        <div class="col-sm-3">
                            <div class="input-group"><input type="text" id="keyword" placeholder="订单号、法院、律师" class="input-sm form-control"><span class="input-group-btn">
                                <button type="button" class="btn btn-sm btn-primary" onclick="search()"> 查询</button> </span></div>
                        </div>
                    </div>
					<div class="row">
						<div class="col-md-12 jqGrid_wrapper">
							<table id="gridTable3"></table>
							<div id="gridPager3"></div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<div id="modal-uploadGuarantee" class="modal fade" tabindex="-1">
	<div class="modal-dialog" style="max-width: 800px;">
		<div class="modal-content">
			<div class="modal-header">
      			<div class="table-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						<span class="white">&times;</span>
					</button>
					上传保函
				</div>
	      	</div>
	      	<div class="modal-body" style="max-height: 500px;overflow-y: scroll;">
	      		<form id="otherForm" class="form-horizontal">
                <div class="form-group">
                  	<label class="col-sm-3 control-label">
                  		保函(图片)
                  	</label>
                    <div class="col-sm-9 text-left">
                    	<div id="div71" class="checkbox-inline"></div>
						<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="uploadPic(71)">上传图片</button>
					</div>
                </div>
                <c:if test="${sessionScope.SESSION_COMPANY.companyType==0}">
                	<div class="form-group" style="display:none;">
	                  	<label class="col-sm-3 control-label">
	                  		保单(图片)
	                  	</label>
	                    <div class="col-sm-9 text-left">
	                    	<div id="div72" class="checkbox-inline"></div>
							<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="uploadPic(72)">上传图片</button>
						</div>
	                </div>
                </c:if>
                <c:if test="${sessionScope.SESSION_COMPANY.companyType==1}">
	                <div class="hr-line-dashed"></div>
	                <div class="form-group">
	                  	<label class="col-sm-3 control-label">
	                  		保单(图片)
	                  	</label>
	                    <div class="col-sm-9 text-left">
	                    	<div id="div72" class="checkbox-inline"></div>
							<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="uploadPic(72)">上传图片</button>
						</div>
	                </div>
                </c:if>
                <!--<div class="hr-line-dashed"></div>
                 <div class="form-group">
                  	<label class="col-sm-3 control-label">
                  		发票(图片)
                  	</label>
                    <div class="col-sm-9 text-left">
                    	<div id="div73" class="checkbox-inline"></div>
						   <button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="uploadPic(73)">上传图片</button>
					     </div>
                </div> 
                <div class="hr-line-dashed"></div>
                <div class="form-group">
                  	<label class="col-sm-3 control-label">
                  		出函编号(对账用)
                  	</label>
                    <div class="col-sm-9 text-left">
                    	<input type="text" id="outOrderId" class="form-control" />
					</div>
                </div>-->
                </form>
	      	</div>
	      	<div class="modal-footer">
                <button class="btn " data-dismiss="modal"><i class="fa fa-share bigger-160"></i>取消</button>
	      		<button class="btn btn-primary" type="button" id="mod-uploadGuarantee-submit"><strong>确定</strong></button>
			</div>
		</div>
	</div>
</div>

<div id="mod-pic" class="modal fade" tabindex="-1">
	<div class="modal-dialog" style="max-width: 500px;">
		<div class="modal-content">
			<div class="modal-header no-padding">
				<div class="table-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						<span class="white">&times;</span>
					</button>
					图片上传
				</div>
			</div>
			<div class="modal-body">
				<div class="row">
					<div class="col-xs-12">
						<!-- PAGE CONTENT BEGINS  -->
						<form id="picform" >
							<input id="picFileId" type="file" name="file" multiple />
							<input type="hidden" name="attachType" id="mod-pic-attachType"/>
							<input type="hidden" name="orderId" id="mod-pic-orderId"/>
							<div class="hr hr-12 dotted"></div>
							<div class="text-center">
							<button type="button" class="btn btn-sm btn-primary" onclick="picUpload();">上传</button>
							<button type="reset" class="btn btn-sm">清除</button>
							</div>
						</form>
					</div><!-- /.col -->
				</div><!-- /.row -->
				
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal-dialog -->
</div>

<div id="modal-dispatch" class="modal fade" tabindex="-1">
	<div class="modal-dialog" style="max-width: 800px;">
		<div class="modal-content">
			<div class="modal-header">
      			<div class="table-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						<span class="white">&times;</span>
					</button>
					配送
				</div>
	      	</div>
	      	<div class="modal-body">
	      		<table style="width:100%;height:100%;border-collapse:separate;border-spacing:10px;">
	      			<tr>
	      				<td colspan=3><span style="font-size:16px;">请谨慎操作，如果虚假出函，则关闭服务！</span></td>
	      			</tr>
	      			<tr id="dispatchTypeTr">
	      				<td>
	      					配送方式:
	      					<span id="ssdbOrderId" style="display:none"></span>
	      				</td>
	      				<td colspan=2>
	      					<select class="select" id="dispatchType" onchange="dispatchTypeOnchange();">
								<option value="0" selected = "selected">快递配送</option>
								<option value="1">上门配送</option>
							</select>
	      				</td>
	      			</tr>
	      			<tr>
	      				<td rowspan=3>
	      					<h3>保函</h3>
	      					<span id="dispatch1SendType"></span><span id="dispatch1Id" style="display:none"></span>
	      				</td>
	      				<td>
	      					收件人：<span id="dispatch1Receiver"></span>
	      				</td>
	      				<td id="dispatch1TdRandom1">
	      					          
	      				</td>
	      			</tr>
	      			<tr>
	      				<td>
	      					电话：<span id="dispatch1Mobile"></span>
	      				</td>
	      				<td id="dispatch1TdRandom2">
	      					
	      				</td>
	      			</tr>
	      			<tr>
	      				<td colspan=2>
	      					地址：<span id="dispatch1Address"></span>
	      				</td>
	      			</tr>
	      			<!-- <tr>
	      				<td colspan=3></td>
	      			</tr>
	      			<tr>
	      				<td rowspan=3>
	      					<c:if test="${sessionScope.SESSION_COMPANY.companyType==0}">
	      						<h3>发票</h3>
	      					</c:if>
	      					<c:if test="${sessionScope.SESSION_COMPANY.companyType==1}">
	      						<h3>保单及发票</h3>
	      					</c:if>
	      					<span id="dispatch2SendType"></span><span id="dispatch2Id" style="display:none"></span>
	      				</td>
	      				<td>
	      					收件人：<span id="dispatch2Receiver"></span>
	      				</td>
	      				<td id="dispatch2TdRandom1">
	      					
	      				</td>
	      			</tr>
	      			<tr>
	      				<td>
	      					电话：<span id="dispatch2Mobile"></span>
	      				</td>
	      				<td id="dispatch2TdRandom2">
	      				
	      				</td>
	      			</tr>
	      			<tr>
	      				<td colspan=2>
	      					地址：<span id="dispatch2Address"></span>
	      				</td>
	      			</tr> -->
	      		</table>
	      	</div>
	      	<div class="modal-footer">
                <button class="btn " data-dismiss="modal"><i class="fa fa-share bigger-160"></i>取消</button>
	      		<button class="btn btn-primary" type="button" id="mod-dispatch-submit"><strong>确定</strong></button>
			</div>
		</div>
	</div>
</div>

<%@include file="/WEB-INF/page/order/orderDetail.jsp" %>

<%@include file="/WEB-INF/page/footer.jsp" %>


<link href="${contextPath}/static/css/plugins/jQueryUI/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" />
<link href="${contextPath}/static/css/plugins/jqGrid/ui.jqgrid.css" rel="stylesheet">

<script src="${contextPath}/static/js/plugins/jqGrid/jquery.jqGrid.min.js"></script>
<script src="${contextPath}/static/js/plugins/jqGrid/i18n/grid.locale-cn.js"></script>

<link rel="stylesheet" href="${contextPath}/static/ssdb/ace.fileinput.css"/>


<link href="${contextPath}/static/js/plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<script src="${contextPath}/static/js/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>
<script src="${contextPath}/static/js/plugins/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js"></script>
 
<!-- Data picker -->
<script src="${contextPath}/static/js/plugins/datapicker/bootstrap-datepicker.js"></script>
 
<script src="${contextPath}/static/js/plugins/lazyload/jquery.lazyload.js"></script>
<!-- 阿里OSS  JSSDK -->
<script type="text/javascript" src="${contextPath}/static/ssdb/promise-6.1.0.js"></script>
<script type="text/javascript" src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.3.0.min.js"></script>
<script type="text/javascript" src="${contextPath}/static/ssdb/ace.fileinput.js"></script>  
<script type="text/javascript" src="${contextPath}/static/ssdb/uuid.js"></script>
<script type="text/javascript" src="${contextPath}/static/ssdb/picupload.js?v=2"></script>

<script type="text/javascript">
	var currentOrderId = null;
	var gridTable1 = null;
	var grid_selector = "#gridTable3";
	var notSubmitSaveWlInfo = true;
	var pager_selector = "#gridPager3";
	jQuery(function($) {
		$('#searchDate').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true,
            format: "yyyy-mm-dd"
        });
		
		initGridTable();
		// resize to fit page size
		$(window).on("resize.jqGrid", function() {
			$(grid_selector).jqGrid("setGridWidth", $(".page-content").width());
		});
		// resize on sidebar collapse/expand
		var parent_column = $(grid_selector).closest("[class*='col-']");
		$(document).on("settings.ace.jqGrid", function(ev, event_name, collapsed) {
			if (event_name === "sidebar_collapsed" || event_name === "main_container_fixed") {
				// setTimeout is for webkit only to give time for DOM changes and then redraw!!!
				setTimeout(function() {
					$(grid_selector).jqGrid("setGridWidth", parent_column.width());
				}, 0);
			}
		});
		
		$(document).one('ajaxloadstart.page', function(e) {
			$(grid_selector).jqGrid('GridUnload');
			$('.ui-jqdialog').remove();
		});
		
		$('#mod-uploadGuarantee-submit').on('click', function() {
			uploadGuaranteeSubmit();
		});
		
		$('#mod-dispatch-submit').on('click', function() {
			saveWlInfo();
		});

	 	// Add responsive to jqGrid
        $(window).bind('resize', function () {
            var width = $('.jqGrid_wrapper').width();
            gridTable1.setGridWidth(width);
        });
	});
	
	//删除图片
	function deletePic(id){
		$('#picDiv' + id).hide();
		var url = '${contextPath}/order/deleteAttachById';
		var parameters = {"id":id};
		postData(url, parameters, deletePiCallback, errorCallbackDefault);
	}

    function deletePiCallback(data){
    	if(data.success){
    		showMsg('删除成功');
    		loadPic(data.attachType);
    	}else{
    		$('#picDiv' + data.attachType).show();
			showMsg(data.message);
		}
    }

	//显示配送
	function dispatchOperation1(id){
		showMsg('请上传保函');
	}
	
	//显示配送
	function dispatchOperation(id){
		currentOrderId = id;
		//var ids = ['71','72','73'];
		var ids = ['71'];
		for(var i in ids){
			$('#div' + ids[i]).html('');
		}
		loadWlInfo();
	}

	function errorCallbackDefault(data){
		
	}
	
    function loadPic(attachType){
    	var url = '${contextPath}/order/getOrderAttachsByType';
		var parameters = {"orderId":currentOrderId,"attachType":attachType};
		postData(url, parameters, loadPiCallback, errorCallbackDefault);
    }
    
    function loadPiCallback(data){
    	if(data.success){
    		var url = '${oss_bucket_ssdb_url}';
			var thum = '${oss_bucket_ssdb_url_img}';
			var size = '${oss_bucket_ssdb_url_img_size}';
    		var v = null;
    		var sec = '';
    		for(var i in data.attachs){
    			v = data.attachs[i];
    			//url = "${ServerC}/ssdbOrderPic?orderAttachId="+v.id;
    			
    			sec += '<div style="text-align:center;display:inline-block;vertical-align:top;" id="picDiv' + v.id + '">';
   				sec += '<a href="' + url + v.path + '" target="_blank">';
    			sec += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + v.path + size + v.suffix.toLowerCase() + '" height="100" width="100" id="' + v.id + '"/>';
    			sec += '</a><br/><a href="javascript:void(0)" onclick="deletePic(\'' + v.id + '\')">删除</a>';
    			sec += '</div>&nbsp;';
    		}
    		$("#div" + data.attachType).html(sec);
    		setTimeout(function () {
				$("img.lazy").lazyload({
					threshold : 200
				});
			  }, 200);
    	}else{
			showMsg(data.message);
		}
    }

	function loadWlInfo(){
		$("#dispatchTypeTr").hide();
		var ids=['dispatch1SendType','dispatch1Receiver','dispatch1TdRandom1','dispatch1Mobile','dispatch1TdRandom2','dispatch1Address',
		         'dispatch1ReachTime','dispatch1WlCompany','dispatch1WlOrderId','dispatch1Id','dispatch2SendType','dispatch2Receiver',
		         'dispatch2TdRandom1','dispatch2Mobile','dispatch2TdRandom2','dispatch2Address','dispatch2ReachTime',
		         'dispatch2WlCompany','dispatch2WlOrderId','dispatch2Id'];
		for(var i in ids){
			$('#' + ids[i]).html('');
		}
		var url = '${contextPath}/order/getOrderWLInfo';
		var parameters = {"orderId":currentOrderId};
		postData(url, parameters, loadWlInfoCallback, errorCallbackDefault);
	}

	function loadWlInfoCallback(data){
		if(data.success){
			var ids=['dispatch1SendType','dispatch1Receiver','dispatch1TdRandom1','dispatch1Mobile','dispatch1TdRandom2','dispatch1Address',
			         'dispatch1ReachTime','dispatch1WlCompany','dispatch1WlOrderId','dispatch1Id','dispatch2SendType','dispatch2Receiver',
			         'dispatch2TdRandom1','dispatch2Mobile','dispatch2TdRandom2','dispatch2Address','dispatch2ReachTime',
			         'dispatch2WlCompany','dispatch2WlOrderId','dispatch2Id'];
			var dateDivids = ['dispatch1ReachTimeDiv','dispatch2ReachTimeDiv'];
			for(var i in ids){
				$('#' + ids[i]).html('');
			}
			var wls = data.wlInfos;
			var wl = null;
			var m = null;
			var iShow = true;
			for(var j in wls){
				iShow = false;
				wl = wls[j];
				m = parseInt(wl.fileType);
				$('#' + ids[m * 10 + 2]).html('');
				$('#' + ids[m * 10 + 4]).html('');
				if('0' == wl.sendType){
					needInitDate = true;
					$('#' + ids[m * 10]).html('快递配送');
					$('#' + ids[m * 10 + 2]).html(
						'<input class="form-control" id="' + ids[m * 10 + 7] +'" size="16" type="text" placeholder="快递公司名称">'
					);
					$('#' + ids[m * 10 + 4]).html(
						'<input class="form-control" id="' + ids[m * 10 + 8] +'" size="16" type="text" placeholder="快递单号">'
					);
				}else{
					$('#' + ids[m * 10]).html('上门配送');
					$('#' + ids[m * 10 + 2]).html(
						'<div class="input-group date form_datetime" data-date-format="yyyy-mm-dd  hh:ii" id="' + dateDivids[m] + '">' + 
			                    '<input class="form-control" id="' + ids[m * 10 + 6] +'" size="16" type="text" placeholder="送达时间" readonly/>' + 
								'<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>' + 
			            '</div>'		
					);
					initDatetimepicker(dateDivids[m]);
				}
				$('#' + ids[m * 10 + 1]).html(wl.receiver);
				$('#' + ids[m * 10 + 3]).html(wl.mobile);
				$('#' + ids[m * 10 + 5]).html(wl.address);
				$('#' + ids[m * 10 + 9]).html(wl.id);
			}
			if(iShow){
				$("#ssdbOrderId").html(data.orderId);
				$("#dispatchTypeTr").show();
				dispatchTypeOnchange();
			}
			$("#modal-dispatch").modal('toggle');
		}else{
			showMsg(data.message);
		}
	}
	
	function initGridTable(){
		gridTable1 = jQuery(grid_selector).jqGrid({
			subGrid : false,
   			url : "${contextPath}/order/getOrders?orderState=3&orderServiceType=1",//32 待出函，40 已出函
   			datatype : "json",
   			height : "auto",
   			autowidth:true,
   			colModel : [{
   				name : "companyName",
   				index : "companyName",
   				label : "公司名称",
   				width : 120,
   				search : false
        	},{
   				name : "orderId",
   				index : "orderId",
   				label : "订单号",
   				width : 100,
   				search : false
        	},{
   				name : "courtName",
   				index : "courtName",
   				label : "受理法院",
   				width : 160,
   				search : false
        	},{
   				name : "sqbd",
   				index : "sqbd",
   				label : "标的金额（元）",
   				width : 80,
   				search : false
        	},{
   				name : "bdCode",
   				index : "bdCode",
   				label : "标的类型",
   				width : 60,
   				sortable: false,
   				search : false
        	},{
   				name : "bf",
   				index : "bf",
   				label : "保费（元）",
   				width : 80,
   				search : false
        	},{
   				name : "lsDate",
   				index : "lsDate",
   				label : "承诺出函时间",
   				width : 110,
   				search : false
        	},{
   				name : "contactName",
   				index : "contactName",
   				label : "申请人",
   				width : 80,
   				search : false
        	},{
   				align : "center",
   				name : "uploadState",
   				index : "uploadState",
   				label : "操作",
   				width : 200,
   				sortable: false,
   				fixed:true,
   				viewable:false,
   				formatter:operationLink
        	},{
   				name : "outOrderId",
   				index : "outOrderId",
   				label : "出函编号",
   				width : 100,
   				search : false,
   				hidden : true
        	}],
   			sortname : "createDate",
   			sortorder : "desc",
   			viewrecords : true,
   			rowNum : 10,
   			rowList : [ 10, 20, 30 ],
   			pager : pager_selector,
   			altRows : true,
   			//toppager : true,
   			multiselect : false,
   			//multikey : "ctrlKey",
   	        multiboxonly : true,
   	     	rownumbers:true,  
      		rownumWidth:30, 
   	        
		});
	}

	//向后台请求数据
	function postData(url, parameters, successCallback, errorCallback){
		$.ajax({
		    type : "POST",
		    url : url,
		    data : parameters,
		    dataType : "json",
		    success : function(data) {
		    	successCallback(data); 
		    },
		    error : function(data) {
		    	errorCallback(data);
		    }
	    }); 
	}
	
	//操作链接
	function operationLink(cellvalue, options, rowObject){
		var result = '';
		if('0' == cellvalue){
			result = '<a href="javascript:void(0);" style="color:blue" onclick="uploadGuaranteeOperation(\'' + rowObject.orderId + '\',\'' + cellvalue + '\',\'' + rowObject.outOrderId + '\')">上传保函</a>&nbsp;|&nbsp;'
			       //+ '<a href="javascript:void(0);" style="color:blue" onclick="dispatchOperation1(\'' + rowObject.orderId + '\')">配送</a>';
		}else{
			result = '<a href="javascript:void(0);" style="color:blue" onclick="uploadGuaranteeOperation(\'' + rowObject.orderId + '\',\'' + cellvalue + '\',\'' + rowObject.outOrderId + '\')">已上传</a>&nbsp;|&nbsp;'
			      // + '<a href="javascript:void(0);" style="color:blue" onclick="dispatchOperation(\'' + rowObject.orderId + '\')">配送</a>';
		}
		result += '<a href="javascript:void(0);" style="color:blue" onclick="showdetail(\''+rowObject.orderId+'\')">详细</a>';
		return result;
	}
	
	function reloadGrid(){
		gridTable1.trigger('reloadGrid');
	}
	
	//保存配送信息
	function saveWlInfo(){
		if(notSubmitSaveWlInfo){
			var ids=['dispatch1SendType','dispatch1ReachTime','dispatch1WlCompany','dispatch1WlOrderId','dispatch1Id','dispatch2SendType','dispatch2ReachTime','dispatch2WlCompany','dispatch2WlOrderId','dispatch2Id'];
			var wl,sendType,reachTime,company,orderId = null;
			var ssdbOrderId = $('#ssdbOrderId').html();
			var array = new Array();
			for(var i=0;i<2;i++){
				wl = {'id':$('#' + ids[i * 5 + 4]).html()};
				sendType = $('#' + ids[i * 5]).html();
				sendType = sendType == '快递配送' ? '1':'0';
				wl['sendType'] = sendType;
				if(ssdbOrderId.length > 0){
					wl['orderId'] = ssdbOrderId;
					wl['fileType'] = i;
				}
				if('0' == sendType){
					reachTime = $('#' + ids[i * 5 + 1]).val();
					if(reachTime == ''){
						showMsg('送达时间不能为空');
						return false;
					}
					wl['reachTime'] = reachTime;
				}else{
					company = $('#' + ids[i * 5 + 2]).val();
					if(company == ''){
						showMsg('快递公司名称不能为空');
						return false;
					}
					orderId = $('#' + ids[i * 5 + 3]).val();
					if(orderId == ''){
						showMsg('快递单号不能为空');
						return false;
					}
					wl['wl_company'] = company;
					wl['wl_order'] = orderId;
				}
				array.push(wl);
			}
			notSubmitSaveWlInfo = false;
			var url = '${contextPath}/order/saveWLInfo';
			var parameters = {'wls':JSON.stringify(array)};
			postData(url, parameters, saveWlInfoCallback, saveWlInfoCallbackErrorCallback);
		}else{
			showMsg('保存中请稍候');
		}
	}
	
	//保存配送信息成功后回调
	function saveWlInfoCallback(data){
		notSubmitSaveWlInfo = true;
		if(data.success){
			showMsg('保存成功');
			$("#modal-dispatch").modal('toggle');
			reloadGrid();
		}else{
			showMsg(data.message);
		}
	}
	
	//保存配送信息失败后回调
	function saveWlInfoCallbackErrorCallback(data){
		notSubmitSaveWlInfo = true;
	}

	function search(){
		var keyword =$("#keyword").val();
		var searchDate =$("#searchDate").val();
		gridTable1.setGridParam({postData:{'keyword':keyword,'searchDate':searchDate,'orderState':3},url : '${contextPath}/order/getOrders',page:1}).trigger('reloadGrid');	
	}
	
	//显示信息
	function showMsg(msg){
		if(msg != undefined && msg.length > 0){
			alert(msg);
		}
	}
	
	//显示上传保函
	function uploadGuaranteeOperation(id,status,outOrderId){
		currentOrderId = id;
		//if('0' != status){
			var ids = ['71','72','73'];
			var id = null;
			for(var i in ids){
				id = ids[i];
				$('#div' + id).html('');
				loadPic(id);
			}
		//}
		$('#outOrderId').val(outOrderId);
		$("#modal-uploadGuarantee").modal('toggle');
	}

    function uploadGuaranteeSubmit(){
    	var count = 0;
    	var ids = ['71','72','73'];
		var id = null;
		for(var i in ids){
			id = ids[i];
			count += $('#div' + id).children().length;
		}
		if(count > 0){
			$("#modal-uploadGuarantee").modal('toggle');
			var url = '${contextPath}/order/saveUploadGuarantee';
			var parameters = {"orderId":currentOrderId, "outOrderId":$("#outOrderId").val()};
			postData(url, parameters, uploadGuaranteeSubmitCallback, errorCallbackDefault);
		}else{
			showMsg('请上传图片');
		}
    }

	//上传保函成功后回调
	function uploadGuaranteeSubmitCallback(data){
		if(data.success){
			showMsg('保存成功');
			reloadGrid();
		}else{
			showMsg(data.message);
		}
	}
	
    function uploadPic(attachType){
    	$("#mod-pic").modal("toggle");
    	$("#mod-pic-attachType").val(attachType);
    	$("#mod-pic-orderId").val(currentOrderId);
    }
    
    function uploadSuccess(){
    	$("#mod-pic").modal("toggle");
    	var t = $("#mod-pic-attachType").val();
    	loadPic(t);
    }
    
    var appServer = 'http://b.duowenlvshi.com/oss/token?name=ssdb';
    var bucket = '${oss_bucket_ssdb}';
    var region = 'oss-cn-shenzhen';
    var Buffer = OSS.Buffer;
    var OSS = OSS.Wrapper;
    var STS = OSS.STS;
    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 uploadFile = function(client) {
    	 var picFile=document.getElementById('picFileId').files[0];
    	 var orderId=document.getElementById('mod-pic-orderId').value;
    	 var fileName = UUIDjs.create().hex;
    	 var fileType = getFileType(picFile.name);
         var key = "ssdb/order/${sessionScope.SESSION_COMPANY.id}/bd/"+orderId+"/"+fileName+"."+fileType;
         return client.multipartUpload(key, picFile, {
            progress: progress
        }).then(function(res) {
        	saveToDB(orderId,key,fileName,fileType);
        });
    }
    ;
    var progress = function(p) {//上传成功的进度条
    	return function (done) {
  	 		 done();
  		};
    }
    ;
    var getFileURL = function(client) {
        console.log(client);
        var object = data[0].name;
        var filename = object.replace(/^.*[\\\/]/, '');
        console.log(object + ' => ' + filename);
        var result = client.signatureUrl(object, {
            response: {
                'content-disposition': 'attachment; filename="' + filename + '"'
            }
        });
        // fileRequest(result);
        //  return result;
    }
    ;
    //pic上传处理
    function picUpload() {
        applyTokenDo(uploadFile);
    }

    function getFileType(fileName){
    	var ldot = fileName.lastIndexOf('.')
    	if(ldot>=0)
    		return fileName.substring(ldot + 1);
    	else
    		return "";
    }
    
    function saveToDB(orderId,key,fileName,fileType){
    	var attachType = $("#mod-pic-attachType").val();
		var parameters = {"orderId":orderId,"attachType":attachType,"path":key,"fileName":fileName,"fileType":fileType};
		console.log(parameters);
		$.getJSON('${contextPath}/order/bdUpload',parameters,function(result){
			if(result.success){
				uploadSuccess();
			}else
				alert(result.message);
		});
    	
    }
    
    function dispatchTypeOnchange(){
    	var value = $('#dispatchType').val();
    	var st = '';
    	var obj = ['dispatch1TdRandom1','dispatch1TdRandom2','dispatch2TdRandom1','dispatch2TdRandom2'];
    	for(var i in obj){
    		$('#' + obj[i]).html('');
    	}
    	if('0' == value){
    		$('#dispatch1TdRandom1').html('<input class="form-control" id="dispatch1WlCompany" size="16" type="text" placeholder="快递公司名称">');
    		$('#dispatch1TdRandom2').html('<input class="form-control" id="dispatch1WlOrderId" size="16" type="text" placeholder="快递单号">');
    		$('#dispatch2TdRandom1').html('<input class="form-control" id="dispatch2WlCompany" size="16" type="text" placeholder="快递公司名称">');
    		$('#dispatch2TdRandom2').html('<input class="form-control" id="dispatch2WlOrderId" size="16" type="text" placeholder="快递单号">');
    		st = '快递配送';
    	}else{
    		$('#dispatch1TdRandom1').html(
				'<div class="input-group date form_datetime" data-date-format="yyyy-mm-dd  hh:ii" id="dispatch1ReachTimeDiv">' + 
	                    '<input class="form-control" id="dispatch1ReachTime" size="16" type="text" placeholder="送达时间" readonly/>' + 
						'<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>' + 
	            '</div>'		
			);
    		$('#dispatch2TdRandom1').html(
   				'<div class="input-group date form_datetime" data-date-format="yyyy-mm-dd  hh:ii" id="dispatch2ReachTimeDiv">' + 
   	                    '<input class="form-control" id="dispatch2ReachTime" size="16" type="text" placeholder="送达时间" readonly/>' + 
   						'<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>' + 
   	            '</div>'		
    		);
    		initDatetimepicker('dispatch1ReachTime');
    		initDatetimepicker('dispatch2ReachTime');
    		st = '上门配送';
    	}
    	$('#dispatch1SendType').html(st);
    	$('#dispatch2SendType').html(st);
    }
    
    function initDatetimepicker(id){
    	$('#' + id).datetimepicker({
			language: 'zh-CN',
	        weekStart: 1,
	        todayBtn:  1,
			autoclose: 1,
			todayHighlight: 1,
			startView: 2,
			forceParse: 0,
	        showMeridian: 1
	    });
    }
</script>


