<%@ 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,3);//左边菜单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="gridTable2"></table>
							<div id="gridPager2"></div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<div id="modal-reviewPay" class="modal fade" tabindex="-1">
	<div class="modal-dialog" style="max-width: 600px;">
		<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">
	      		<form id="viewForm" class="form-horizontal">
		      	<div class="form-group">
		      		<label class="col-sm-3 control-label">投保单</label>
		      		<div class="col-sm-9 text-left" id="modal-reviewPay-1"></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" id="modal-reviewPay-2"></div>
		      	</div>
		      	<div class="hr-line-dashed"></div>
		      	<div class="form-group">
		      		<label class="col-sm-3 control-label">反馈问题说明</label>
		      		<textarea cols="45" rows="2" id="reviewPayFailReason" placeholder="投保单或转账证明有问题时填写！"></textarea>
		      	</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-warning" type="button" id="mod-reviewPay-fail-submit"><strong>反馈问题给律师</strong></button>
	      		<button class="btn btn-primary" type="button" id="mod-reviewPay-submit"><strong>确认收款</strong></button>
			</div>
		</div>
	</div>
</div>

<div id="mod-file" 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="fileform" >
							<div class="col-xs-12">
								<input id="fileId" type="file" name="avatar" multiple />
								<input type="hidden" name="attachType" id="mod-file-attachType"/>
								<input type="hidden" name="orderId" id="mod-file-orderId"/>
							</div>
							<div class="col-xs-12">
								<select id="mod-file-accountSel" class="form-control input-sm"></select>
							</div>
							<div class="col-xs-12">
								<label class="col-sm-2 no-padding">银行账户:</label>
					      		<div class="col-sm-10 text-left no-padding">
					      			<input type="text" id="mod-file-accountNum" class="form-control" />
					      		</div>
							</div>
							<div class="col-xs-12">
								<label class="col-sm-2 no-padding">开户行:</label>
					      		<div class="col-sm-10 text-left no-padding">
					      			<input type="text" id="mod-file-accountBank" class="form-control" />
					      		</div>
							</div>
							<div class="col-xs-12">
								<label class="col-sm-2 no-padding">开户名:</label>
					      		<div class="col-sm-10 text-left no-padding">
					      			<input type="text" id="mod-file-accountName" class="form-control" />
					      		</div>
							</div>
							<div class="col-xs-12">
			      				<div class="hr hr-12 dotted"></div>
			      			</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>

<!-- 模态框（Modal） -->
<div id="modal-dispatch" class="modal fade" tabindex="-1" data-backdrop="static">
  <div class="modal-dialog" style="min-width: 400px;">
    <div class="modal-content">
       <div class="modal-header bg-primary">
           <button type="button" class="close white" data-dismiss="modal" aria-hidden="true">×</button>
           <h4 class="modal-title text-center" id="myModalLabel">配送</h4>
       </div>
     <div class="modal-body" id="modal-view-order-body">
      <form id="viewOrderForm" class="form-horizontal">
        <input type="hidden" name="orderId" id="modal-dispatch-orderId" />
        <div class="col-sm-12 text-left" style="margin-bottom:15px;">请谨慎操作，如果虚假出函，则关闭服务！</div>  
        <div class="form-group text-left" id="mod-audit-LawyerName-div">
          <label class="col-sm-3 control-label">收件人:</label>
          <label class="control-label" id="modal-dispatch-name"></label>   
        </div>
        <div class="form-group text-left" id="mod-audit-LawyerName-div">
          <label class="col-sm-3 control-label">联系电话:</label>
          <label class="control-label" id="modal-dispatch-phone"></label>
        </div>
        <div class="form-group text-left" id="mod-audit-LawyerName-div">
         <label class="col-sm-3 control-label">收件地址:</label>
         <label class="control-label" id="modal-dispatch-address"></label>
        </div>
        <hr class="style-one" style="border: 0;height: 1px;background: #333;
        background-image: linear-gradient(to right, #ccc, #333, #ccc);">        
        <div class="form-group text-left" id="mod-audit-LawyerName-div">
          <div class="col-sm-3 control-label">配送方式:</div>
          <div class="col-sm-2 control-label text-left">
             <select class="select" id="orderShippingType" onchange="orderShippingTypeOnchange();">
             <option value="4" selected = "selected">快递配送</option>
             <option value="6">专人送函</option>
             <option value="5">同城闪送</option>
          </select>
          </div>
        </div>
		  <div class="form-group text-left" id="modal-Ship-company">
			 <label class="col-sm-3 control-label text-left">快递公司:</label>
			 <div class="col-sm-9">
			   <input type="text" id="mod-dispatch-company" class="col-sm-9"/>
			 </div>
		  </div>      
        <div class="form-group text-left" id="modal-Ship-id">
          <label class="col-sm-3 control-label text-left">快递单号:</label>
          <div class="col-sm-6">
            <input type="text" id="mod-dispatch-id" class="col-sm-9"/>
          </div>
        </div>
        
        <div class="form-group text-left" id="modal-Ship-name">
          <label class="col-sm-3 control-label text-left">配送员姓名:</label>
          <div class="col-sm-9">
            <input type="text" id="mod-dispatch-name" class="col-sm-9"/>
          </div>
        </div>      
        <div class="form-group text-left" id="modal-Ship-mobile">
          <label class="col-sm-3 control-label text-left">配送员电话:</label>
          <div class="col-sm-6">
            <input type="text" id="mod-dispatch-mobile" class="col-sm-9"/>
          </div>
        </div>     
        <!--  <div class="form-group text-left" id="modal-Ship-time">
          <label class="col-sm-3 control-label text-left">送达时间:</label>
          <div class="col-sm-6">
            <input class="form-control" id="dispatch1ReachTime" size="16" type="text" placeholder="送达时间" readonly/> 
          </div>
        </div>-->
        <hr class="style-one" style="border: 0;height: 1px;background: #333;
        background-image: linear-gradient(to right, #ccc, #333, #ccc);">
      </form>
     </div>
     <div class="modal-footer no-margin-top">
      <div class="text-center">     
        <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>
</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">
<link rel="stylesheet" href="${contextPath}/static/ssdb/ace.fileinput.css"/>

<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 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/fileupload.js?v=2"></script>

<script type="text/javascript">
	var accountsObject = {};
	
	var currentOrderId = null;
	var gridTable1 = null;
	var grid_selector = "#gridTable2";
	var notSubmitReviewPayFail = true;
	var notSubmitReviewPayPass = true;
	var notSubmitSaveWlInfo = true;
    var pager_selector = "#gridPager2";
	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-reviewPay-fail-submit').on('click', function() {
   			reviewPayFailSubmit();
   		});
   		
   		$('#mod-reviewPay-submit').on('click', function() {
   			reviewPayPassSubmit();
   		});

	 	// Add responsive to jqGrid
        $(window).bind('resize', function () {
            var width = $('.jqGrid_wrapper').width();
            gridTable1.setGridWidth(width);
        });
	 	
        $('#mod-file-accountSel').change(function(){
        	onchangeAccountSel();
        }); 
	});
	
	
	function errorCallbackDefault(data){
		
	}

    function getBlankInfos(id){
    	accountsObject = {};
    	document.getElementById('mod-file-accountSel').innerHTML = '';
    	var url = '${contextPath}/order/getBlankInfos';
		var parameters = {"orderId":id};
		postData(url, parameters, getBlankInfosCallback, errorCallbackDefault);
    }

    function getBlankInfosCallback(data){
    	if(data.success){
    		document.getElementById("fileform").reset();
    		var html = '';
    		var info,v,t = null;
    		for(var i in data.accounts){
    			info = data.accounts[i];
    			//v = info.leval;
    			v = info.accountNum;
    			t = info.accountName;
    			if(v == 10){
    				t = '自定义';
    				b = true;
    			}
    			accountsObject[v] = info;
    			html += '<option value="' + v + '" >' + t + '</option>';
    		}
    		if(html.length > 0){
    			html = '<option value="" ></option>' + html;
    			document.getElementById('mod-file-accountSel').innerHTML = html;
    			
    			var obj = {'accountBank':'mod-file-accountBank','accountName':'mod-file-accountName','accountNum':'mod-file-accountNum'};
    			info = data.accounts[0];
	    		for(var o in obj){
	    			$('#' + obj[o]).val(info[o]);
	    		}
	    		//$('#mod-file-accountSel').val(info.leval);
	    		$('#mod-file-accountSel').val(info.accountNum);
    		}
        	$("#mod-file").modal("toggle");
    	}else{
			showMsg(data.message);
		}
    }
    
	function getOrderAttachsCallback(data){
		if(data.success){
			notSubmitReviewPayFail = true;
			notSubmitReviewPayPass = true;
			var html1 = '';
			var es = data.example3s;
			var e = null;
			var url = '${oss_bucket_ssdb_url}';
			var thum = '${oss_bucket_ssdb_url_img}';
			var size = '${oss_bucket_ssdb_url_img_size}';
			var path = null;
			for(var i in es){
				e = es[i];
				path = e.path;
				if(path.indexOf('/') != 0){
					path = '/' + path;
				}
				html1 +='<a href="' + url + path + '" target="_blank">';
				html1 += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + path + size + e.suffix.toLowerCase() + '" height="100" width="100"/>';
				html1 +='</a>&nbsp;';
			}
			if(html1!=''){
				$('#modal-reviewPay-1').html(html1);
			}else
				$('#modal-reviewPay-1').html('无');

			var html2 = '';
			es = data.payed;
			for(var i in es){
				e = es[i];
				path = e.path;
				if(path.indexOf('/') != 0){
					path = '/' + path;
				}
				html2 +='<a href="' + url + path + '" target="_blank">';
				html2 += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + path + size + e.suffix.toLowerCase() + '" height="100" width="100"/>';
				html2 +='</a>&nbsp;';
			}
			if(html2!=''){
				$('#modal-reviewPay-2').html(html2);
			}else
				$('#modal-reviewPay-2').html('无');
			
			$("#modal-reviewPay").modal('toggle');
			//alert(1);
			setTimeout(function () {
				$("img.lazy").lazyload({
					threshold : 200
				});
			  }, 200);
			
		}else{
			showMsg(data.message);
		}
		
	}
	
	function initGridTable(){
		gridTable1 = jQuery(grid_selector).jqGrid({
			subGrid : false,
   			url : "${contextPath}/order/getOrders?orderState=2&orderServiceType=1",//
   			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 : 80,
   				sortable: false,
   				search : false
        	},{
   				name : "bf",
   				index : "bf",
   				label : "保费（元）",
   				width : 80,
   				search : false
        	},{
   				name : "lpDate",
   				index : "lpDate",
   				label : "承诺收款时间",
   				width : 110,
   				search : false
        	},{
   				name : "contactName",
   				index : "contactName",
   				label : "申请人",
   				width : 60,
   				search : false
        	},{
   				align : "center",
   				name : "payState",
   				index : "payState",
   				label : "操作",
   				width : 300,
   				viewable:false,
   				sortable: false,
   				fixed:true,
   				formatter:operationLink
        	}],
   			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 isBlank(obj){
		var result = false;
		if(obj == undefined || obj == null || obj == 'null' || obj.length < 1){
			result = true;
		}
		return result;
	}

	function onchangeAccountSel(){
		var obj = {'accountBank':'mod-file-accountBank','accountName':'mod-file-accountName','accountNum':'mod-file-accountNum'};
		var info = {'accountBank':'','accountName':'','accountNum':''};
		var v = $('#mod-file-accountSel').val();
		if(!isBlank(v)){
			info = accountsObject[v];
		}
		for(var o in obj){
			$('#' + obj[o]).val(info[o]);
		}
	}

	//向后台请求数据
	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 = null;
		if('1' == rowObject.uploadPolicy){
			result = '<a href="javascript:void(0);" style="color:blue" onclick="uploadFileShow(74,\''+rowObject.orderId+'\')">重传投保单</a>';
		}else{
			result = '<a href="javascript:void(0);" style="color:blue" onclick="uploadFileShow(74,\''+rowObject.orderId+'\')">上传投保单</a>';
		}
		result += '&nbsp;|&nbsp;';
		if("已配送" == rowObject.shippingState){
			result += '<a href="javascript:void(0);" style="color:blue" onclick="orderShipShow1()">已配送</a>';
		}else{
			result += '<a href="javascript:void(0);" style="color:blue" onclick="orderShipShow(\'' + rowObject.orderId + '\')">配送</a>';
		}
		result += '&nbsp;|&nbsp;';
		if('1' == cellvalue){
			result += '<a href="javascript:void(0);" style="color:blue" onclick="reviewPayOperation(\'' + rowObject.orderId + '\')">去确认</a>';
		}else{
			result += '未付款';
		}
		result += '&nbsp;|&nbsp;<a href="javascript:void(0);" style="color:blue" onclick="showdetail(\''+rowObject.orderId+'\')">详细</a>';
		return result;
	}
	
	function reloadGrid(){
		gridTable1.trigger('reloadGrid');
	}
	
	//保存付款未通过成功后回调
	function reviewPayFailCallback(data){
		notSubmitReviewPayFail = true;
		if(data.success){
			$("#modal-reviewPay").modal('toggle');
			showMsg('保存成功');
			reloadGrid();
		}else{
			showMsg(data.message);
		}
	}

	//保存付款未通过失败后回调
	function reviewPayFailErrorCallback(data){
		notSubmitReviewPayFail = true;
	}
	
	//保存付款未通过
	function reviewPayFailSubmit(){
		if(notSubmitReviewPayFail){
			var reason = $('#reviewPayFailReason').val();
			if(reason != undefined && reason.length > 0){
				notSubmitReviewPayFail = false;
				var url = '${contextPath}/order/saveReviewPayFail';
				var parameters = {"reason":reason,"orderId":currentOrderId};
				postData(url, parameters, reviewPayFailCallback, reviewPayFailErrorCallback);
			}else{
				alert('反馈问题说明不能为空');
			}
		}else{
			showMsg('提交中，请稍候');
		}
	}
	
	function reviewPayOperation(id){
		currentOrderId = id;
		var url = '${contextPath}/order/getOrderAttachs';
		var parameters = {"orderId":id};
		postData(url, parameters, getOrderAttachsCallback, errorCallbackDefault);
	}
	
	//保存付款通过成功后回调
	function reviewPayPassCallback(data){
		notSubmitReviewPayPass = true;
		if(data.success){
			$("#modal-reviewPay").modal('toggle');
			showMsg('保存成功');
			reloadGrid();
		}else{
			showMsg(data.message);
		}
	}

	//保存付款未通过失败后回调
	function reviewPayPassErrorCallback(data){
		notSubmitReviewPayPass = true;
	}
	
	//保存付款通过
	function reviewPayPassSubmit(){
		if(notSubmitReviewPayPass){
			notSubmitReviewPayPass = false;
			var url = '${contextPath}/order/saveReviewPayPass';
			var parameters = {"orderId":currentOrderId};
			postData(url, parameters, reviewPayPassCallback, reviewPayPassErrorCallback);
		}else{
			showMsg('提交中，请稍候');
		}
	}

	function search(){
		var keyword =$("#keyword").val();
		var searchDate =$("#searchDate").val();
		gridTable1.setGridParam({postData:{'keyword':keyword,'searchDate':searchDate,'orderState':2},url : '${contextPath}/order/getOrders',page:1}).trigger('reloadGrid');	
	}
	
	//显示信息
	function showMsg(msg){
		if(msg != undefined && msg.length > 0){
			alert(msg);
		}
	}
	
	function uploadFileShow(attachType,orderId){
		getBlankInfos(orderId);
		$("#mod-file-attachType").val(attachType);
		$("#mod-file-orderId").val(orderId);
	}
	 
	    
    function uploadFileSuccess(){
    	alert("文件上传成功！");
    	$("#mod-file").modal("toggle");
    	gridTable1.trigger('reloadGrid');	
    }
    
    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 accountBank = $('#mod-file-accountBank').val();
		 var accountName = $('#mod-file-accountName').val();
		 var accountNum = $('#mod-file-accountNum').val();
		 
		 var orderId=document.getElementById('mod-file-orderId').value;
		 var picfilenum =document.getElementById('fileId').files.length;
		 var keyArray ="";
		 var fileNameArray ="";
		 var fileTypeArray ="";
    	 for(var i=0;i<picfilenum;i++){
	    	 var picFile=document.getElementById('fileId').files[i];
	    	 var fileName = UUIDjs.create().hex;
	    	 var fileType = getFileType(picFile.name);
	    	 var oDate = new Date(); //实例一个时间对象；
	    	 var y = oDate.getFullYear();   //获取系统的年；
	    	 var m = oDate.getMonth()+1;   //获取系统月份，由于月份是从0开始计算，所以要加1
	    	 var d = oDate.getDate(); // 获取系统日
	         var key = "ssdb/order/${sessionScope.SESSION_COMPANY.id}/"+y+"/"+m+"/"+d+"/"+fileName+"."+fileType;
	         
	         client.multipartUpload(key, picFile, {
	            progress: progress
	        }).then(function(res) {
	        	
	        });
			if(i==picfilenum-1){
				keyArray += key;
				fileNameArray += fileName;
				fileTypeArray += fileType;
			}else{
				keyArray = keyArray + key +",";
				fileNameArray = fileNameArray+fileName+",";
				fileTypeArray = fileTypeArray+fileType+",";
			}
    	 }
    	 saveToDB(orderId,keyArray,fileNameArray,fileTypeArray,accountBank,accountName,accountNum);
    }
    ;
    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() {
    	var obj = {'mod-file-accountBank':'开户行','mod-file-accountName':'开户名','mod-file-accountNum':'银行账户'};
    	for(var o in obj){
    		if(isBlank($('#' + o).val())){
    			showMsg(obj[o] + '不能为空');
    			return;
    		}
    	}
        applyTokenDo(uploadFile);
    }

    function getFileType(fileName){
    	var ldot = fileName.lastIndexOf('.')
    	if(ldot>=0)
    		return fileName.substring(ldot + 1);
    	else
    		return "";
    }
    
    $('#mod-dispatch-submit').on('click', function() {
    	saveShipInfo();
     });
    //保存配送信息
    function saveShipInfo(){
    	var orderId = $("#modal-dispatch-orderId").val();
      var company = $("#mod-dispatch-company").val();
      var id = $("#mod-dispatch-id").val();
      var name = $("#mod-dispatch-name").val();
      var mobile = $("#mod-dispatch-mobile").val();
      var orderShippingType = $("#orderShippingType").val();
      var url = '${contextPath}/order/saveShipInfo';
      
      var parameters = {'orderId':orderId,'company':company,'id':id,'name':name,'mobile':mobile,'orderShippingType':orderShippingType};
      postData(url, parameters, saveWlInfoCallback, saveWlInfoCallbackErrorCallback);
    }
    
    //保存配送信息
    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 dispatchOperation(id){
       currentOrderId = id;
       //var ids = ['71','72','73'];
       var ids = ['71'];
       for(var i in ids){
          $('#div' + ids[i]).html('');
       }
       loadWlInfo();
    }
    function orderShipShow1(){
    	alert("已配送");
    	return;
    }
    function orderShipShow(id){
        var url = '${contextPath}/order/getOrderWLInfo';
        var parameters = {"orderId":id};
        $.post(url, parameters, function (data) {
	        if (data.success) {
	        	$("#modal-dispatch-orderId").val(id);
	        	$("#modal-dispatch-address").html(data.wlInfos[0].address);
	        	$("#modal-dispatch-name").html(data.wlInfos[0].receiver);
	        	$("#modal-dispatch-phone").html(data.wlInfos[0].mobile);
	        	
            if(data.orderShippingType==4){
                $("#orderShippingType option[value='4']").attr("selected", true);
                $("#orderShippingType option[value='5']").attr("selected", false);
                $("#orderShippingType option[value='6']").attr("selected", false);
                
             } else if(data.orderShippingType==5){
                 $("#orderShippingType option[value='4']").attr("selected", false);
                 $("#orderShippingType option[value='5']").attr("selected", true);
                 $("#orderShippingType option[value='6']").attr("selected", false);
             } else if(data.orderShippingType==6){
                 $("#orderShippingType option[value='4']").attr("selected", false);
                 $("#orderShippingType option[value='5']").attr("selected", false);
                 $("#orderShippingType option[value='6']").attr("selected", true);
             }
            
            if (data.orderShippingType==5||data.orderShippingType==6) {
                $("#modal-Ship-company").hide();
                $("#modal-Ship-id").hide();
                $("#modal-Ship-name").show();
                $("#modal-Ship-mobile").show();
                $("#modal-Ship-time").show();
             } else {
            	 alert("44444");
                $("#modal-Ship-company").show();
                $("#modal-Ship-id").show();
                $("#modal-Ship-name").hide();
                $("#modal-Ship-mobile").hide();
                $("#modal-Ship-time").hide();
             }
            $("#mod-dispatch-company").val("");
            $("#mod-dispatch-id").val("");
            $("#mod-dispatch-name").val("");
            $("#mod-dispatch-mobile").val("");
            //$("#modal-Ship-time").val("");       	
	        	$("#modal-dispatch").modal('toggle');
	        } else {
	        	alert("获取配送信息出错："+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 errorCallbackDefault(data){
        
    }
    
    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 orderShippingTypeOnchange(){
    	var orderShippingType = $("#orderShippingType").val();
    	if (orderShippingType==5||orderShippingType==6) {
    		$("#modal-Ship-company").hide();
    		$("#modal-Ship-id").hide();
    		$("#modal-Ship-name").show();
    		$("#modal-Ship-mobile").show();
    		$("#modal-Ship-time").show();
    	} else {
         $("#modal-Ship-company").show();
         $("#modal-Ship-id").show();
         $("#modal-Ship-name").hide();
         $("#modal-Ship-mobile").hide();
         $("#modal-Ship-time").hide();
    	}
    }
    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
         });
      }
    
    function saveToDB(orderId,keyArray,fileNameArray,fileTypeArray,accountBank,accountName,accountNum){
    	var attachType = $("#mod-file-attachType").val();
		var parameters = {"orderId":orderId,"attachType":attachType,"path":keyArray,"fileNameArray":fileNameArray,"fileTypeArray":fileTypeArray,"accountBank":accountBank,"accountName":accountName,"accountNum":accountNum};
		console.log(parameters);
		$.getJSON('${contextPath}/order/bdTempleteUpload',parameters,function(result){
			if(result.success){
				uploadFileSuccess();
			}else
				alert(result.message);
		});
    	
    }
</script>