<%@ 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(10,'');
//左边菜单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><strong><a>开通微信通知</a></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">
                    <label for="name">登录名：</label>
                    <div class="input-group">
                        <input type="text" id="name" class="form-control"/>
                    </div>
                    <br/>
                    <label for="role">角色：</label>
                    <div class="input-group">
                        <select class="select" id="role">
                            <option value="">请选择</option>
                            <option value="3">保险公司跟单人员</option>
                            <option value="4">保险公司管理员</option>
                        </select>
                    </div>
                    <br/>
                    <label for="phone">联系电话：</label>
                    <div class="input-group">
                        <input type="text" id="phone" class="form-control"/>
                    </div>
                    <div class="modal-footer no-margin-top">
                        <div class="text-center">
                            <button onclick="addWechat()" id="mod-add-submit" type="button" class="btn btn-sm btn-primary">
                                <i class="ace-icon fa fa-floppy-o bigger-160"></i>
                                生成二维码
                            </button>
                        </div>
                    </div>
                    <img class="lazy" id="img"  style="width: 150px;height: 150px;display: none">
                </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-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>
                                    <div style="display: none" id="div_templateId">
                                        <input type="file" id="templateId" name="avatar" multiple>
                                    </div>
                                    <div style="text-align: center ;display:none" id="templateId_pic">
                                        <input type="hidden" id="templateId_pic_hidden_id" value="">
                                        <img src="" style="width: 119px;height: 111px" id="templateId_pic_img">
                                    </div>
                                    <div style="text-align: center ;display:none" id="templateId_del">
                                        <a href="javascript:void(0)" onclick="deletePic()">删除</a>
                                    </div>
                                </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="fileUpload();">上传</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/company/companyuseradd.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"/>

<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">
    var accountsObject = {};
    //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 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/"+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();
        if (imgeType != "bmp" && imgeType != "jpg" && imgeType != "jpeg" && imgeType != "png" && imgeType != "gif" && imgeType != "bmp"
            && imgeType != "pcx" && imgeType != "tiff" && imgeType != "tga" && imgeType != "exif" && imgeType != "fpx" && imgeType != "svg" && imgeType != "psd") {
            showMsg( '保函模板必须为图片，请重新上传');
            return;
        }

        saveToDB(orderId,keyArray,keyArrayTemplate,fileNameArray,fileNameArrayTemplate,fileTypeArray,fileTypeArrayTemplate,accountBank,accountName,accountNum);
    };

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

    function addWechat(){
        var name = $("#name").val();
        var role = $("#role").val();
        var phone = $("#phone").val();
        if(!name || !role ||!phone){
            alert("请完善信息");
            return;
        }
        $.ajax({
            dataType : "json",
            url : "${contextPath}/companyUser/getWeChatImage",
            type : "post",
            data : {
                'name' : name,
                'phone': phone,
                'type' : role
            },
            complete : function(ret) {
                debugger;
                var ret = eval("(" + ret.responseText + ")");
                if(ret.success){
                    $("#img").attr("src",""+ret.qrCodeUrl+"");
                    $("#img").show();
                }else{
                    alert(ret.message);
                }

            }
        });

    }

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

        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-reviewFail-submit').on('click', function() {
            reviewFailSubmit();
        });
        $('#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 ;
            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.success){
            var divObj = $('#gridTable1ReviewDetail');
            var html = '<div class="row">'
                + '<div class="col-md-2"><strong>订单号</strong></div>'
                + '<div class="col-md-3"><strong>受理法院</strong></div>'
                + '<div class="col-md-1"><strong>保全金额</strong>（元）</div>'
                + '<div class="col-md-1"><strong>保费</strong>（元）</div>'
                + '<div class="col-md-2"><strong>提交时间</strong></div>'
                + '<div class="col-md-2"><strong>承诺审核时间</strong></div>'
                + '</div>';
            var o = data.order;
            html += '<div class="row">'
                + '<div class="col-md-2">' + formatString(o.orderId) + '</div>'
                + '<div class="col-md-3">' + formatString(o.courtName) + '</div>'
                + '<div class="col-md-1">' + formatString(o.sqbd) + '</div>'
                + '<div class="col-md-1">' + formatString(o.bf) + '</div>'
                + '<div class="col-md-2">' + formatString(o.createDate) + '</div>'
                + '<div class="col-md-2">' + formatString(o.lcDate) + '</div>'
                + '</div>'
                + '<div class="hr-line-dashed"></div>';
            var a = data.attachs;
            var row = null;
            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">'
                + '<label class="col-sm-2">获取审核资料:</label>'
                + '<div class="col-sm-8 text-center no-padding">'
                + 	'<button class="btn btn-primary" type="button" onClick="downExamineData()" style="margin-right: 30px;">下载资料</button>'
                + 	'<button class="btn btn-primary" type="button" onClick="showEmailComfig()">邮件发送资料</button>'
                + '</div>'
                + '<div class="col-sm-2 text-center no-padding">'
                + '</div>'
                + '</div>'
                + '<div class="hr-line-dashed"></div>';

            html += '<div class="row">'
                + '<div class="col-md-4"></div>'
                + '<div class="col-md-1 text-center">'
                + '<button class="btn btn-default" type="button" onClick="reviewFailPageShow()">审核失败</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-primary" type="button" onClick="reviewPassSubmit()">审核通过</button>'
                + '</div>'
                + '<div class="col-md-4"></div>'
                + '</div>';
            html += '<div class="hr-line-dashed"></div>';
            html +=  '<div class="row"><div class="col-sm-12 text-left"><h5>律师反馈</h5></div></div>';
            for(var m in data.logReplys){
                row = data.logReplys[m];
                html += '<div class="row">'
                    + '<label class="col-sm-2 control-label">' + row.createDate + '</label>'
                    + '<label class="col-sm-10 control-label text-right">' + row.content + '</label>'
                    + '</div>';
            }
            html += '<div class="hr-line-dashed"></div>';
            html += '<div class="row">'
                + '<label class="col-sm-2">反馈信息:</label>'
                + '<div class="col-sm-8 text-left no-padding">'
                + 	'<input type="text" id="gridTable1Review-companyFeedback" class="form-control" />'
                + '</div>'
                + '<div class="col-sm-2 text-center no-padding">';
            if (data.lawyerBack) {
                html += '<button class="btn btn-primary" type="button" onClick="saveCompanyFeedback()" >发送</button>';
            } else {
                html += '<button class="btn btn-default" type="button" onClick="saveCompanyFeedback()" >发送</button>';
            }
            html +=  '</div>'
                + '</div>';
            divObj.html(html);

            setTimeout(function () {
                $("img.lazy").lazyload({
                    threshold : 200
                });
            }, 200);
        }else{
            showMsg(data.message);
        }
    }

    //文件上传处理
    function fileUpload() {
        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 formatString(str){
        var result = '';
        if(str != undefined && str != null){
            result = str;
        }
        return result;
    }

    function initGridTable(){
        gridTable1 = jQuery(grid_selector).jqGrid({
            subGrid : false,
            url : "${contextPath}/companyUser/getStatistics",//
            datatype : "json",
            height : "auto",
            autowidth:true,
            colModel : [{
                name : "userName",
                index : "userName",
                label : "跟单人员",
                width : 120,
                search : false
            },{
                name : "orderCount",
                index : "orderCount",
                label : "提交订单数",
                width : 80,
                search : false
            },{
                name : "paymentOrder",
                index : "paymentOrder",
                label : "付款订单数",
                width : 80,
                search : false
            },{
                name : "turnoverOrder",
                index : "turnoverOrder",
                label : "订单成交率",
                width : 80,
                search : false,
                formatter:turnoverOrder
            },{
                name : "price",
                index : "price",
                label : "提交保费",
                width : 60,
                sortable: false,
                search : false,
                formatter:ToDouble
            },{
                name : "paymentPrice",
                index : "paymentPrice",
                label : "付款保费",
                width : 50,
                search : false,
                formatter:ToDouble
            },{
                name : "turnoverPrice",
                index : "turnoverPrice",
                label : "保费成交率",
                width : 50,
                search : false,
                formatter:turnoverOrder
            },{
                name : "auditTimeout",
                index : "auditTimeout",
                label : "首次审核超时单数",
                width : 50,
                search : false
            },{
                name : "turnoverAudit",
                index : "turnoverAudit",
                label : "首次审核时效达标率",
                width : 50,
                search : false,
                formatter:turnoverAudit
            },{
                name : "successOrder",
                index : "successOrder",
                label : "审核通过单数",
                width : 50,
                search : false
            },{
                name : "turnoverSuccess",
                index : "turnoverSuccess",
                label : "审核通过率",
                width : 50,
                search : false,
                formatter:turnoverAudit
            },{
                name : "timeoutOrder",
                index : "timeoutOrder",
                label : "出函超时单数",
                width : 50,
                search : false
            },{
                name : "turnoverTimeoutOrder",
                index : "turnoverTimeoutOrder",
                label : "出函时效达标率",
                width : 50,
                search : false,
                formatter:turnoverAudit
            }],
            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 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 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="company('+rowObject.id+')">设置负责公司</a>';
        result += '&nbsp;|&nbsp;<a href="javascript:void(0);" style="color:blue" onclick="deleteByUserId('+rowObject.id+')">删除账号</a>';
        return result;
    }
    //订单成交率
    function turnoverOrder(cellvalue, options, rowObject){
        var result =keepTwoDecimalFull(cellvalue) +"%";
        if(cellvalue < 80){
            cellvalue =keepTwoDecimalFull(cellvalue) +"%";
            result = '<sapn style="color:red">'+cellvalue+'</sapn>';
        }
        return result;
    }
    //订单成交率
    function turnoverAudit(cellvalue, options, rowObject){
        var result =keepTwoDecimalFull(cellvalue) +"%";
        if(cellvalue < 90){
            cellvalue =keepTwoDecimalFull(cellvalue) +"%";
            result = '<sapn style="color:red">'+cellvalue+'</sapn>';
        }
        return result;
    }


    function ToDouble(cellvalue, options, rowObject){
        return keepTwoDecimalFull(cellvalue);
    }

    function deleteByUserId(userId){
        if(confirm("确定要删除该用户吗")){
            $.ajax({
                dataType : "json",
                url : "${contextPath}/companyUser/deleteByUserId",
                type : "post",
                data : {'userId':userId},
                success : function(result) {
                    if(result.success){
                        alert("操作成功!");
                        reloadGrid();
                    }else
                        alert(result.message);
                }
            });
        }

    }

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

    //保存反馈给律师信息成功后回调
    function replyLawyerCallback(data){
        notSubmitReplyLawyer = true;
        if(data.success){
            $("#modal-replyLawyer").modal('toggle');
            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 reviewFailCallback(data){
        notSubmitReviewFail = true;
        if(data.success){
            $("#modal-reviewFail").modal('toggle');
            showMsg('保存成功');
            reloadGrid();
            reviewPageHide();
        }else{
            showMsg(data.message);
        }
    }

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

    //打开审核失败页面
    function reviewFailPageShow(){
        var result = confirm("确认结束该订单吗？");
        if(result == true){
            notSubmitReviewFail = true;
            $("#modal-reviewFail").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 reviewPassCallback(data){
        notSubmitReviewPass = true;
        if(data.success){
            gridTable1.trigger('reloadGrid');
            showMsg('保存成功,请上传需客户签名的投保单');
            uploadFileShow(74,70,currentOrderId);
            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('提交中，请稍候');
        }
    }

    $("#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");
                    }else {
                        alert(ret.message);
                    }
                }
            });
        }
    });

    //下载审核资料
    function downExamineData() {
        window.open('${contextPath}/order/downloadOrderAttachsByType?id=' + currentOrderId + '&key=31');
    }

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

    function reviewOperation(id){
        companyMaterialObj = {};
        currentOrderId = id;
        reviewPageShow();
        notSubmitReviewPass = true;
        var url = '${contextPath}/order/getOrderDetail';
        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 reason = $('#gridTable1Review-companyFeedback').val();
        if(reason.length < 1){
            showMsg('反馈信息不能为空');
        }else{
            var url = '${contextPath}/order/saveCompanyFeedback';
            var parameters = {"reason":reason,"orderId":currentOrderId};
            postData(url, parameters, saveCompanyFeedbackCallback, errorCallbackDefault);
        }
    }

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

    //保存图片路径到数据库
    function saveToDB(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 search(){
        var createStartDate =$("#startDate").val();
        var createEndDate =$("#endDate").val();
        var startingPremium =$("#startingPremium").val();
        var endPremium =$("#endPremium").val();

        gridTable1.setGridParam({postData:{'createStartDate':createStartDate,'createEndDate':createEndDate,'startingPremium':startingPremium,'endPremium':endPremium},url : '${contextPath}/companyUser/getStatistics',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 uploadFileSuccess(){
        $("#mod-file").modal("toggle");
    }

    function formShow(){
        document.getElementById("fileform").reset();
    }

    //四舍五入保留2位小数（不够位数，则用0替补）
    function keepTwoDecimalFull(num) {
        var result = parseFloat(num);
        if (isNaN(result)) {
            return 0;
        }
        result = Math.round(num * 100) / 100;
        var s_x = result.toString();
        var pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
            pos_decimal = s_x.length;
            s_x += '.';
        }
        while (s_x.length <= pos_decimal + 2) {
            s_x += '0';
        }
        return s_x;
    }
</script>
