<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>

<link rel="stylesheet" href="${contextPath}/static/assets/css/jquery-ui.css"/>
<link rel="stylesheet" href="${contextPath}/static/assets/css/ui.jqgrid.css"/>
<link rel="stylesheet" href="${contextPath}/static/js/contract/ace.fileinput.css"/>

<style>
    #MyDiv{
        position: absolute;
        left: 300px;
        top: 0px;
        display: none;
    }
</style>

<div class="row">
    <div class="col-xs-12">
        <table id="grid-table">
            <select id="yearBill">
                <option value="2019">2019</option>
                <option selected value="2018">2018</option>
                <option value="2017">2017</option>
                <option value="2016">2016</option>
                <option value="2015">2015</option>
            </select>
            &nbsp
            <select id="monthBill">
                <option selected value="12">12</option>
                <option value="11">11</option>
                <option value="10">10</option>
                <option value="9">9</option>
                <option value="8">8</option>
                <option value="7">7</option>
                <option value="6">6</option>
                <option value="5">5</option>
                <option value="4">4</option>
                <option value="3">3</option>
                <option value="2">2</option>
                <option value="1">1</option>
            </select>
            &nbsp;<input id="keyword" class="input-medium search-query" type="text" placeholder="搜索关键字"/>
            <select id="companyName">
                <option selected value="0">选择登录名</option>
            </select>&nbsp;&nbsp;
            <button onclick="search()" type="button" class="btn">搜索</button>&nbsp;&nbsp;
            <button onclick="getFwfCount()" type="button" class="btn btn-primary">计算筛选后的服务费</button>&nbsp;&nbsp;
            <button onclick="getDuiZhang()" type="button" class="btn btn-danger">生成对账单</button>
            <div class="row" style="margin-top: 10px">
                <div class="col-md-7">
                    <div style="float: left; width: 25%">
                        <p>当月服务费</p>
                        <p><span id="addServiceCost">0.00</span>元</p>
                    </div>
                    <div style="float: left; width: 25%">
                        <p>退保扣减服务费</p>
                        <p><span id="reduceServiceCost">0.00</span>元</p>
                    </div>
                    <div style="float: left; width: 25%">
                        <p>当月应付服务费</p>
                        <p><span id="sumServiceCost">0.00</span>元</p>
                    </div>
                    <div style="float: left; width: 25%">
                        <p>当月成交保费</p>
                        <p><span id="dealBf">0.00</span>元</p>
                    </div>
                </div>
            </div>
            <div id="newdiv" style="display: none ;background-color: #d6d6d6">
                <p>筛选后：</p>
                <p><span id="newBf"></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id="newFwf"></span></p>
            </div>
        </table>
        <div id="grid-pager"></div>

        <script type="text/javascript">
            var $path_base = "${contextPath}/static";//in Ace demo this will be used for editurl parameter
        </script>

        <!-- PAGE CONTENT ENDS -->
    </div><!-- /.col -->
    <div id="modal-refund-body" class="modal fade" tabindex="-1" data-backdrop="static">
        <div class="modal-dialog">
            <form id="checkForm">
                <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" style="overflow-y: scroll;">
                        <div id="mod-edit-tip" class="red clearfix"></div>
                        <input type="hidden" id="modal-refund-orderid" value="">
                        <div class="form-group" style="margin-left: 30px;">
                            <label class="control-label">请输入备注：</label>
                        </div>
                        <div class="form-group" style="margin-left: 30px;">
						<textarea id="modal-refund-reason" rows="4" cols="60"
                                  placeholder="请输入备注"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer no-margin-top">
                        <div class="text-center">
                            <button id="mod-check-success" type="button" class="btn btn-sm btn-primary"
                                    onclick="showRefundConfirm();">
                                确定
                            </button>
                            <button class="btn btn-sm" data-dismiss="modal">
                                取消
                            </button>
                        </div>
                    </div>
                </div><!-- /.modal-content -->
            </form>
        </div><!-- /.modal-dialog -->
    </div>
    <div id="modal-refund-remark" class="modal fade" tabindex="-1" data-backdrop="static">
        <div class="modal-dialog">
            <form id="checkForm1">
                <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" style="overflow-y: scroll;" id="serviceCostDiv">

                    </div>
                    <div class="modal-footer no-margin-top">
                        <div class="text-center">
                            <button class="btn btn-sm" data-dismiss="modal">
                                取消
                            </button>
                        </div>
                    </div>
                </div><!-- /.modal-content -->
            </form>
        </div><!-- /.modal-dialog -->
    </div>

    <div id="modal-upload-balance" class="modal fade" tabindex="-1">
        <div class="modal-dialog" style="max-width: 800px;max-height: 660px;overflow-y: scroll;">
            <div class="modal-content">
                <div class="modal-body">
                    <input type="hidden" id="modal-upload-balance-id" value="">
                    <form id="otherForm" class="form-horizontal">
                        <input type="hidden" id="modal-orderid" value="">
                        <div class="form-group" style="margin-left: 30px;">
                            <label class="control-label">上传律师退款截图</label>
                        </div>
                        <div class="form-group" style="margin-left: 30px;">
                            <div class="col-sm-9 text-left">
                                <div id="div-lawyer-refund" class="checkbox-inline"></div>
                                <button class="btn btn-primary btn-white checkbox-inline" type="button"
                                        onclick="uploadPic('lawyer-refund')">上传图片
                                </button>
                            </div>
                        </div>
                        <div class="form-group" style="margin-left: 30px;">
                            <label class="control-label">上传确认退保的聊天记录（和保险公司、律师的聊天记录都要上传）</label>
                        </div>
                        <div class="form-group" style="margin-left: 30px;">
                            <div class="col-sm-9 text-left">
                                <div id="div-lawyer-chat" class="checkbox-inline"></div>
                                <button class="btn btn-primary btn-white checkbox-inline" type="button"
                                        onclick="uploadPic('lawyer-chat')">上传图片
                                </button>
                            </div>
                        </div>
                        <div class="form-group" style="margin-left: 30px;">
                            <label class="control-label">修改记录：</label>
                        </div>
                        <div class="form-group" style="margin-left: 30px;" id="operation-log">
                            <label class="control-label">记录记录记录。。。</label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer no-margin-top">
                    <div class="text-center">
                        <button class="btn btn-sm" data-dismiss="modal">
                            取消
                        </button>
                    </div>
                </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>
<!-- /.row -->

<%--生成对账单--%>
<div  id="MyDiv" class="modal-dialog white_content">
    <div class="modal-content">
        <div class="modal-header no-padding">
            <div class="table-header">
                <button onclick="CloseDiv()" type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    <span  class="white">&times;</span>
                </button>
                生成对账单
            </div>
        </div>
        <div>
            <div>
               <h5> &nbsp;&nbsp;&nbsp;&nbsp;选择条件：</h5>
            </div>
            <br>
            <div>
                &nbsp;
                &nbsp;
                &nbsp;
                &nbsp;
                &nbsp;
                <select id="duiZhangYear">
                    <option value="2020">2020</option>
                    <option selected value="2019">2019</option>
                    <option value="2018">2018</option>
                    <option value="2017">2017</option>
                    <option value="2016">2016</option>
                    <option value="2015">2015</option>
                </select>
                &nbsp;
                &nbsp;
                &nbsp;
                &nbsp;
                &nbsp;
                <select id="duiZhangMonth">
                    <option selected value="12">12</option>
                    <option value="11">11</option>
                    <option value="10">10</option>
                    <option value="9">9</option>
                    <option value="8">8</option>
                    <option value="7">7</option>
                    <option value="6">6</option>
                    <option value="5">5</option>
                    <option value="4">4</option>
                    <option value="3">3</option>
                    <option value="2">2</option>
                    <option value="1">1</option>
                </select>
                &nbsp;
                &nbsp;
                &nbsp;
                &nbsp;
                &nbsp;
                <select id="duiZhangCompanyName">
                    <option selected value="0">选择登录名</option>
                </select>
            </div>
            <br>
            <br>
        </div>
        <div class="modal-footer no-margin-top">
            <div class="text-center">
                <button onclick="exportDuiZhang()" class="btn btn-sm" data-dismiss="modal">
                    导出
                </button>
                <button onclick="CloseDiv()" class="btn btn-sm" data-dismiss="modal">
                    取消
                </button>
            </div>
        </div>
    </div><!-- /.modal-dialog -->
</div>

<script>

    /**
     * 生成文件名
     * @returns
     */
    function timestamp() {
        var time = new Date();
        var y = time.getFullYear();
        var m = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var mm = time.getMinutes();
        var s = time.getSeconds();

        console.log(y);

        return "" + y + add0(m) + add0(d) + add0(h) + add0(mm) + add0(s);
    }

    function add0(m) {
        return m < 10 ? '0' + m : m;
    }

    function search() {
        var keyword = encodeURI($("#keyword").val());
        var startDate =$("#yearBill").val();
        var endDate =$("#monthBill").val();
        var companyId = $("#companyName").val();
        myGrid.setGridParam({postData:{'keyword':keyword,'year':startDate,'month':endDate,'companyId':companyId},url : '${contextPath}/bill/ssdbBill/getBillOrders',page:1}).trigger('reloadGrid');
        $(function () {
            getTotalCost(startDate,endDate);
        });
    }
    function getFwfCount() {
        var newBf = $("#grid-table").getCol('bf',false,'sum');
        var newFwf = $("#grid-table").getCol('serviceCost',false,'sum');
        $("#newBf").html("筛选后的保费：" + (newBf).toFixed(2));
        $("#newFwf").html("筛选后的服务费：" + (newFwf).toFixed(2));
        if( $("#newdiv").css("display")==='none' ){
            $("#newdiv").show();
        }else{
            $("#newdiv").hide();
        }
    }

    function changeDoubleToType(cellvalue) {
        var result = "";
        if (cellvalue != null) {
            result = cellvalue.toFixed(2);
        }
        return result;
    }

    function getTotalCost(startDate, endDate) {
        var keyword =$("#keyword").val();
        var companyId = $("#companyName").val();
        $.ajax({
            dataType : "json",
            url : "${contextPath}/bill/ssdbBill/getTotalCost",
            type : "post",
            data : {'keyword':keyword,'year':startDate,'month':endDate,'companyId':companyId},
            success : function(result) {
                if (result != null) {
                    $("#addServiceCost").html(changeDoubleToType(result.addServiceCost));
                    $("#reduceServiceCost").html(changeDoubleToType(result.reduceServiceCost));
                    $("#sumServiceCost").html(changeDoubleToType(result.sumServiceCost));
                    $("#dealBf").html(changeDoubleToType(result.dealBf));
                    if (result.orderTime) {
                        var time = result.orderTime;
                        var arr = time.split("-");
                        if (arr.length > 2) {
                            $("#yearBill").val(arr[0]);
                            $("#monthBill").val(arr[1]);
                        }
                    }
                }
            }
        });
    }

    $('#update_lawyer_url2').click(function() {
       document.getElementById('picform').reset();
       $('#mod-pic').modal('toggle');
    });


</script>
<!-- page specific plugin scripts -->

<script type="text/javascript">
    var scripts = [null, "${contextPath}/static/assets/js/date-time/bootstrap-datepicker.js",
        "${contextPath}/static/assets/js/date-time/locales/bootstrap-datepicker.zh-CN.js",
        "${contextPath}/static/assets/js/jqGrid/jquery.jqGrid.js",
        "${contextPath}/static/assets/js/jqGrid/i18n/grid.locale-cn.js",
        "${contextPath}/static/js/contract/promise-6.1.0.js",
        "${contextPath}/static/js/contract/ace.fileinput.js",
        "${contextPath}/static/js/contract/uuid.js",
        "${contextPath}/static/js/contract/picupload.js",
        "${contextPath}/static/assets/js/lazyload/jquery.lazyload.js",
        "${contextPath}/static/js/network.js",
        null]
    $('.page-content-area').ace_ajax('loadScripts', scripts, function () {
        // inline scripts related to this page
        jQuery(function ($) {
            var grid_selector = "#grid-table";
            var pager_selector = "#grid-pager";

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

            myGrid=	jQuery(grid_selector).jqGrid({
                subGrid : false,
                url : "${contextPath}/bill/ssdbBill/getBillOrders",
                datatype : "json",
                height : '100%',
                width : 'auto',
                colNames : ['序号','订单时间', '确认付款时间', '订单号', '登录名', '结算机构','省', '市', '法院', '原告', '保全金额','保费','服务费比例','应付服务费','结算情况','备注','操作'],
                colModel : [ {
                    name : 'orderNum',
                    index : 'orderNum',
                    width : 20,
                    editable : false,
                },{
                    name : 'createDate',
                    index : 'createDate',
                    sorttype : 'date',
                    width : 40,
                    editable : false,
                }, {
                    name : 'payedDate',
                    index : 'payedDate',
                    width : 40,
                    editable : false,
                }, {
                    name : 'orderId',
                    index : 'orderId',
                    width : 40,
                    editable : false,
                    sorttype : 'text',
                }, {
                    name : 'loginName',
                    index : 'loginName',
                    width : 25,
                    editable : false,
                }, {
                    name : 'clearingInstitutionName',
                    index : 'clearingInstitutionName',
                    width : 70,
                    editable : false,
                },{
                    name : 'provinceText',
                    index : 'provinceText',
                    width : 20,
                    editable : false,
                }, {
                    name : 'cityText',
                    index : 'cityText',
                    width : 40,
                    editable : false,
                    search : false,
                }, {
                    name : 'courtName',
                    index : 'courtName',
                    width : 60,
                    editable : false,
                    search : false,
                }, {
                    name : 'plaintiff',
                    index : 'plaintiff',
                    width : 25,
                    editable : false,
                    search : false,
                }, {
                    name : 'sqbd',
                    index : 'sqbd',
                    width : 30,
                    editable : false,
                    search : false,
                    formatter:changeDoubleType
                }, {
                    name : 'bf',
                    index : 'bf',
                    width : 30,
                    editable : false,
                    search : false,
                    formatter:chagneDoubleCostStyle
                }, {
                    name : 'serviceCostProportion',
                    index : 'serviceCostProportion',
                    width : 40,
                    editable : false,
                    search : false,
                    formatter:changeProportionType
                },{
                    name : 'serviceCost',
                    index : 'serviceCost',
                    width : 40,
                    editable : false,
                    search : false,
                    formatter:chagneDoubleCostStyle
                },{
                    name : 'settlementType',
                    index : 'settlementType',
                    width : 30,
                    editable : false,
                    search : false,
                    formatter:changeCostStyle
                }, {
                    name : 'remark',
                    index : 'remark',
                    width : 30,
                    editable : false,
                    search : false,
                },{
                    name : 'id',
                    index : '',
                    label : '操作',
                    width : 160,
                    editable : false,
                    search : false,
                    sortable : false,
                    fixed:true,
                    formatter : optionFormatter
                }
                ],
                //scroll : 1, // set the scroll property to 1 to enable paging with scrollbar - virtual loading of records
                sortname : "paytime",
                sortorder : "desc",
                viewrecords : true,
                rowNum : 1000,
                rowList : [ 10, 30, 500,1000,3000 ],
                pager : pager_selector,
                altRows : true,
                multiselect : true,
                multiboxonly : true,
                loadComplete : function() {
                    var table = this;
                    setTimeout(function () {
                        styleCheckbox(table);
                        updateActionIcons(table);
                        updatePagerIcons(table);
                        enableTooltips(table);
                    }, 0);
                },
                editurl: "${contextPath}/ads/order/adsOrderDetails"
            });

            $(window).triggerHandler('resize.jqGrid');// trigger window resize to make the grid get the correct size

            // enable search/filter toolbar
            // jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})
            // jQuery(grid_selector).filterToolbar({});
            // switch element when editing inline
            function aceSwitch(cellvalue, options, cell) {
                setTimeout(function () {
                    $(cell).find('input[type=checkbox]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
                }, 0);
            }

            $("#mod-pic-submit").click(function () {
                applyTokenDo(uploadFile);
            });


            // navButtons
            jQuery(grid_selector).jqGrid('navGrid', pager_selector, { // navbar options
                edit: <shiro:hasPermission name="${ROLE_KEY}:payRecord:edit">true</shiro:hasPermission><shiro:lacksPermission name="${ROLE_KEY}:payRecord:edit">false</shiro:lacksPermission>,
                editicon: 'ace-icon fa fa-pencil blue',
                add: <shiro:hasPermission name="${ROLE_KEY}:payRecord:add">true</shiro:hasPermission><shiro:lacksPermission name="${ROLE_KEY}:payRecord:add">false</shiro:lacksPermission>,
                addicon: 'ace-icon fa fa-plus-circle purple',
                del: <shiro:hasPermission name="${ROLE_KEY}:payRecord:delete">true</shiro:hasPermission><shiro:lacksPermission name="${ROLE_KEY}:payRecord:delete">false</shiro:lacksPermission>,
                delicon: 'ace-icon fa fa-trash-o red',
                search: <shiro:hasPermission name="${ROLE_KEY}:payRecord:search">true</shiro:hasPermission><shiro:lacksPermission name="${ROLE_KEY}:payRecord:search">false</shiro:lacksPermission>,
                searchicon: 'ace-icon fa fa-search orange',
                refresh: true,
                refreshicon: 'ace-icon fa fa-refresh blue',
                view: <shiro:hasPermission name="${ROLE_KEY}:payRecord:view">true</shiro:hasPermission><shiro:lacksPermission name="${ROLE_KEY}:payRecord:view">false</shiro:lacksPermission>,
                viewicon: 'ace-icon fa fa-search-plus grey'
            }, {
                // edit record form
                // closeAfterEdit: true,
                // width: 700,
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_edit_form(form);
                },
                errorTextFormat: function (response) {
                    var result = eval('(' + response.responseText + ')');
                    return result.message;
                }
            }, {
                // new record form
                // width: 700,
                closeAfterAdd: true,
                recreateForm: true,
                viewPagerButtons: false,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_edit_form(form);
                },
                errorTextFormat: function (response) {
                    var result = eval('(' + response.responseText + ')');
                    return result.message;
                }
            }, {
                // delete record form
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    if (form.data('styled'))
                        return false;
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_delete_form(form);
                    form.data('styled', true);
                },
                onClick: function (e) {
                    // alert(1);
                }
            }, {
                // search form
                recreateForm: true,
                afterShowSearch: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                    style_search_form(form);
                },
                afterRedraw: function () {
                    style_search_filters($(this));
                },
                multipleSearch: true
                /**
                 * multipleGroup:true, showQuery: true
                 */
            }, {
                // view record form
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                }
            })

            // add custom button to export the data to excel
            if(<shiro:hasPermission name="${ROLE_KEY}:companyPay:export">true</shiro:hasPermission><shiro:lacksPermission name="${ROLE_KEY}:companyPay:export">false</shiro:lacksPermission>){
                jQuery(grid_selector).jqGrid('navButtonAdd', pager_selector,{
                    caption : "",
                    title : "导出Excel",
                    buttonicon : "ace-icon fa fa-file-excel-o green",
                    onClickButton : function () {
                        var keyword = encodeURI($("#keyword").val());
                        var year =$("#yearBill").val();
                        var month =$("#monthBill").val();
                        var companyId = $("#companyName").val();

                        var page =jQuery(grid_selector).getGridParam('page'); // current page
                        var rows = jQuery(grid_selector).getGridParam('rowNum'); // rows

                        window.open('${contextPath}/bill/ssdbBill/downloadBillOrder?year=' + year + '&month=' + month + '&keyword=' + keyword + '&companyId=' + companyId + '&page=' + page + '&rows=' + rows);
                    }
                });
            }

            function style_edit_form(form) {
                // form.find('input[name=statusCn]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
                // don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
                // .addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');

                // update buttons classes
                var buttons = form.next().find('.EditButton .fm-button');
                buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();// ui-icon, s-icon
                buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
                buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')

                buttons = form.next().find('.navButton a');
                buttons.find('.ui-icon').hide();
                buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
                buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
            }

            function style_delete_form(form) {
                var buttons = form.next().find('.EditButton .fm-button');
                buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();// ui-icon, s-icon
                buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
                buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
            }

            function style_search_filters(form) {
                form.find('.delete-rule').val('X');
                form.find('.add-rule').addClass('btn btn-xs btn-primary');
                form.find('.add-group').addClass('btn btn-xs btn-success');
                form.find('.delete-group').addClass('btn btn-xs btn-danger');
            }
            function style_search_form(form) {
                var dialog = form.closest('.ui-jqdialog');
                var buttons = dialog.find('.EditTable')
                buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
                buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
                buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
            }

            function beforeDeleteCallback(e) {
                var form = $(e[0]);
                if (form.data('styled'))
                    return false;
                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                style_delete_form(form);
                form.data('styled', true);
            }

            function beforeEditCallback(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                style_edit_form(form);
            }

            // it causes some flicker when reloading or navigating grid
            // it may be possible to have some custom formatter to do this as the grid is being created to prevent this
            // or go back to default browser checkbox styles for the grid
            function styleCheckbox(table) {
                /**
                 * $(table).find('input:checkbox').addClass('ace') .wrap('<label />') .after('<span class="lbl align-top" />') $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
                 * .find('input.cbox[type=checkbox]').addClass('ace') .wrap('<label />').after('<span class="lbl align-top" />');
                 */
            }

            // unlike navButtons icons, action icons in rows seem to be hard-coded
            // you can change them like this in here if you want
            function updateActionIcons(table) {
                /**
                 * var replacement = { 'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue', 'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red', 'ui-icon-disk' : 'ace-icon fa fa-check green', 'ui-icon-cancel' :
        			 * 'ace-icon fa fa-times red' }; $(table).find('.ui-pg-div span.ui-icon').each(function(){ var icon = $(this); var $class = $.trim(icon.attr('class').replace('ui-icon', '')); if($class in replacement)
        			 * icon.attr('class', 'ui-icon '+replacement[$class]); })
                 */
            }

            // replace icons with FontAwesome icons like above
            function updatePagerIcons(table) {
                var replacement = {
                    'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                    'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                    'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                    'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
                };
                $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                    var icon = $(this);
                    var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                    if ($class in replacement)
                        icon.attr('class', 'ui-icon ' + replacement[$class]);
                })
            }

            function enableTooltips(table) {
                $('.navtable .ui-pg-button').tooltip({
                    container: 'body'
                });
                $(table).find('.ui-pg-div').tooltip({
                    container: 'body'
                });
            }

            function changeProportionType(cellvalue, options, rowObject) {
                var result = null;
                result = '<span>' + cellvalue + '</span><a style="margin-left: 2px" href="javaScript:void(0)" onclick="showProtocol(' + rowObject.orderId + ')"><img src="${contextPath}/static/img/question.jpg" style="width: 16px; height: 16px;"></a>'

                return result;
            }

            function changeDoubleType(cellvalue, options, rowObject) {
                var result = "";
                if (cellvalue != null) {
                    result = cellvalue.toFixed(2);
                }
                return result;
            }

            function chagneDoubleCostStyle(cellvalue, options, rowObject) {
                var result = "";
                if (cellvalue != null) {
                    result = cellvalue.toFixed(2);
                }
                //退保
                if (rowObject.signB) {
                    result = '<span style="color: #DC143C">'+result+'</span>'
                } else {
                    result = result ;
                }

                return result;
            }
            //根据是否退保改变样式
            function changeCostStyle(cellvalue, options, rowObject) {
                var result = null ;

                //退保
                if (rowObject.signB) {
                    result = '<span style="color: #DC143C">'+cellvalue+'</span>'
                } else {
                    result = cellvalue ;
                }
                return result;
            }

            function optionFormatter(cellvalue, options, cell) {
                var template = "<button data-toggle='modal' onclick='showRemark(\""+cell.orderId+"\",\"" + cell.remark +"\")' class='btn btn-minier btn-yellow'><i class='ace-icon fa fa-hdd-o '></i>添加备注</button>";

                if (cell.orderState == 51) {
                    template += "&nbsp;|&nbsp;<button data-toggle='modal' onclick='showChangeInfo(\""+cell.orderId+"\")' class='btn btn-minier btn-yellow'><i class='ace-icon fa fa-hdd-o '></i>修改</button>";
                }

                return template;
            }
            // var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

            $(document).one('ajaxloadstart.page', function(e) {
                $(grid_selector).jqGrid('GridUnload');
                $('.ui-jqdialog').remove();
            });

            $('#startDate').datepicker({
                language: 'zh-CN',
                pickTime: false,
                todayBtn: true,
                autoclose: true,
                minView: '2',
                forceParse: false,
                format:"yyyy-mm-dd"
            });
            $('#endDate').datepicker({
                language: 'zh-CN',
                pickTime: false,
                todayBtn: true,
                autoclose: true,
                minView: '2',
                forceParse: false,
                format: "yyyy-mm-dd"
            });
        });
    });


    function getFileType(fileName) {
        var ldot = fileName.lastIndexOf('.')
        if (ldot >= 0)
            return fileName.substring(ldot + 1);
        else
            return "";
    }

    function showRefundConfirm() {
        var reason = $("#modal-refund-reason").val();
        var id = $("#modal-refund-orderid").val();
        $.ajax({
            dataType : "json",
            url : "${contextPath}/sys/ssdbOrder/saveBillRemark",
            type : "post",
            data : {
                'orderId' : id,
                'remark' : reason
            },
            success : function(ret) {
                $("#modal-refund-body").modal("toggle");
                if(ret.success == true){
                    alert("修改成功！");
                    jQuery("#grid-table").trigger("reloadGrid");
                }else {
                    alert("修改失败！");
                }
            }
        });
    }


    function showRemark(id,remark) {
        console.log("添加备注");
        $("#modal-refund-reason").val(remark);
        $("#modal-refund-orderid").val(id);
        $("#modal-refund-body").modal("toggle");
    }

    function showChangeInfo(id) {
        $("#modal-upload-balance-id").val(id);
        $("#modal-upload-balance").modal("toggle");
        $('#div-' + 'lawyer-refund').html('');
        $('#div-' + 'lawyer-chat').html('');
        loadPic('lawyer-refund', id);
        loadPic('lawyer-chat', id);
        showChangeLog(id)
    }

    function showProtocol(orderId) {
        $("#modal-refund-remark").modal("toggle");
        $.ajax({
            dataType: "json",
            url: "${contextPath}/bill/ssdbBill/getProtocolInfo",
            type: "post",
            data: {"orderId": orderId},
            success: function (result) {
                console.log(result);
                if (result.success) {
                    var html = "";
                    var data = result.data ;
                    html = '<div class="form-group" style="margin-left: 30px;">\n' +
                        '                            <label class="control-label">服务费计算规则：</label>\n' +
                        '                        </div>\n' +
                        '                        <div class="form-group" style="margin-left: 30px;">\n' +
                        '                            <label class="control-label">服务费比例：'+data.serviceCostProportion+'%</label>\n' +
                        '                        </div>\n' +
                        '                        <div class="form-group" style="margin-left: 30px;">\n' +
                        '                            <label class="control-label">服务费修改记录：</label>\n' +
                        '                        </div>\n' +
                        '                        <div class="form-group" style="margin-left: 30px;">\n' +
                        '                            <label class="control-label" id="changeRemark">'+data.changeRemark+'</label>\n' +
                        '                        </div>\n' +
                        '                        <div class="form-group" style="margin-left: 30px;">\n' +
                        '                            <label class="control-label">服务费修改原因：</label>\n' +
                        '                        </div>\n' +
                        '                        <div class="form-group" style="margin-left: 30px;">\n' +
                        '                            <label class="control-label" id="changeReason">'+data.changeReason+'</label>\n' +
                        '                        </div>\n' +
                        '                        <div class="form-group" style="margin-left: 30px;">\n' +
                        '                            <label class="control-label">服务费修改依据：</label>\n' +
                        '                        </div>\n';

                    var urls = data.urls;
                    var urlhtml = ' <div class="form-group" style="margin-left: 30px;">';
                    for (var i = 0; i < urls.length; i++) {
                        urlhtml += '<img src="' + urls[i] + '"/>';
                    }
                    urlhtml += '</div>';
                    html += urlhtml;
                    $("#serviceCostDiv").html(html);
                }
            }
        });
    }

    function getAllCompanys() {
        $.ajax({
            dataType : "json",
            url : "${contextPath}/sys/company/getAllCompany",
            type : "post",
            data : {},
            success : function(result) {
                var html = '<option selected value="0">全部</option>';
                var html2 = '<option selected value="0">请选择登录名</option>';
                if (result.success) {
                    var data = result.data;
                    for(var i = 0 ; i < data.length; i ++) {
                        html += '<option selected value='+data[i].id+'>'+data[i].name+'</option>'
                        html2 += '<option selected value='+data[i].id+'>'+data[i].name+'</option>'
                    }
                    $("#companyName").html(html);
                    $("#companyName").val(0);
                    $("#duiZhangCompanyName").html(html2);
                    $("#duiZhangCompanyName").val(0);


                }
            }
        });
    }

    $(function () {
        getAllCompanys();
        getTotalCost(0,0);
    });

    function showChangeLog(id) {
        $.ajax({
            dataType: "json",
            url: "${contextPath}/bill/ssdbBill/extractFileAttachLog",
            type: "post",
            data: {'orderId': id},
            success: function (result) {
                console.debug(result);
                if (result.success) {
                    var data = result.data;
                    html = ""
                    for (var i = 0; i < data.length; i++) {
                        attach_type = data[i][3]
                        if (attach_type == "lawyer-refund") {
                            attach_type = "退款截图"
                        } else if (attach_type == "lawyer-chat") {
                            attach_type = "聊天记录"
                        }
                        item = '<p>' +
                            '<span>[附件类型]' + attach_type + '</span>&nbsp;&nbsp;' +
                            '<span>[操作类型]' + data[i][2] + '</span>&nbsp;&nbsp;' +
                            '<span>[操作时间]' + format_Date(data[i][0]) + '</span>&nbsp;&nbsp;' +
                            '<span>[操作员]' + data[i][1] + '</span>&nbsp;&nbsp;' +
                            '</p>'
                        html += item
                    }
                    $("#operation-log").html(html);
                }
            }
        });
    };

    function formatDate(d) {
        var result = "";
        if (d > 9) {
            result = d.toString();
        } else {
            result = '0' + d.toString();
        }
        return result;
    }

    function format_Date(cellvalue) {
        var result = "";
        if (cellvalue != null) {
            var d = new Date(cellvalue);
            result = d.getFullYear() + '-' + formatDate(d.getMonth() + 1) + "-" + formatDate(d.getDate()) + ' ' + formatDate(d.getHours()) + ":" + formatDate(d.getMinutes()) + ":" + formatDate(d.getSeconds());
        }
        return result;
    }

    //-------------------------上传文件-----开始---------------------
    function uploadPic(attachType) {
        $("#mod-pic").modal("toggle");
        $("#mod-pic-attachType").val(attachType);
        $("#mod-pic-orderId").val($("#modal-upload-balance-id").val());
    }

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

    var appServer = 'http://b.duowenlvshi.com/oss/token?name=ssdb';
    var bucket = '${oss_bucket_ssdb}';
    var region = 'oss-cn-shenzhen';
    var applyTokenDo = function (func) {
            var url = appServer;
            $.ajax({
                type: "POST",
                url: url,
                data: "",
                dataType: "jsonp",
                success: function (e) {
                    var client = new OSS.Wrapper({
                        region: region,
                        accessKeyId: e.AccessKeyId,
                        accessKeySecret: e.AccessKeySecret,
                        stsToken: e.SecurityToken,
                        bucket: bucket
                    });
                    return func(client);
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }
    ;
    var uploadFile = function (client) {
            var picFile = document.getElementById('picFileId').files[0];
            var orderId = document.getElementById('mod-pic-orderId').value;
            var fileName = UUIDjs.create().hex;
            var fileType = getFileType(picFile.name);
            var key = "ssdb/finance/balance/" + orderId + "/" + fileName + "." + fileType;
            return client.multipartUpload(key, picFile, {
                progress: progress
            }).then(function (res) {
                saveToDB(orderId, key, fileName, fileType);
            });
        }
    ;

    function getFileType(fileName) {
        var ldot = fileName.lastIndexOf('.')
        if (ldot >= 0)
            return fileName.substring(ldot + 1);
        else
            return "";
    }

    function saveToDB(orderId, key, fileName, fileType) {
        var attachType = $("#mod-pic-attachType").val();
        var parameters = {
            "orderId": orderId,
            "attachType": attachType,
            "path": key,
            "fileName": fileName,
            "fileType": fileType
        };
        console.debug(parameters);
        $.getJSON('${contextPath}/bill/ssdbBill/uploadFileAttach', parameters, function (result) {
            if (result.success) {
                uploadSuccess(orderId);
                showChangeInfo(orderId)
            } else {
                alert(result.message);
            }
        });
    };

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

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

    function loadPic(attachType, orderId) {
        var url = '${contextPath}/bill/ssdbBill/extractFileAttach';
        var parameters = {"orderId": orderId, "attachType": attachType};
        postData(url, parameters, loadPiCallback, errorCallbackDefault);
    }

    //向后台请求数据
    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 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];
                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 + '" height="100" width="100" id="' + v.id + '"/>';
                sec += '</a><br/><a href="javascript:void(0)" onclick="deletePic(\'' + v.id + '\')">删除</a>';
                sec += '</div>&nbsp;';
            }
            $("#div-" + data.attachType).html(sec);
            setTimeout(function () {
                $("img.lazy").lazyload({
                    threshold: 200
                });
            }, 200);
        } else {
            showMsg(data.message);
        }
    }

    //删除图片
    function deletePic(id) {
        $('#picDiv' + id).hide();
        var url = '${contextPath}/bill/ssdbBill/deleteFileAttach';
        var parameters = {"id": id};
        postData(url, parameters, deletePiCallback, errorCallbackDefault);
    }

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

    function errorCallbackDefault(data) {
        console.debug("=*= eroro=*= " + data)
        ///donoting....
    }

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

    //-------------------------上传文件----结束----------------------

    /*-------------------------导出对账单---start-------------------*/
    function CloseDiv() {
        $("#MyDiv").hide();
    }
    function getDuiZhang() {
        $("#MyDiv").show();
    }
    function exportDuiZhang() {
        var year = $("#duiZhangYear").val();
        var month = $("#duiZhangMonth").val();
        var companyId = $("#duiZhangCompanyName").val();
        var url = '${contextPath}/bill/ssdbBill/downloadDuiZhang?year=' + year +
            "&month="+month + "&companyId="+companyId ;
        console.info(url);
        window.open(url);
    }

</script>
