<%@ 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(6,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>订单统计</li>
            <li>订单列表</li>
<%--            <li class="active" id="navigationList"><strong>待审核</strong></li>--%>
<%--            <li id="navigationReview1" style="display:none">待审核</li>--%>
<%--            <li class="active" id="navigationReview2" style="display:none"><strong>审核资料</strong></li>--%>
        </ol>
    </div>
</div>

<div class="wrapper wrapper-content">
    <div class="row">
        <div class="col-lg-12" id="gridTable1List">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="row">
                        <div class="col-sm-2">
                               <select  class="form-control" id="orderState">
                                   <option value="">状态</option>
                                   <option value="0">待审核</option>
                                   <option value="10">已取消</option>
                                   <option value="20">审核失败</option>
                                   <option value="21">审核问题反馈</option>
                                   <option value="22">待付款</option>
                                   <option value="30">等待付款确认</option>
                                   <option value="31">付款问题反馈</option>
                                   <option value="32">待出函</option>
                                   <option value="40">已出函</option>
                                   <option value="41">已配送</option>
                                   <option value="50">退保处理中</option>
                                   <option value="51">退保成功</option>
                                   <option value="52">退保失败</option>
                               </select>
                        </div>
                        <div class="col-md-2">
                            <select class="form-control input-sm" id="province">
                                <option value="">省份</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <select class="form-control input-sm" id="city">
                                <option value="">城市</option>
                            </select>
                        </div>
                        <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="startDate">
                            </div>
                        </div>
                        <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="endDate">
                            </div>
                        </div>

                        <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="payedStartDate">
                            </div>
                        </div>
                        <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="pavedEndDate">
                            </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="gridTable1"></table>
                            <div id="gridPager1"></div>
                            <div>订单总数：<span id="count"></span>|保费总额：<span id="priceCount"></span>|客单价：<span id="unitPrice"></span></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row" id="gridTable1Review" style="display:none">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-content" id= "gridTable1ReviewDetail">
                </div>
            </div>
        </div>
    </div>
</div>

<%--审核失败原因--%>
<div id="modal-reviewFail" class="modal fade" tabindex="-1">
    <div class="modal-dialog" style="max-width: 400px;">
        <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">
                <div class="form-group">失败原因：</div>
                <div class="form-group"><textarea cols="39" rows="5" id="reviewFailReason"></textarea></div>
            </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-reviewFail-submit"><strong><i class="fa fa-floppy-o bigger-160"></i>确定</strong></button>
            </div>
        </div>
    </div>
</div>

<%--付款不通过原因--%>
<div id="modal-reviewFail2" class="modal fade" tabindex="-1">
    <div class="modal-dialog" style="max-width: 400px;">
        <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">
                <div class="form-group">付款不通过原因：</div>
                <div class="form-group"><textarea cols="39" rows="5" id="reviewFailReason2"></textarea></div>
            </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-reviewFail-submit2"><strong><i class="fa fa-floppy-o bigger-160"></i>确定</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-email" class="modal fade" tabindex="-1">
    <div class="modal-dialog" style="max-width: 400px;">
        <div class="modal-content">
            <div class="modal-body">
                <div class="form-group">审核资料将发送到以下邮箱</div>
                <div class="form-group"><input class="form-control" id="email-address" value="${cookie.emailAddress.value}"></div>
                <div class="form-group text-center">
                    <button class="btn btn-primary" type="button" id="mod-Email-submit" >确定发送</button>
                    <button class="btn " data-dismiss="modal" style="margin-left: 10px">取消</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="modal-replyLawyer" class="modal fade" tabindex="-1">
    <div class="modal-dialog" style="max-width: 400px;">
        <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" id="modal-replyLawyer-body"></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-replyLawyer-submit"><strong><i class="fa fa-floppy-o bigger-160"></i>确定</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" style="height: 26px;margin-top: 11px;">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="margin-right: 10px;">
                        <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 type="hidden" name="attachType" id="mod-file-accountSel"/>
                                <input type="hidden" name="attachType" id="mod-file-attachType"/>
                                <input type="hidden" name="attachType" id="mod-file-attachTemplateType"/>
                                <input type="hidden" name="orderId" id="mod-file-orderId"/>
                                <div class="col-sm-6 ">
                                    <label for="fileId">投保单</label>
                                    <input type="file" id="fileId" name="avatar" multiple>
                                </div>
                                <div class="col-sm-6 ">
                                    <label for="templateId">保函模板</label>
                                    <input type="file" id="templateId" name="avatar" multiple>
                                </div>
                            </div>
                            <div class="col-xs-12">
                                <label class="col-sm-3 no-padding">输入收款账号</label>
                                <div class="col-sm-9 text-left no-padding">
                                </div>
                            </div>
                            <div class="col-xs-12">
                                <label class="col-sm-2 no-padding" style="margin-top: 10px;">地区:</label>
                                <div class="col-sm-4 text-left" style="padding-bottom: 10px;">
                                    <select class="form-control" id="address-province">
                                        <option selected value="0">省</option>
                                    </select>
                                </div>
                                <label class="col-sm-2 no-padding"></label>
                                <div class="col-sm-4 text-left">
                                    <select class="form-control" id="address-city">
                                        <option selected value="0">市</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-xs-12">
                                <label class="col-sm-2 no-padding" style="margin-top: 10px;">账户名:</label>
                                <div class="col-sm-10 text-left no-padding">
                                    <input type="text" id="mod-file-accountName" class="form-control" style="margin-bottom: 5px"/>
                                </div>
                            </div>
                            <div class="col-xs-12">
                                <label class="col-sm-2 no-padding" style="margin-top: 10px;">账号:</label>
                                <div class="col-sm-10 text-left no-padding">
                                    <input type="text" id="mod-file-accountNum" class="form-control" style="margin-bottom: 5px"/>
                                </div>
                            </div>
                            <div class="col-xs-12">
                                <label class="col-sm-2 no-padding" style="margin-top: 10px;">开户行:</label>
                                <div class="col-sm-10 text-left no-padding">
                                    <input type="text" id="mod-file-accountBank" class="form-control" style="margin-bottom: 5px"/>
                                </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="fileUpload2();">上传</button>
                                <button type="reset" class="btn btn-sm">清除</button>
                            </div>
                        </form>
                    </div><!-- /.col -->
                </div><!-- /.row -->

            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</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 href="${contextPath}/static/css/plugins/datapicker/datepicker3.css" rel="stylesheet">
<link href="${contextPath}/static/ssdb/ace.fileinput.css" rel="stylesheet"/>
<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>
<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>
<!-- 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" src="${contextPath}/static/ssdb/picupload.js?v=2"></script>
<script src="${contextPath}/static/ssdb/china_area.js"></script>

<script type="text/javascript">
    var accountsObject = {};
    $.each(provinceJson, function (k, p) {
        var option = "<option value='" + p.id + "'>" + p.province + "</option>";
        $("#selProvince").append(option);
        $("#province").append(option);
    });
    $("#province").change(function () {
        var selValue = $(this).val();
        $("#city option:gt(0)").remove();
        $.each(cityJson, function (k, p) {
            // 直辖市处理.|| p.parent == selValue，直辖市为当前自己
            if (p.id == selValue || p.parent == selValue) {
                var option = "<option value='" + p.city + "'>" + p.city + "</option>";
                $("#city").append(option);
            }
        });
    });
    $("#selProvince").change(function () {
        var selValue = $(this).val();
        $("#selCity option:gt(0)").remove();
        $.each(cityJson, function (k, p) {
            // 直辖市处理.|| p.parent == selValue，直辖市为当前自己
            if (p.id == selValue || p.parent == selValue) {
                var option = "<option value='" + p.city + "'>" + p.city + "</option>";
                $("#selCity").append(option);
            }
        });
    });

    //oss

    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 uploadFile2 = 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/"+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+",";
            }
        }


        var picfilenumTemplate =document.getElementById('templateId').files.length;
        var keyArrayTemplate ="";
        var fileNameArrayTemplate ="";
        var fileTypeArrayTemplate ="";
        for(var i=0;i<picfilenumTemplate;i++){
            var picFile=document.getElementById('templateId').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/"+y+"/"+m+"/"+d+"/"+fileName+"."+fileType;

            client.multipartUpload(key, picFile, {
                progress: progress
            }).then(function(res) {

            });
            if(i==picfilenumTemplate-1){
                keyArrayTemplate += key;
                fileNameArrayTemplate += fileName;
                fileTypeArrayTemplate += fileType;
            }else{
                keyArrayTemplate = keyArrayTemplate + key +",";
                fileNameArrayTemplate = fileNameArrayTemplate+fileName+",";
                fileTypeArrayTemplate = fileTypeArrayTemplate+fileType+",";
            }
        }

        if (fileTypeArrayTemplate == null || fileTypeArrayTemplate == '') {
            showMsg( '保函模板不能为空，请重新上传');
            return;
        }

        var imgeType = fileTypeArrayTemplate.toLowerCase();
        saveToDB2(orderId,keyArray,keyArrayTemplate,fileNameArray,fileNameArrayTemplate,fileTypeArray,fileTypeArrayTemplate,accountBank,accountName,accountNum);
    };

    //删除图片
    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);
        }
    }

    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;
    };

    var companyMaterialObj = {};
    var currentOrderId = null;
    var gridTable1 = null;
    var grid_selector = "#gridTable1";
    var notSubmitReplyLawyer = true;
    var notSubmitReviewFail = true;
    var notSubmitReviewPass = true;
    var pager_selector = "#gridPager1";
    jQuery(function($) {
        $('#startDate').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true,
            format: "yyyy-mm-dd"
        });
        $('#endDate').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true,
            format: "yyyy-mm-dd"
        });
        $('#payedStartDate').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true,
            format: "yyyy-mm-dd"
        });
        $('#pavedEndDate').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true,
            format: "yyyy-mm-dd"
        });

        initGridTable();
        // $("#priceCount").text(priceCount);
        // $("#count").text(count);
        // 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-reviewFail-submit').on('click', function() {
            reviewFailSubmit();
        });
        $('#mod-reviewFail-submit2').on('click', function() {
            reviewFailSubmit2();
        });
        $('#mod-replyLawyer-submit').on('click', function() {
            replyLawyerSubmit();
        });

        // 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 getFileType(fileName){
        var ldot = fileName.lastIndexOf('.')
        if(ldot>=0)
            return fileName.substring(ldot + 1);
        else
            return "";
    }

    function getBlankInfos(id){
        $("#mod-file-accountName").val("");
        $("#mod-file-accountBank").val("");
        $("#mod-file-accountNum").val("");
        var url = '${contextPath}/order/getAreaBlankInfos';
        var parameters = {"orderId":id};
        postData(url, parameters, getBlankInfosCallback, errorCallbackDefault);
    }

    function getBlankInfosCallback(ret){
        $("#address-province").html("");
        $("#address-city").html("");
        if(ret.success){
            $("#mod-file").modal("toggle");
            var optionProvince = '';
            var provinceArray = ret.provinceList ;
            for(var i=0; i<provinceArray.length; i++) {
                optionProvince += '<option value=' + provinceArray[i].code +'>'+provinceArray[i].areaName +'</option>';
            }
            $("#address-province").append(optionProvince);
            //选中
            $("#address-province").val(ret.targetProvinceCode);

            var optionCity = '';
            var cityListArray = ret.cityList ;
            if(cityListArray && cityListArray.length > 0){
                for(var i=0; i<cityListArray.length; i++) {
                    optionCity += '<option value=' + cityListArray[i].code +'>'+cityListArray[i].areaName +'</option>';
                }
            }
            $("#address-city").append(optionCity);
            //选中
            $("#address-city").val(ret.targetCityCode);

            $("#mod-file-accountName").val(ret.accountName);
            $("#mod-file-accountBank").val(ret.accountBank);
            $("#mod-file-accountNum").val(ret.accountNum);

        }else{
            showMsg(ret.message);
        }
    }

    $("#address-province").change(function(){
        var selectval = $("#address-province").val();

        $.ajax({
            dataType : "json",
            url : "${contextPath}/pub/getAreas",
            type : "post",
            data : {
                'parentCode' : selectval,
            },
            success : function(ret) {
                if(ret != null){
                    var optionCity = '';
                    var cityListArray = ret;
                    $("#address-city").html(optionCity);
                    for(var i=0; i<cityListArray.length; i++) {
                        optionCity += '<option value=' + cityListArray[i].code +'>'+cityListArray[i].name +'</option>';
                    }
                    $("#address-city").append(optionCity);
                    //选中
                    $("#address-city").val(0);
                }
            }
        });
    });

    $("#address-city").change(function(){
        var selectval = $("#address-city").val();
        var orderId = $("#mod-file-orderId").val();
        //根据公司id 和 省市 返回具体地址
        $.ajax({
            dataType : "json",
            url : "${contextPath}/company/getCompanyAccount",
            type : "post",
            data : {
                'cityCode' : selectval,
                'orderId' : orderId
            },
            success : function(ret) {
                if(ret.success){
                    var tempRet = ret.ssdbCompanyAccount;
                    $("#mod-file-accountName").val(tempRet.accountName);
                    $("#mod-file-accountBank").val(tempRet.accountBank);
                    $("#mod-file-accountNum").val(tempRet.accountNum);
                } else {
                    $("#mod-file-accountName").val("");
                    $("#mod-file-accountBank").val("");
                    $("#mod-file-accountNum").val("");
                }
            }
        });
    });


    //获取订单详情成功回调
    function getOrderDetailCallback(data){
        if(data.orderInfoBean.success){
            var divObj = $('#gridTable1ReviewDetail');
            var o = data.orderInfoBean.order;
            var html = '<h3 class="ma">基本信息</h3>'
            html += '<div class="row">'
                + '<div class="col-md-3 ma"><strong>订单号：'+formatString(o.orderId) +'</strong></div>'
                + '<div class="col-md-3 ma"><strong>法院：'+formatString(o.courtName)+'</strong></div>'
                + '<div class="col-md-3 ma"><strong>保全金额：'+ formatString(o.sqbd)+'</strong>（元）</div>'
                + '</div>'
                + '<div class="row">'
                + '<div class="col-md-3 ma"><strong>费率：'+ formatString(o.sbRate) +'</strong></div>'
                + '<div class="col-md-3 ma"><strong>保费：'+ formatString(o.bf)  +'</strong>（元）</div>'
                + '<div class="col-md-3 ma"><strong>原告：' + formatString(o.plaintiff) + '</strong></div>'
                + '</div>'
                + '<div class="row">'
                + '<div class="col-md-3 ma"><strong>订单状态：' + formatString(o.orderState) + '</strong></div>'
                + '<div class="col-md-3 ma"><strong>跟单人员：' + formatString(o.documentaryUser) + '</strong></div>'
                + '<div class="col-md-3 ma"><strong>案件类型：' + formatString(o.dictCode) + '</strong></div>'
                + '</div>';
                + '<div class="hr-line-dashed"></div>';


            //基本信息资源(图片之类的)
            var a = data.orderInfoBean.attachs;
            var aName = null;
            var oa = null;
            var i = 1;
            var url = '${oss_bucket_ssdb_url}';
            var thum = '${oss_bucket_ssdb_url_img}';
            var size = '${oss_bucket_ssdb_url_img_size}';

            //循环图片名字
            for(var j in a){
                row = a[j];
                aName = formatString(row.name);
                if(aName.length > 0){
                    companyMaterialObj[row.companyAttachId] = aName;
                    html += '<div class="row">'
                        + '<div class="col-md-2">' + i + '、' + aName + '</div>'
                        + '<div class="col-md-10">';
                    //循环对应图片
                    for(var m in row.attachs){
                        oa = row.attachs[m];
                        html +='<a href="' + url + oa.path + '" target="_blank">';
                        html += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + oa.path + size + oa.suffix.toLowerCase() + '" height="100" width="100">';
                        html +='</a>&nbsp;';
                    }
                    html +=   '</div>'
                        + '</div>'
                        + '<div class="hr-line-dashed"></div>';
                    i++;
                }
            }
            html += '<div class="row">'
                + '<div class="col-sm-12 text-center ">'
                + 	'<button class="btn btn-primary text-center" type="button" onClick="downExamineData()" style="margin-right: 30px;">下载资料</button>'
                + 	'<button class="btn btn-primary" type="button" onClick="showEmailComfig()">邮件发送资料</button>'
                + '</div>'
                + '</div>'
                + '<div class="hr-line-dashed"></div>';

            //审核信息

            html += '<h3 class="ma">审核</h3>'
            html += '<div class="row">'
                + '<div class="col-md-2 ma"><strong>提交时间：'+formatString(o.createDate) +'</strong></div>'
                + '<div class="col-md-3 ma"><strong>承诺首次审核时间：'+formatString(o.lcDate)+'</strong></div>'
                + '<div class="col-md-3 ma"><strong>实际首次审核时间：'+ formatString(o.checkDate)+'</strong></div>'
                + '<div class="col-md-2 ma"><strong>审核时效：'+ getHour(o.lcDate,o.checkDate) +'</strong></div>'
                + '</div>';
            + '<div class="hr-line-dashed"></div>';
            var logReplys = data.orderInfoBean.logReplys;
            if(logReplys.length>0){
                html += '<div class="row">'
                    + '<div class="col-md-2 ma"><strong>保险公司要求补充资料：</strong></div>';
                for(var j in logReplys){
                    row = logReplys[j];
                    if(row.attachType == 21 || row.attachType == 52){
                        var content = row.createDate +" "+row.content;
                        html +="<strong>"+content+"</strong>";
                    }
                }
                html += '</div>'
                + '<div class="hr-line-dashed"></div>';
            }else{
                html += '<div class="row">'
                    + '<div class="col-md-5 ma"><strong>保险公司要求补充资料：</strong></div>'
                    + '</div>'
                + '<div class="hr-line-dashed"></div>';
            }

            html += '<div class="row">'
                + '<div class="col-md-12 ma"><strong>律师上传的补充资料：';
                var additionalMaterials = data.additionalMaterials;
                if(additionalMaterials.length > 0){
                    for(var m in additionalMaterials){
                        oa = additionalMaterials[m];
                        html +='<a href="' + url + oa.path + '" target="_blank">';
                        html += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + oa.path + size + oa.suffix.toLowerCase() + '" height="100" width="100">';
                        html +='</a>&nbsp;';
                    }
                }
            html+='</strong></div>'
                + '</div>'
            + '<div class="hr-line-dashed"></div>';

            //下载补充的资料
            if(additionalMaterials.length > 0) {
                html += '<div class="row">'
                    + '<div class="col-sm-12 text-center ">'
                    + '<button class="btn btn-primary text-center" type="button" onClick="downloadAdditionalMaterials()" style="margin-right: 30px;">下载补充的资料</button>'
                    + '</div>'
                    + '</div>'
                    + '<div class="hr-line-dashed"></div>';
            }

            //律师对审核结果的回复
            html += '<div class="row">'
                + '<div class="col-md-2 ma"><strong>律师对审核结果的回复：</strong></div>';
                for(var j in logReplys){
                row = logReplys[j];
                if(row.attachType == 51){
                    var content = row.createDate +" "+row.content;
                    html +="<strong>"+content+"</strong>";
                }
            }
                html += '</div>'
            + '<div class="hr-line-dashed"></div>';

                //审核
            if(o.orderStateValue == 0){
                html += '<div class="row">'
                    + '<div class="col-md-4"></div>'
                    + '<div class="col-md-1 text-center">'
                    + '<button class="btn btn-primary" type="button" onClick="reviewPassSubmit()">审核通过</button>'
                    + '</div>'
                    + '<div class="col-md-2 text-center">'
                    + '<button class="btn btn-primary" type="button" onClick="replyLawyerPageShow()">资料审核问题反馈</button>'
                    + '</div>'
                    + '<div class="col-md-1 text-center">'
                    + '<button class="btn btn-default" type="button" onClick="reviewFailPageShow()">审核失败</button>'
                    + '</div>'
                    + '<div class="col-md-4"></div>'
                    + '</div>';
                html += '<div class="hr-line-dashed"></div>';
            }

            //付款信息
            var companyInfo = data.companyInfo;
            //账户名
            var accountName = "";
            //账号
            var accountNum = "";
            //开户行
            var accountBank = "";
            if(companyInfo.accountName){
                accountName = companyInfo.accountName;
            }
            if(companyInfo.accountNum){
                accountNum = companyInfo.accountNum;
            }
            if(companyInfo.accountBank){
                accountBank = companyInfo.accountBank;
            }
            html += '<h3 class="ma">付款</h3>'
            html += '<div class="row">'
                + '<div class="col-md-2 ma"><strong>保险公司收据信息</strong></div>'
                + '</div>';

            html += '<div class="form-group">'
                    +'<div class="row ma">'
                    +'<label class="col-sm-1 control-label"> 账户名：</label>'
                    +'<input class="col-sm-3 text-left" value="'+accountName+'" id="accountName">'
                    +'</div>'
                    +'<div class="row ma">'
                    +'<label class="col-sm-1 control-label">账号：</label>'
                    +'<input class="col-sm-3 text-left" value="'+accountNum+'" id="accountNum">'
                    +'</div>'
                    +'<div class="row ma">'
                    +'<label class="col-sm-1 control-label">开户行：</label>'
                    +'<input class="col-sm-3 text-left" value="'+accountBank+'" id="accountBank">'
                    +'</div>'
                    +'</div>'
                    +'<div class="row ma">'
                    +'<button class="btn  btn-primary" style="margin-left: 500px" type="button" onClick="saveCompanyInfo()">保存</button>';
                    +'</div>'
            html += '<div class="hr-line-dashed"></div>';

            //订单资源
            var ssdbOrderAttachList = data.ssdbOrderAttachList;
            //未签名的投保单
            var SsdbOrderAttach74;
            //未盖章保函模板
            var SsdbOrderAttach70;
            //律师上传的投保单
            var SsdbOrderAttach52;
            //律师上传的付款凭证
            var SsdbOrderAttach41;
            //盖章保函图片
            var SsdbOrderAttach71;
            //盖章保单图片
            var SsdbOrderAttach72;
            if(ssdbOrderAttachList && ssdbOrderAttachList.length > 0){
                for(var j in ssdbOrderAttachList){
                    switch (ssdbOrderAttachList[j].attachType) {
                        case 70:
                            //未盖章保函模板
                            SsdbOrderAttach70 = ssdbOrderAttachList[j];
                            break;
                        case 74:
                            //未签名的投保单
                            SsdbOrderAttach74 = ssdbOrderAttachList[j];
                            break;
                        case 52:
                            //律师上传的投保单
                            SsdbOrderAttach52 = ssdbOrderAttachList[j];
                            break;
                        case 41:
                            //律师上传的付款凭证
                            SsdbOrderAttach41 = ssdbOrderAttachList[j];
                            break;
                        case 71:
                            //盖章保函图片
                            SsdbOrderAttach71 = ssdbOrderAttachList[j];
                            break;
                        case 72:
                            //盖章保单图片
                            SsdbOrderAttach72 = ssdbOrderAttachList[j];
                            break;

                    }
                }
            }

            html += '<div class="form-group">'
                 +'<div class="row ma">'
                 +'<label class="col-sm-2 control-label">未签名的投保单 </label>'
                 +'<div class="col-sm-9 text-left">'
                 +'<div id="div74" class="checkbox-inline">'
                if(SsdbOrderAttach74){
                    html += '<div style="text-align:center;display:inline-block;vertical-align:top;" id="picDiv' + SsdbOrderAttach74.id + '">';
                    html += '<a href="' + url +'/' +SsdbOrderAttach74.path + '" target="_blank">';
                    html += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum +'/'+ SsdbOrderAttach74.path + size + SsdbOrderAttach74.suffix.toLowerCase() + '" height="100" width="100" id="' + SsdbOrderAttach74.id + '"/>';
                    html += '</a>';
                    html += '</div>';
                }
            html +='</div>';
            if(!SsdbOrderAttach74){
                html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="uploadPic(74)">上传</button>'
            }
                 html += '</div></div> '
                +'<div class="row ma">'
                +'<label class="col-sm-2 control-label">未盖章保函模板</label>'
                +'<div class="col-sm-9 text-left">'
                +'<div id="div70" class="checkbox-inline">';
            if(SsdbOrderAttach70){
                html += '<div style="text-align:center;display:inline-block;vertical-align:top;" id="picDiv' + SsdbOrderAttach70.id + '">';
                html += '<a href="' + url + '/' +SsdbOrderAttach70.path + '" target="_blank">';
                html += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + '/'+SsdbOrderAttach70.path + size + SsdbOrderAttach70.suffix.toLowerCase() + '" height="100" width="100" id="' + SsdbOrderAttach70.id + '"/>';
                html += '</a>';
                html += '</div>';
            }
               html +='</div>';
            if(!SsdbOrderAttach70){
                html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="uploadPic(70)">上传</button>';
            }
                html+='</div> '
                 + '</div></div>';
            html += '<div class="hr-line-dashed"></div>';

            html += '<div class="row ma">'
                +'<label class="col-sm-2 control-label">律师上传的投保单</label>'
                +'<div class="col-sm-9 text-left">'
                +'<div id="div70" class="checkbox-inline">';
            if(SsdbOrderAttach52){
                html += '<div style="text-align:center;display:inline-block;vertical-align:top;" id="picDiv' + SsdbOrderAttach52.id + '">';
                html += '<a href="' + url + '/' +SsdbOrderAttach52.path + '" target="_blank">';
                html += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + '/'+SsdbOrderAttach52.path + size + SsdbOrderAttach52.suffix.toLowerCase() + '" height="100" width="100" id="' + SsdbOrderAttach52.id + '"/>';
                html += '</a>';
                html += '</div>';
            }
                html += '</div>'
                +'</div>'
                +'</div>';

            html += '<div class="row ma">'
                +'<label class="col-sm-2 control-label">律师上传的付款凭证</label>'
                +'<div class="col-sm-9 text-left">'
                +'<div id="div70" class="checkbox-inline">';
            if(SsdbOrderAttach41){
                html += '<div style="text-align:center;display:inline-block;vertical-align:top;" id="picDiv' + SsdbOrderAttach41.id + '">';
                html += '<a href="' + url + '/' +SsdbOrderAttach41.path + '" target="_blank">';
                html += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + '/'+SsdbOrderAttach41.path + size + SsdbOrderAttach41.suffix.toLowerCase() + '" height="100" width="100" id="' + SsdbOrderAttach41.id + '"/>';
                html += '</a>';
                html += '</div>';
            }
            html += '</div>'
                +'</div>'
                +'</div>';
            html += '<div class="hr-line-dashed"></div>';

            //发票信息
            html += '<div class="row ma">'
                + '<div class="col-md-2 ma"><strong>付款问题反馈：'+formatString(o.failReason);
            // if(logReplys.length > 0){
            //     for(var j in logReplys){
            //         row = logReplys[j];
            //         if(row.attachType == 31){
            //             var content = row.createDate +" "+row.content;
            //             html +=""+content+"";
            //         }
            //     }
            // }
                html +='</strong></div></div>';
                html +='<div class="row ma"><div class="col-md-2 ma"><strong>开票信息</strong> </div></div>';
                html +='<div class="row ma"><div class="col-md-2 ma"><strong>发票类型：'+formatString(data.orderFPBean.invoType)+'</strong></div></div>';
                html +='<div class="row ma"><div class="col-md-5 ma"><strong>发票抬头：'+formatString(data.orderFPBean.name)+'</strong></div></div>';
                html +='<div class="row ma"><div class="col-md-5 ma"><strong>纳税人识别号：'+formatString(data.orderFPBean.taxNum)+'</strong></div></div>';

            if(o.orderStateValue == 30){
                html += '<div class="row">'
                    + '<div class="col-md-4"></div>'
                    + '<div class="col-md-1 text-center">'
                    + '<button class="btn btn-primary" type="button" onClick="reviewPassSubmit2()">确认收款</button>'
                    + '</div>'
                    + '<div class="col-md-2 text-center">'
                    + '<button class="btn btn-default" type="button" onClick="reviewFailPageShow2()">付款不通过</button>'
                    + '</div>'
                    +'</div>';
            }

            html += '<div class="hr-line-dashed"></div>';



            html += '<h3 class="ma">出函</h3>';
            html += '<div class="row">'
                + '<div class="col-md-3 ma"><strong>付款时间：'+formatString(o.payedDate) +'</strong></div>'
                + '<div class="col-md-3 ma"><strong style="color: red">承诺出函时间：'+formatString(o.lsDate)+'</strong></div>'
                + '</div>'
                + '<div class="row">'
                + '<div class="col-md-3 ma"><strong>实际出函时间：'+ formatString(o.sendDate)+'</strong></div>'
                + '<div class="col-md-3 ma"><strong>出函时效：'+ getHour(o.lsDate,o.sendDate) +'</strong></div>'
                + '</div>'
               + '<div class="hr-line-dashed"></div>';

            //出函图片
            html += '<div class="row ma">'
                +'<label class="col-sm-2 control-label">盖章保函图片</label>'
                +'<div class="col-sm-9 text-left">'
                +'<div id="div71" class="checkbox-inline">';
            if(SsdbOrderAttach71){
                html += '<div style="text-align:center;display:inline-block;vertical-align:top;" id="picDiv' + SsdbOrderAttach71.id + '">';
                html += '<a href="' + url + '/' +SsdbOrderAttach71.path + '" target="_blank">';
                html += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + '/'+SsdbOrderAttach71.path + size + SsdbOrderAttach71.suffix.toLowerCase() + '" height="100" width="100" id="' + SsdbOrderAttach71.id + '"/>';
                html += '</a>';
                html += '</div>';
            }
            html += '</div>';
            if(!SsdbOrderAttach71){
                html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="uploadPic(71)">上传</button>'
            }
                html += '</div>'
                +'</div>';

            html += '<div class="row ma">'
                +'<label class="col-sm-2 control-label">盖章保单图片</label>'
                +'<div class="col-sm-9 text-left">'
                +'<div id="div72" class="checkbox-inline">';
            if(SsdbOrderAttach72){
                html += '<div style="text-align:center;display:inline-block;vertical-align:top;" id="picDiv' + SsdbOrderAttach72.id + '">';
                html += '<a href="' + url + '/' +SsdbOrderAttach72.path + '" target="_blank">';
                html += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + '/'+SsdbOrderAttach72.path + size + SsdbOrderAttach72.suffix.toLowerCase() + '" height="100" width="100" id="' + SsdbOrderAttach72.id + '"/>';
                html += '</a>';
                html += '</div>';
            }
            html += '</div>';
            if(!SsdbOrderAttach72){
                html += '<button class="btn btn-primary btn-white checkbox-inline" type="button" onclick="uploadPic(72)">上传</button>'
            }
            html += '</div>'
                +'</div>'
            + '<div class="hr-line-dashed"></div>';

            //配送
            html += '<h3 class="ma">配送</h3>';
            html += '<div class="row">'
                + '<div class="col-md-3 ma"><strong>配送方式：'+formatString(data.orderLogisticsVO.deliveryMethod) +'</strong></div>'
                + '<div class="col-md-3 ma"><strong>单号：'+formatString(data.orderLogisticsVO.logisticsNo)+'</strong></div>'
                + '</div>'
                + '<div class="row">'
                + '<div class="col-md-3 ma"><strong>配送时间：'+ formatString(data.orderLogisticsVO.logisticsDate) +'</strong></div>'
                + '</div>'
                + '<div class="hr-line-dashed"></div>';

            //跟单管理
            html += '<h3 class="ma">跟单管理</h3>';
            html += '<div class="row">'
                + '<label class="col-sm-5 ma" id="gendanRecordShow">跟单备注:'+formatString(o.gendanRecord)+'</label>'
                +'<div class="row">'
                + '<div class="col-sm-8 form-group ">'
                + 	'<textarea style="margin-left: 15px" cols="70" rows="5" id="gendanRecord" placeholder="输入跟单备注信息"></textarea>'
                + '</div>'
                +'</div>'
                + '<div class="col-sm-2 text-center no-padding">';
                html += '<button class="btn btn-primary" type="button" onClick="saveCompanyFeedback()" >发送</button>';
            html +=  '</div>'
                + '</div>';

            //操作记录
            html += '<div class="hr-line-dashed"></div>';
            html += '<h3 class="ma" >操作记录</h3>';

            html += '<span id="record">';
            if(o.record){
                var recordList =o.record.split('|');
                for(var j = 0;j<recordList.length-1;j++){
                    html += '<div class="row"><label class="col-sm-5">'+recordList[j]+'</label></div>'
                }
            }
            html += '</span>';
            divObj.html(html);

            setTimeout(function () {
                $("img.lazy").lazyload({
                    threshold : 200
                });
                $(".ma").css("margin-bottom","30px");
            }, 200);

        }else{
            showMsg(data.message);
        }
    }


    // //文件上传处理
    function fileUpload2() {
        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(uploadFile2);
    }


    function uploadPic(attachType){
        $("#mod-pic").modal("toggle");
        $("#mod-pic-attachType").val(attachType);
        $("#mod-pic-orderId").val(currentOrderId);
    }
    //获取审核时效
    function getHour(lcDate,checkDate){
        if(lcDate && checkDate){
            var date1 = new Date(checkDate);

            var date2 = new Date(lcDate);
            var s1 = date1.getTime(),s2 = date2.getTime();
            var total = (s2 - s1)/1000;
            var day = parseInt(total / (24*60*60));//计算整数天数
            var afterDay = total - day*24*60*60;//取得算出天数后剩余的秒数
            var hour = parseInt(afterDay/(60*60));//计算整数小时数
            return hour+"工作时";
        }else{
            return "";
        }
    }

    function formatString(str){
        var result = '';
        if(str != undefined && str != null){
            result = str;
        }
        return result;
    }

    function initGridTable(){
        gridTable1 = jQuery(grid_selector).jqGrid({
            subGrid : false,
            url : "${contextPath}/order/getOrderList",
            datatype : "json",
            height : "auto",
            autowidth:true,
            colModel : [{
                name : "orderCreateTime",
                index : "orderCreateTime",
                label : "订单时间",
                width : 120,
                search : false
            },{
                name : "orderId",
                index : "orderId",
                label : "订单号",
                width : 80,
                search : false
            },{
                name : "province",
                index : "province",
                label : "省",
                width : 80,
                search : false
            },{
                name : "court",
                index : "court",
                label : "法院",
                width : 80,
                search : false
            },{
                name : "plaintiff",
                index : "plaintiff",
                label : "原告",
                width : 60,
                sortable: false,
                search : false
            },{
                name : "sqbd",
                index : "sqbd",
                label : "保全金额",
                width : 50,
                search : false
            },{
                name : "probability",
                index : "probability",
                label : "费率",
                width : 50,
                search : false,
                formatter : format
            },{
                name : "price",
                index : "price",
                label : "保费",
                width : 100,
                search : false
            },{
                name : "remark",
                index : "remark",
                label : "状态",
                width : 120,
                search : false,
                formatter :state
            },{
                name : "documentaryUser",
                index : "documentaryUser",
                label : "跟单人员",
                width : 80,
                search : false,
            },{
                align : "center",
                name : "checkState",
                index : "checkState",
                label : "订单操作",
                width : 170,
                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 format(cellvalue, options, rowObject){
        return cellvalue.toFixed(2) + "%";
    }

    function optionFormatter(cellvalue, options, cell) {
        var template = cell.lcDate ;
        if (cell.overTime) {
            template += "  <button type=\"button\" style='background-color: #d30404;'><span style='color:white'>已超时</span></button>";
        }
        return template;
    }

    function state(cellvalue, options, cell) {
        var stateValue = cell.orderState;
        var isBusy = cell.isBusy;
        var isChaoshi = cell.isChaoshi;
        var template;
        switch (stateValue) {
            case 0:
                template = "<span>待审核</span>"
                break;
            case 10:
                template = "<span>已取消</span>"
                break;
            case 20:
                template = "<span>审核失败</span>"
                break;
            case 21:
                template = "<span>审核问题反馈</span>"
                break;
            case 22:
            case 30:
                template = "<span>待付款</span>"
                break;
            case 31:
                template = "<span>付款问题反馈</span>"
                break;
            case 32:
                template = "<span>待出函</span>"
                break;
            case 40:
                template = "<span >已出函</span>"
                break;
            case 41:
                template = "<span'>已配送</span>"
                break;
            case 50:
                template = "<span'>退保处理中</span>"
                break;
            case 51:
                template = "<span'>退保成功</span>"
                break;
            case 52:
                template = "<span'>退保失败</span>"
                break;
            default:
                template = "<span>无状态</span>"
                break;
        }
        if(isBusy == 1){
            template += "  <button type=\"button\" style='background-color: #d30404;'><span style='color:white'>加急</span></button>";
        }
        if(isChaoshi == 1){
            template += "  <button type=\"button\" style='background-color: #d30404;'><span style='color:white'>超时</span></button>";
        }
        return template;
    }

    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 = '';
        result += '<a href="javascript:void(0);" style="color:blue" onclick="reviewOperation(\''+rowObject.orderId+'\')">订单详情</a>';
        if(rowObject.count){
            $("#count").text(rowObject.count);
        }else{
            $("#count").text(0);
        }
        if(rowObject.priceCount){
            $("#priceCount").text(rowObject.priceCount);
        }else{
            $("#priceCount").text(0);
        }
        if(rowObject.unitPrice){
            $("#unitPrice").text(rowObject.unitPrice.toFixed(2));
        }else{
            $("#unitPrice").text(0);
        }
        return result;
    }

    function reloadGrid(){
        gridTable1.trigger('reloadGrid');
    }
    function reloadGrid2(){
        gridTable1.trigger('reloadGrid');
    }

    //保存反馈给律师信息成功后回调
    function replyLawyerCallback(data){
        notSubmitReplyLawyer = true;
        if(data.success){
            $("#modal-replyLawyer").modal('toggle');
            saveRecord(getDate()+" 反馈信息给律师");
            showMsg('保存成功');
            reloadGrid();
            reviewPageHide();
        }else{
            showMsg(data.message);
        }
    }

    //保存反馈给律师信息失败后回调
    function replyLawyerErrorCallback(data){
        notSubmitReplyLawyer = true;
    }

    //打开反馈给律师页面
    function replyLawyerPageShow(){
        notSubmitReplyLawyer = true;
        var divObj = $("#modal-replyLawyer-body");
        divObj.html('');
        var html = '';
        var i = 1;
        for(var key in companyMaterialObj){
            html += '<div class="form-group">' + i + '、' + companyMaterialObj[key] + '</div>'
                + '<div class="form-group"><textarea cols="39" rows="2" id="' + key +'" placeholder="请备注申请资料的问题，方便律师重新上传！"></textarea></div>'
            i ++;
        }
        divObj.html(html);
        $("#modal-replyLawyer").modal('toggle');
    }

    //保存反馈给律师信息
    function replyLawyerSubmit(){
        if(notSubmitReplyLawyer){
            var reasons = new Array();
            var reason = null;
            for(var key in companyMaterialObj){
                reason = $('#' + key).val();
                if(reason != undefined && reason.length > 0){
                    reasons.push(companyMaterialObj[key] + ':' + reason);
                }
            }
            if(reasons.length > 0){
                var url = '${contextPath}/order/saveReplyLawyer';
                var parameters = {"reasons":reasons,"orderId":currentOrderId};
                postData(url, parameters, replyLawyerCallback, replyLawyerErrorCallback);
            }else{
                showMsg('原因不能为空');
            }
        }else{
            showMsg('提交中，请稍候');
        }
    }

    function reviewCallback(data){
        showMsg('保存成功');
    }

    //保存审核失败成功后回调
    function reviewFailCallback(data){
        notSubmitReviewFail = true;
        if(data.success){
            $("#modal-reviewFail").modal('toggle');
            saveRecord(getDate()+" 审核失败");
            showMsg('保存成功');
            reloadGrid();
            reviewPageHide();
        }else{
            showMsg(data.message);
        }
    }

    //保存付款失败成功后回调
    function reviewFailCallback2(data){
        notSubmitReviewFail = true;
        if(data.success){
            $("#modal-reviewFail2").modal('toggle');
            saveRecord(getDate()+" 付款不通过");
            showMsg('操作成功');
            reloadGrid2();
            reviewPageHide();
        }else{
            showMsg(data.message);
        }
    }

    //保存审核失败失败后回调
    function reviewFailErrorCallback(data){
        notSubmitReviewFail = true;
    }

    //保存付款信息
    function saveCompanyInfo(){
        if(notSubmitReviewFail){
            //账户名
            var accountName = $("#accountName").val();
            //账户开行号
            var accountBank = $("#accountBank").val();
            //账户号
            var accountNum = $("#accountNum").val();
            if(accountName && accountBank && accountNum){
                var url = '${contextPath}/order/updateCompanyByOrderId';
                var parameters = {"accountName":accountName,"accountBank":accountBank,"accountNum":accountNum,"orderId":currentOrderId};
                $.ajax({
                    dataType : "json",
                    url : url,
                    type : "post",
                    data : parameters,
                    complete : function() {
                        showMsg('保存成功');
                        saveRecord(getDate()+" 修改了付款信息");
                    }
                });
                // postData(url, parameters, reviewCallback, reviewFailErrorCallback);
            }else{
                showMsg('信息不能为空');
            }
        }else{
            showMsg('提交中，请稍候');
        }

    }

    //打开审核失败页面
    function reviewFailPageShow(){
        var result = confirm("确认结束该订单吗？");
        if(result == true){
            notSubmitReviewFail = true;
            $("#modal-reviewFail").modal('toggle');
        }
    }

    //打开付款不通过页面
    function reviewFailPageShow2(){
        notSubmitReviewFail = true;
        $("#modal-reviewFail2").modal('toggle');

    }
    //保存审核失败
    function reviewFailSubmit(){
        if(notSubmitReviewFail){
            var reason = $('#reviewFailReason').val();
            if(reason != undefined && reason.length > 0){
                notSubmitReviewFail = false;
                var url = '${contextPath}/order/saveReviewFail';
                var parameters = {"reason":reason,"orderId":currentOrderId};
                postData(url, parameters, reviewFailCallback, reviewFailErrorCallback);
            }else{
                showMsg('失败原因不能为空');
            }
        }else{
            showMsg('提交中，请稍候');
        }
    }

    //保存付款失败
    function reviewFailSubmit2(){
        if(notSubmitReviewFail){
            var reason = $('#reviewFailReason2').val();
            if(reason != undefined && reason.length > 0){
                notSubmitReviewFail = false;
                var url = '${contextPath}/order/paymentFailed';
                var parameters = {"reason":reason,"orderId":currentOrderId};
                postData(url, parameters, reviewFailCallback2, reviewFailErrorCallback);
            }else{
                showMsg('失败原因不能为空');
            }
        }else{
            showMsg('提交中，请稍候');
        }
    }

    //保存审核通过成功后回调
    function reviewPassCallback(data){
        notSubmitReviewPass = true;
        if(data.success){
            gridTable1.trigger('reloadGrid');
            showMsg('保存成功,请上传需客户签名的投保单');
            saveRecord(getDate()+" 审核通过");
            uploadFileShow(74,70,currentOrderId);
            // reviewPageHide();
        }else{
            showMsg(data.message);
        }
    }

    //保存付款通过成功后回调
    function reviewPassCallback2(data){
        notSubmitReviewPass = true;
        if(data.success){
            gridTable1.trigger('reloadGrid');
            showMsg('操作成功');
                saveRecord(getDate()+" 付款通过");
            reviewPageHide();
        }else{
            showMsg(data.message);
        }
    }

    //保存审核通过失败后回调
    function reviewPassErrorCallback(data){
        notSubmitReviewPass = true;
    }

    //保存审核通过
    function reviewPassSubmit(){
        if(notSubmitReviewPass){
            notSubmitReviewPass = false;
            var url = '${contextPath}/order/saveReviewPass';
            var parameters = {"orderId":currentOrderId};
            postData(url, parameters, reviewPassCallback, reviewPassErrorCallback);
        }else{
            showMsg('提交中，请稍候');
        }
    }

    //保存付款通过
    function reviewPassSubmit2(){
        if(notSubmitReviewPass){
            notSubmitReviewPass = false;
            var url = '${contextPath}/order/paymentPassed';
            var parameters = {"orderId":currentOrderId};
            postData(url, parameters, reviewPassCallback2, reviewPassErrorCallback);
        }else{
            showMsg('提交中，请稍候');
        }
    }

    $("#mod-Email-submit").click(function () {
        var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
        var emailAddress = $("#email-address").val();
        if(emailAddress === ""){ //输入不能为空
            alert("输入不能为空!");
            return false;
        }else if(!reg.test(emailAddress)){ //正则验证不通过，格式不对
            alert("验证不通过!");
            return false;
        }else{
            $.ajax({
                dataType : "json",
                url : "${contextPath}/order/sendOrderAttachByEmail",
                type : "post",
                data : {
                    'orderId' : currentOrderId,
                    'key' : 31,
                    'email' : emailAddress,
                },
                success : function(ret) {
                    console.log(ret);
                    if(ret){
                        alert("发送成功");
                        $("#modal-email").modal("toggle");
                        saveRecord(getDate()+" 基本资料发送至邮箱："+emailAddress+"");
                    }else {
                        alert(ret.message);
                    }
                }
            });
        }
    });

    function uploadSuccess(){
        $("#mod-pic").modal("toggle");
        var t = $("#mod-pic-attachType").val();
        loadPic(t);
    }


    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/saveOrderAttach',parameters,function(result){
            if(result.success){
                var type = $("#mod-pic-attachType").val();
                var record = getDate();
                if(type == 74){
                    record +=" 上传了未签名投保单图片";
                }else if(type == 70){
                    record +=" 上传了未盖章保函模板图片";
                }else if(type == 71){
                    record +=" 上传了盖章保函图片";
                }else if(type == 72){
                    record +=" 上传了盖章保单图片";
                }
                saveRecord(record);
                uploadSuccess();
            }else
                alert(result.message);
        });

    }

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

    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/bd/"+orderId+"/"+fileName+"."+fileType;

        return client.multipartUpload(key, picFile, {
            progress: progress
        }).then(function(res) {
            saveToDB(orderId,key,fileName,fileType);
        });
    };

    //pic上传处理
    function picUpload() {
        applyTokenDo(uploadFile);
    }

    //下载审核资料
    function downExamineData() {
        window.open('${contextPath}/order/downloadOrderAttachsByType?id=' + currentOrderId + '&key=31');
        saveRecord(getDate()+" 下载了基本信息资料")
    }

    //补充的资料
    function downloadAdditionalMaterials(){
        window.open('${contextPath}/order/downloadAdditionalMaterials?id=' + currentOrderId + '&key=31');
    }

    function showEmailComfig() {
        $("#modal-email").modal("toggle");
    }

    function reviewOperation(id){
        companyMaterialObj = {};
        currentOrderId = id;
        reviewPageShow();
        notSubmitReviewPass = true;
        var url = '${contextPath}/order/getOrderDetailById';
        var parameters = {"orderId":id};
        postData(url, parameters, getOrderDetailCallback, errorCallbackDefault);
    }

    //关闭审核资料页面
    function reviewPageHide(){
        $('#gridTable1List').show();
        $('#navigationList').show();
        $('#gridTable1Review').hide();
        $('#navigationReview1').hide();
        $('#navigationReview2').hide();
    }

    //打开审核资料页面
    function reviewPageShow(){
        $('#gridTable1ReviewDetail').html('');
        $('#gridTable1List').hide();
        $('#navigationList').hide();
        $('#gridTable1Review').show();
        $('#navigationReview1').show();
        $('#navigationReview2').show();
    }

    //保存公司回复律师信息
    function saveCompanyFeedback(){
        var gendanRecord = $('#gendanRecord').val();
        if(!gendanRecord){
            showMsg('跟单备注信息不能为空');
        }else{
            var url = '${contextPath}/order/updateGendanRecord';
            var parameters = {"gendanRecord":gendanRecord,"orderId":currentOrderId};
            postData(url, parameters, saveCompanyFeedbackCallback2, errorCallbackDefault);
        }
    }

    //保存跟单备注的回调
    function saveCompanyFeedbackCallback2(data){
        notSubmitReplyLawyer = true;
        if(data.success){
            showMsg('保存成功');
            saveRecord(getDate()+" 修改了跟单备注");
            var content = $("#gendanRecord").val();
            var d = new Date();
            $("#gendanRecordShow").html("跟单备注："+d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+" "+content)
            $("#gendanRecord").val("");
        }else{
            showMsg(data.message);
        }
    }

    //获取当前时间
    function getDate(){
        var d = new Date();
        var date = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes();
        return date;
    }

    //添加操作记录
    function saveRecord(record){
        $.ajax({
            type : "POST",
            url : "${contextPath}/order/saveRecord",
            data : {
                'record' : record,
                'orderId':currentOrderId
            },
            dataType : "json",
            success : function(data) {
                $("#record").append('<div class="row"><label class="col-sm-5" >'+record+'</label></div>');
            },
            error : function(data) {
                errorCallback(data);
            }
        });
    }

    //保存公司回复律师信息成功后回调
    function saveCompanyFeedbackCallback(data){
        notSubmitReplyLawyer = true;
        if(data.success){
            showMsg('保存成功');
            reloadGrid();
            reviewPageHide();
        }else{
            showMsg(data.message);
        }
    }

    //保存图片路径到数据库
    function saveToDB2(orderId,keyArray,keyArrayTemplate,fileNameArray,fileNameArrayTemplate,fileTypeArray,fileTypeArrayTemplate,accountBank,accountName,accountNum){
        var attachType = $("#mod-file-attachType").val();
        var attachTemplateType = $("#mod-file-attachTemplateType").val();
        var parameters = {"orderId":orderId,"attachType":attachType,"attachTemplateType":attachTemplateType,"path":keyArray,
            "pathTemplate":keyArrayTemplate,"fileNameArray":fileNameArray,"fileNameArrayTemplate":fileNameArrayTemplate,
            "fileTypeArrayTemplate":fileTypeArrayTemplate,
            "fileTypeArray":fileTypeArray,"accountBank":accountBank,"accountName":accountName,"accountNum":accountNum};
        console.log(parameters);
        $.ajax({
            dataType : "json",
            url : "${contextPath}/order/bdTempleteUpload",
            type : "post",
            data : parameters,
            success : function(result) {
                if(result.success){
                    uploadFileSuccess();
                }else
                    alert(result.message);
            }
        });

    }

    function uploadFileSuccess(){
        alert("文件上传成功！");
        $("#mod-file").modal("toggle");
        gridTable1.trigger('reloadGrid');
    }

    //点击搜索
    function search(){
        //关键字
        var keyword =$("#keyword").val();
        //提交开始日期
        var startDate =$("#startDate").val();
        //提交结束日期
        var endDate =$("#endDate").val();
        //订单状态
        var orderState =$("#orderState").val();
        var province = $("#province").val();
        //省份
        var pName = "";
        if (province != '') {
            $.each(provinceJson, function (k, p) {
                if (province == p.id)
                    pName = p.province;
            });
        }
        // 城市
        var city = $("#city").val();
        //付款开始日期
        var payedStartDate = $("#payedStartDate").val();
        //付款结束日期
        var pavedEndDate = $("#pavedEndDate").val();

        gridTable1.setGridParam({postData:{'orderId':keyword,'createStartDate':startDate,'createEndDate':endDate,'orderState':orderState,'province':pName,'region':city,'payedStartDate':payedStartDate,'pavedEndDate':pavedEndDate},url : '${contextPath}/order/getOrderList',page:1}).trigger('reloadGrid');
    }

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

    //上传文件
    function uploadFileShow(attachType,attachTemplateType,orderId){
        $("#mod-file-orderId").val(orderId);
        getBlankInfos(orderId);
        $("#mod-file-attachType").val(attachType);
        $("#mod-file-attachTemplateType").val(attachTemplateType);
    }

    // function uploadSuccess(){
    //     $("#mod-pic").modal("toggle");
    //     var t = $("#mod-pic-attachType").val();
    //     loadPic(t);
    // }
    //查询文件回显
    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>';
                sec += '</div>&nbsp;';
            }
            if (data.attachs.length >0) {
                $("#div" + data.attachType).next().hide();
            }
            $("#div" + data.attachType).html(sec);
            setTimeout(function () {
                $("img.lazy").lazyload({
                    threshold : 200
                });
            }, 200);
        }else{
            showMsg(data.message);
        }
    }
</script>
