<%@ 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(7,3);//左边菜单active</script>
<div class="row white-bg border-bottom white-bg page-heading">
    <div class="col-lg-12">
        <h2>保单信息</h2>
        <ol class="breadcrumb">
            <li>主页</li>
            <li><a>对账模块</a></li>
            <li class="active"><strong>开票</strong></li>
        </ol>
    </div>
</div>

<div class="wrapper wrapper-content">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="row">
                        <div class="col-sm-1">
                            <select class="form-control" 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>
                        </div>
                        <div class="col-sm-3">
                            <button type="button" class="btn btn-sm btn-primary" onclick="search()"> 查询</button></div>
                    </div>
                </div>
                <div class="row" style="margin-top: 10px">
                    <div class="col-md-12 jqGrid_wrapper">
                        <table id="gridTable2"></table>
                        <div id="gridPager2"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<div id="modal-company-protocol" class="modal fade" tabindex="-1">
    <div class="modal-dialog" style="max-width: 600px;">
        <div class="modal-content">
            <div class="modal-header">
                <div class="table-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        <span class="white">&times;</span>
                    </button>
                    协议约定回款时间
                </div>
            </div>
            <div class="modal-body">
                <form id="viewForm" class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-3 control-label">查看合作协议</label>
                    </div>
                    <div class="form-group">
                        <a href="" target="_blank" id="protocol_href"><img src="" class="img-thumbnail" style="height: 84px;width: 84px;margin-left: 20px" id="protocol_img"></a>
                    </div>
                </form>
            </div>
            <div class="text-center" style="padding-bottom: 10px;">
                <button class="btn " data-dismiss="modal"><i class="fa fa-share bigger-160"></i>取消</button>
            </div>
        </div>
    </div>
</div>

<div id="modal-orderAttachs"   class="modal fade" tabindex="-1" style="z-index: 9999 !important;"
     data-backdrop="static">
    <div class="modal-dialog" style="min-width: 650px;">
        <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" id="modal-orderAttachs-body"></div>
        </div>
    </div>
</div>

<div id="modal-company-explain" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <form  class="form-horizontal">
                    <div class="form-group text-center">
                        <label class="col-sm-10 control-label">逾期回款将产生违约金。每逾期1天，按未回金额的千分5收取违约金。</label>
                    </div>
                </form>
            </div>
            <div class="text-center" style="padding-bottom: 10px;">
                <button class="btn btn-primary" data-dismiss="modal">我知道了</button>
            </div>
        </div>
    </div>
</div>

<div id="mod-file-apply" 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">
                            <input type="hidden" id="orderTime" value="">
                            <input type="hidden" id="notInvoice1" value="">
                            <input type="hidden" id="sumServiceCost1" value="">
                            <div class="col-xs-12">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">开票类型</label>
                                <select class="col-sm-10 " id="invoType">
                                    <option value="0">增值税普通发票</option>
                                    <option selected value="1">增值税专用发票</option>
                                    <option value="2">增值税电子普通发票</option>
                                </select>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px;position:relative">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">发票抬头</label>
                                <select class="col-sm-10 " id="qlc_zdz1" >
                                </select>
                                <div class="col-sm-2  no-padding" style="position:absolute;">
                                </div>
                                <div class="col-sm-10  no-padding" style="position:absolute;">
                                    <input type="text" id="qlc_zdz" style="width: 88% ;height: 15px;border:0;margin-left: 19%;">
                                </div>
                            </div>

                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">纳税人识别号</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="taxNum" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">公司地址</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="companyAddress" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">电话</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="phone" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">银行开户名</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="bankName" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">银行账号</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="bankAccount" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">开户行</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="bank" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">开票金额</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="money" style="width: 100%">
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-5no-padding" style="margin-top: 5px">发票配送信息</label>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">收件地址</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="address" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">电子发票邮箱地址</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="mailAddr" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">收件人</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="receiver" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-2 no-padding" style="margin-top: 5px">收件人电话</label>
                                <div class="col-sm-10  no-padding">
                                    <input type="text" id="receiverPhone" style="width: 100%">
                                </div>
                            </div>
                            <div class="col-xs-12" style="margin-top: 10px">
                                <label class="col-sm-6 no-padding" style="margin-top: 5px"><input name="Fruit" type="checkbox" value="" checked="checked" id="checkData"/>自动保存开票信息</label>
                            </div>


                            <div class="text-center">
                                <button type="button" class="btn btn-sm btn-primary" onclick="applyTickets();">确认</button>
                                <button type="button" class="btn btn-sm" data-dismiss="modal">取消</button>
                            </div>
                        </form>
                    </div><!-- /.col -->
                </div><!-- /.row -->

            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>

<div id="mod-file-applyhis" class="modal fade" tabindex="-1" style="z-index: 1;position:absolute;">
    <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" id = "allticketHis">
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>



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

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

<link href="${contextPath}/static/css/plugins/jQueryUI/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="${contextPath}/static/css/jquery.editable-select.css"/>
<link href="${contextPath}/static/css/plugins/jqGrid/ui.jqgrid.css" rel="stylesheet">
<link rel="stylesheet" href="${contextPath}/static/ssdb/ace.fileinput.css"/>

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

<!-- 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>
    $("#qlc_zdz1").change(function(){
        var name = $("#qlc_zdz1").val() ;
        $("#qlc_zdz").val(name);
        $.ajax({
            type : "POST",
            url : "${contextPath}/company/getTicketHis",
            data : {"name":name},
            dataType : "json",
            success : function(result) {
                if (result.companyInvoice != null) {
                    var companyInvoice = result.companyInvoice;
                    $("#invoType").val(companyInvoice.invoType);
                    $("#qlc_zdz").val(companyInvoice.name);
                    $("#taxNum").val(companyInvoice.taxNum);

                    $("#companyAddress").val(companyInvoice.companyAddress);
                    $("#phone").val(companyInvoice.phone);
                    $("#bankName").val(companyInvoice.bankName);
                    $("#bankAccount").val(companyInvoice.bankAccount);
                    $("#bank").val(companyInvoice.bank);
                    $("#money").val(companyInvoice.money);
                    $("#address").val(companyInvoice.address);
                    $("#receiver").val(companyInvoice.receiver);
                    $("#receiverPhone").val(companyInvoice.receiverPhone);

                    var list = result.ticketName;
                    var ticketHtml = "";
                    $("#qlc_zdz1").empty();
                    $("#qlc_zdz1").append("<option value=请选择 >请选择</option>");
                    for (var i = 0; i < list.length; i++) {
                        var temp = list[i];
                        ticketHtml += '<option value =' + temp + '>' + temp + '</option>';
                    }
                    $("#qlc_zdz1").append(ticketHtml);
                }
            }
        });
    });
</script>

<script type="text/javascript">
    var accountsObject = {};

    var currentOrderId = null;
    var gridTable1 = null;
    var grid_selector = "#gridTable2";
    var notSubmitReviewPayFail = true;
    var notSubmitReviewPayPass = true;
    var pager_selector = "#gridPager2";
    jQuery(function($) {
        $('#payDate').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true,
            format: "yyyy-mm-dd"
        });
        initGridTable();
        // resize to fit page size
        $(window).on("resize.jqGrid", function() {
            $(grid_selector).jqGrid("setGridWidth", $(".page-content").width());
        });
        // resize on sidebar collapse/expand
        var parent_column = $(grid_selector).closest("[class*='col-']");
        $(document).on("settings.ace.jqGrid", function(ev, event_name, collapsed) {
            if (event_name === "sidebar_collapsed" || event_name === "main_container_fixed") {
                // setTimeout is for webkit only to give time for DOM changes and then redraw!!!
                setTimeout(function() {
                    $(grid_selector).jqGrid("setGridWidth", parent_column.width());
                }, 0);
            }
        });

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

        $('#mod-reviewPay-fail-submit').on('click', function() {
            reviewPayFailSubmit();
        });

        $('#mod-reviewPay-submit').on('click', function() {
            var sysBf = $("#mod-file-bf").val();
            var inputBf = $("#input-bf").val();
            if (inputBf == "") {
                alert("请输入付款保费");
                return;
            } else {
                var sysBfFoult = parseFloat(sysBf);
                var inputBfFoult = parseFloat(inputBf);
                if (sysBfFoult != inputBfFoult) {
                    alert("付款保费和平台保费不一致，请联系多问客服人员确认！");
                    return;
                }
            }
            reviewPayPassSubmit();
        });

        // Add responsive to jqGrid
        $(window).bind('resize', function () {
            var width = $('.jqGrid_wrapper').width();
            gridTable1.setGridWidth(width);
        });

        $('#mod-file-accountSel').change(function(){
            onchangeAccountSel();
        });
    });


    function errorCallbackDefault(data){

    }
    function getBlankInfos(id){
        $("#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 loadPic(id, attachType){
        var url = '${contextPath}/order/getOrderAttachsByType';
        var parameters = {"orderId":id,"attachType":attachType};
        var picUrl = '${oss_bucket_ssdb_url}';
        $.ajax({
            dataType : "json",
            url : url,
            type : "post",
            data : parameters,
            success : function(data) {
                if(data.success){
                    if (data.attachs.length > 0) {
                        $("#div_templateId").hide();
                        $("#templateId_pic").show();
                        $("#templateId_del").show();
                        $("#templateId_pic_img").attr('src',picUrl + data.attachs[0].path);
                        $("#templateId_pic_hidden_id").val(data.attachs[0].id);
                    } else {
                        $("#div_templateId").show();
                        $("#templateId_pic").hide();
                        $("#templateId_del").hide();
                    }
                } else {
                    $("#div_templateId").show();
                    $("#templateId_pic").hide();
                    $("#templateId_del").hide();
                }
            }
        });
    }

    //删除图片
    function deletePic(){
        var id = '';
        id = $("#templateId_pic_hidden_id").val();

        var url = '${contextPath}/order/deleteAttachById';
        var parameters = {"id":id};
        $.ajax({
            dataType : "json",
            url : url,
            type : "post",
            data : parameters,
            success : function(data) {
                if(data.success){
                    $("#div_templateId").show();
                    $("#templateId_pic").hide();
                    $("#templateId_del").hide();
                } else {
                    showMsg(data.message);
                }

            }
        });
    }

    function applyTickets() {

        var notInvoice1 = $("#notInvoice1"); //未开票金额

        var invoType = $("#invoType").val();
        var qlc_zdz = $("#qlc_zdz").val();
        var taxNum = $("#taxNum").val();
        var companyAddress = $("#companyAddress").val();
        var phone = $("#phone").val();
        var bankName = $("#bankName").val();
        var bankAccount = $("#bankAccount").val();
        var bank = $("#bank").val();
        var money = $("#money").val();
        var address = $("#address").val();
        var receiver = $("#receiver").val();
        var receiverPhone = $("#receiverPhone").val();

        var orderTime = $("#orderTime").val();

        var sumServiceCost = $("#sumServiceCost").val();

        var mailAddr = $("#mailAddr").val();

        var checkData = 0 ;
        if ($("#checkData").prop('checked')) {
            checkData = 1 ;
        }

        if (address == '' || receiver == '' || receiverPhone == '') {
            alert("请输入完整配送信息");
            return ;
        }

        if (Number(money) > Number(notInvoice1)) {
            alert("开票金额不能大于剩余开票金额");
            return ;
        }

        if(!window.confirm('请确认好开票信息后再提交！')){
            return;
        }

        var data = {"invoType":invoType,"name":qlc_zdz,"taxNum":taxNum,"companyAddress":companyAddress,"phone":phone,"bankName":bankName,
            "bankAccount":bankAccount,"bank":bank,"money":money,"address":address,"receiver":receiver,"receiverPhone":receiverPhone,
            "checkData":checkData,"orderTime":orderTime,"serviceCost":sumServiceCost,"mailAddr":mailAddr};
        var url = '${contextPath}/company/saveTicketInfo';
        $.ajax({
            dataType : "json",
            url : url,
            type : "post",
            data : data,
            success : function(res) {
                if(res.success){
                    alert("申请成功");
                    $("#mod-file-apply").modal("toggle");
                    reloadGrid();
                } else {
                    alert("申请失败")
                }
            }
        });
    }

    function errorCallbackDefault(data){

    }

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

            var optionCity = '';
            var cityListArray = ret.cityList ;
            if (cityListArray != null) {
                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);
        }
    }

    function getOrderAttachsCallback(data){
        if(data.success){
            notSubmitReviewPayFail = true;
            notSubmitReviewPayPass = true;
            var html1 = '';
            var es = data.example3s;
            var e = null;
            var url = '${oss_bucket_ssdb_url}';
            var thum = '${oss_bucket_ssdb_url_img}';
            var size = '${oss_bucket_ssdb_url_img_size}';
            var path = null;
            for(var i in es){
                e = es[i];
                path = e.path;
                if(path.indexOf('/') != 0){
                    path = '/' + path;
                }
                html1 +='<a href="' + url + path + '" target="_blank">';
                html1 += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + path + size + e.suffix.toLowerCase() + '" height="100" width="100"/>';
                html1 +='</a>&nbsp;';
            }
            if(html1!=''){
                $('#modal-reviewPay-1').html(html1);
            }else
                $('#modal-reviewPay-1').html('无');

            var html2 = '';
            es = data.payed;
            for(var i in es){
                e = es[i];
                path = e.path;
                if(path.indexOf('/') != 0){
                    path = '/' + path;
                }
                html2 +='<a href="' + url + path + '" target="_blank">';
                html2 += '<img class="lazy" src="${contextPath}/static/img/loading.gif" data-original="' + thum + path + size + e.suffix.toLowerCase() + '" height="100" width="100"/>';
                html2 +='</a>&nbsp;';
            }
            if(html2!=''){
                $('#modal-reviewPay-2').html(html2);
            }else
                $('#modal-reviewPay-2').html('无');

            $("#modal-reviewPay").modal('toggle');
            //alert(1);
            setTimeout(function () {
                $("img.lazy").lazyload({
                    threshold : 200
                });
            }, 200);

        }else{
            showMsg(data.message);
        }

    }

    function initGridTable(){
        gridTable1 = jQuery(grid_selector).jqGrid({
            subGrid : false,
            url : "${contextPath}/order/getInvoice",//
            datatype : "json",
            height : "auto",
            autowidth:true,
            colModel : [{
                name : "month",
                index : "month",
                label : "月份",
                width : 40,
                search : false
            },{
                name : "sumServiceCost",
                index : "sumServiceCost",
                label : "服务费",
                width : 40,
                search : false,
                formatter:changeDoubleType
            },{
                name : "alreadyInvoice",
                index : "alreadyInvoice",
                label : "已开票金额",
                width : 60,
                search : false
            },{
                name : "notInvoice",
                index : "notInvoice",
                label : "未开票金额",
                width : 90,
                search : false,
                formatter:changeDoubleType
            },{
                align : "center",
                label : "操作",
                width : 180,
                viewable:false,
                sortable: false,
                fixed:true,
                formatter:operationLink
            }],
            sortname : "createDate",
            sortorder : "desc",
            viewrecords : true,
            rowNum : 20,
            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.lpDate ;
        if (cell.receivablesOverTime) {
            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 : "${contextPath}/order/getServiceCostLists",
            data : {},
            dataType : "json",
            success : function(data) {
                successCallback(data);
            },
            error : function(data) {
                errorCallback(data);
            }
        });
    }

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

    //操作链接
    function operationLink(cellvalue, options, rowObject){
        var result = '';
        if (!rowObject.invoiceAll) {
            result = '<a href="javascript:void(0);" style="color:blue" onclick="showApply(\''+rowObject.orderTime+'\','+ rowObject.notInvoice +','+ rowObject.sumServiceCost +')">申请开票</a>';
        }
        if (!rowObject.invoiceAll && rowObject.alreadyInvoice > 0) {
            result += '&nbsp;|&nbsp;';
        }
        if (rowObject.alreadyInvoice > 0) {
            result += '<a href="javascript:void(0);" style="color:blue" onclick="showApplyHis(\''+rowObject.orderTime+'\')">开票记录</a>';
        }
        return result;
    }

    //显示提交打款记录
    function showSubmitVoucher() {
        $("#mod-file_money").modal("toggle");
    }

    function showProtocol() {
        $("#modal-company-protocol").modal("toggle");
        $.ajax({
            type: "POST",
            url: url,
            data: "",
            dataType: "jsonp",
            success: function(e) {
            },
            error: function(data) {
            }
        });
    }

    function changeInvoType(type) {
        if (type == 1) {
            return '增值税专用发票';
        } else if(type == 0) {
            return '普通发票';
        } else {
            return type ;
        }
    }

    function timestampToTime(timestamp) {
        var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y+M+D+h+m+s;
    }

    function showImgUrls(id) {
        $("#modal-orderAttachs").modal("toggle");
        $.ajax({
            dataType : "json",
            url : "${contextPath}/order/getAttactImgUrls",
            type : "post",
            data : {
                'id' : id
            },
            success : function(ret) {

                var url = '${oss_bucket_ssdb_url}';
                var thum = '${oss_bucket_ssdb_url_img}';
                var size = '${oss_bucket_ssdb_url_img_size}';
                var v = '';
                var html = '';
                if (ret.success) {
                    var data = ret.data ;
                    for (var i = 0 ; i < data.length; i ++){
                        v = data[i];
                        html +='<a href="'  + url +'/'+ v.filePath + '" target="_blank" style="margin-left: 5px">';
                        html += '<img src ="' + thum +'/'+ v.filePath + '" height="100" width="100">';
                        html +='</a>&nbsp;';
                    }
                }

                $('#modal-orderAttachs-body').html(html);
            }
        });
    }

    function changeApplyType(type) {
        if (type == 1) {
            return '申请中';
        } else if(type == 2) {
            return '申请失败';
        }else if(type == 3) {
            return '未开票';
        }else if(type == 4) {
            return '已开票';
        }else if(type == 5) {
            return '未寄出';
        }else if(type == 6) {
            return '已寄出';
        } else {
            return type ;
        }
    }

    function showApplyHis(orderTime) {
        $("#mod-file-applyhis").modal("toggle");
        $.ajax({
            type : "POST",
            url : "${contextPath}/company/getAllTicketsHis",
            data : {"orderTime":orderTime},
            dataType : "json",
            success : function(result) {
                console.log(result);
                if (result.success) {
                    var data = result.data ;
                    var html = '';
                    for (var i = 0 ; i < data.length ; i ++) {
                        var url = thum +'/' + data[i].ticketImgUrl ;
                        if (i > 0) {
                            html += '<div class="hr-line-dashed row" style="margin-top: 10px" ></div>';
                        }
                        html += '<div class="row">' +
                            '                    <div class="col-xs-12">\n' +
                            '                        <!-- PAGE CONTENT BEGINS -->\n' +
                            '                        <form >\n' +
                            '                            <div class="col-xs-12">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">'+ timestampToTime(data[i].createTime) +'</label>\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px;">开票金额：<span>'+ data[i].money +'</span>元</label>\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px;text-align: right" >'+ changeApplyType(data[i].applyType) +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">发票类型：</label>\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">'+ changeInvoType(data[i].invoType) +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">发票抬头：</label>\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">'+ data[i].name +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                            <label class="col-sm-4 no-padding" style="margin-top: 5px">纳税人识别号：</label>\n' +
                            '<label class="col-sm-5 no-padding" style="margin-top: 5px">'+ data[i].taxNum +'</label>';

                           if (data[i].attacts > 0) {
                               html += '<input type="button" class="btn col-sm-3" onclick="showImgUrls(\''+ data[i].id +'\')" value="查看开票图片" />';
                           }
                           html += '</div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">公司地址：</label>\n' +
                            '                                <label class="col-sm-6 no-padding" style="margin-top: 5px">'+ data[i].companyAddress +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">电话：</label>\n' +
                            '                                <label class="col-sm-6 no-padding" style="margin-top: 5px">'+ data[i].phone +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">开户名：</label>\n' +
                            '                                <label class="col-sm-6 no-padding" style="margin-top: 5px">'+ data[i].bankName +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">开户账号：</label>\n' +
                            '                                <label class="col-sm-6 no-padding" style="margin-top: 5px">'+ data[i].bankAccount +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">开户行：</label>\n' +
                            '                                <label class="col-sm-6 no-padding" style="margin-top: 5px">'+ data[i].bank +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">开票内容：</label>\n' +
                            '                                <label class="col-sm-6 no-padding" style="margin-top: 5px">'+ data[i].ticketContent +'</label>\n' +
                            '                            </div>\n' +
                            '                            <div class="col-xs-12" style="color: #a4a6a9;font-weight: 200;">\n' +
                            '                                <label class="col-sm-4 no-padding" style="margin-top: 5px">发票寄件信息：</label>\n' +
                            '                                <label class="col-sm-8 no-padding" style="margin-top: 5px">'+ data[i].expressInfo +'</label>\n' +
                            '                            </div>\n' +
                            '                        </form>\n' +
                            '                    </div><!-- /.col -->\n' +
                            '                </div><!-- /.row -->';
                    }

                    html += '  <div class="text-center" style = "margin-top: 10px">\n' +
                        '                    <button type="button" class="btn btn-sm" data-dismiss="modal">关闭</button>\n' +
                        '                </div>';

                    $("#allticketHis").html(html);

                } else {
                    alert("出票记录获取失败！")
                }
            }
        });
    }

    function showApply(orderTime,notInvoice,sumServiceCost) {
        $("#orderTime").val(orderTime);
        $("#notInvoice1").val(notInvoice);
        $("#sumServiceCost1").val(sumServiceCost);
        $("#mod-file-apply").modal("toggle");
        $.ajax({
            type : "POST",
            url : "${contextPath}/company/getTicketHis",
            data : {},
            dataType : "json",
            success : function(result) {
                if (result != null) {
                    var companyInvoice = result.companyInvoice ;
                    $("#invoType").val(companyInvoice.invoType);
                    $("#qlc_zdz").val(companyInvoice.name);
                    $("#taxNum").val(companyInvoice.taxNum);

                    $("#companyAddress").val(companyInvoice.companyAddress);
                    $("#phone").val(companyInvoice.phone);
                    $("#bankName").val(companyInvoice.bankName);
                    $("#bankAccount").val(companyInvoice.bankAccount);
                    $("#bank").val(companyInvoice.bank);
                    $("#money").val(notInvoice);
                    $("#address").val(companyInvoice.address);
                    $("#receiver").val(companyInvoice.receiver);
                    $("#receiverPhone").val(companyInvoice.receiverPhone);

                    var list = result.ticketName ;
                    var ticketHtml = "";
                    $("#qlc_zdz1").empty();
                    $("#qlc_zdz1").append("<option value=请选择 >请选择</option>");
                    for (var i = 0 ; i < list.length ; i ++) {
                        var temp = list[i] ;
                        ticketHtml += '<option value =' + temp +'>'+temp+'</option>';
                    }
                    $("#qlc_zdz1").append(ticketHtml);
                }
            }
        });
    }

    function showExplain() {
        $("#modal-company-explain").modal("toggle");
    }

    //约定回款时间后加说明
    function changeAppointTime(cellvalue, options, rowObject) {
        var result = null ;
        //退保
        if (rowObject.overDays > 0) { //逾期了
            result = '<span>'+cellvalue+'</span><a style="margin-left: 2px" href="javaScript:void(0)" onclick="showProtocol()"><img src="../static/img/question.png" ></a>'
        } else {
            result = cellvalue ;
        }
        return result;
    }

    //逾期违约金后加说明
    function changeOverMoney(cellvalue, options, rowObject) {
        var result = null ;
        //退保
        if (rowObject.overDays > 0) { //逾期了
            result = '<span>'+cellvalue+'</span><a style="margin-left: 2px" href="javaScript:void(0)" onclick="showExplain()"><img src="../static/img/question.png" ></a>'
        } else {
            result = cellvalue ;
        }
        return result;
    }



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

    //保存付款未通过成功后回调
    function reviewPayFailCallback(data){
        notSubmitReviewPayFail = true;
        if(data.success){
            $("#modal-reviewPay").modal('toggle');
            showMsg('保存成功');
            reloadGrid();
        }else{
            showMsg(data.message);
        }
    }

    //保存付款未通过失败后回调
    function reviewPayFailErrorCallback(data){
        notSubmitReviewPayFail = true;
    }


    //保存付款未通过
    function reviewPayFailSubmit(){
        if(notSubmitReviewPayFail){
            var reason = $('#reviewPayFailReason').val();
            if(reason != undefined && reason.length > 0){
                notSubmitReviewPayFail = false;
                var url = '${contextPath}/order/saveReviewPayFail';
                var parameters = {"reason":reason,"orderId":currentOrderId};
                postData(url, parameters, reviewPayFailCallback, reviewPayFailErrorCallback);
            }else{
                alert('反馈问题说明不能为空');
            }
        }else{
            showMsg('提交中，请稍候');
        }
    }

    function reviewPayOperation(id,remark,bf){
        $("#input-bf").val("");
        if (remarkText != "null") {
            $("#remarkText").html(remark);
        }
        $("#mod-file-bf").val(bf);
        $("#modal-reviewPay-orderId").val(id);
        currentOrderId = id;
        var url = '${contextPath}/order/getOrderAttachs';
        var parameters = {"orderId":id};
        postData(url, parameters, getOrderAttachsCallback, errorCallbackDefault);
    }

    //保存付款通过成功后回调
    function reviewPayPassCallback(data){
        notSubmitReviewPayPass = true;
        if(data.success){
            $("#modal-reviewPay").modal('toggle');
            showMsg('保存成功');
            reloadGrid();
        }else{
            showMsg(data.message);
        }
    }

    function downloadOrderAttactByType(type) {
        var orderId = $("#modal-reviewPay-orderId").val();
        var url = "${contextPath}/order/downloadOrderAttachsByType?id=" + orderId + "&key=" + type ;
        window.open(url);
    }

    //保存付款未通过失败后回调
    function reviewPayPassErrorCallback(data){
        notSubmitReviewPayPass = true;
    }

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

    function search(){
        var startDate =$("#yearBill").val();
        gridTable1.setGridParam({postData:{'year':startDate},url : '${contextPath}/order/getInvoice',page:1}).trigger('reloadGrid');
    }

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

    function uploadFileShow(attachType,attachTemplateType,orderId){
        document.getElementById("fileform").reset();

        $("#mod-file-orderId").val(orderId);
        loadPic(orderId,70);
        getBlankInfos(orderId);
        $("#mod-file-attachType").val(attachType);
        $("#mod-file-attachTemplateType").val(attachTemplateType);
    }


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

    var appServer = 'http://b.duowenlvshi.com/oss/token?name=ssdb';
    var bucket = '${oss_bucket_ssdb}';
    var region = 'oss-cn-shenzhen';
    var Buffer = OSS.Buffer;
    var OSS = OSS.Wrapper;
    var STS = OSS.STS;
    var applyTokenDo = function(func) {
            var url = appServer;
            $.ajax({
                type: "POST",
                url: url,
                data: "",
                dataType: "jsonp",
                success: function(e) {
                    console.log(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 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+",";
                }
            }
            console.log(keyArray);
            console.log(fileNameArray);
            console.log(fileTypeArray);
            //saveToDB(orderId,keyArray,fileNameArray,fileTypeArray,accountBank,accountName,accountNum);
        }
    ;
    var progress = function(p) {//上传成功的进度条
            return function (done) {
                done();
            };
        }
    ;
    var getFileURL = function(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;
        }
    ;
    //文件上传处理
    function fileUpload() {
        var payMoney = $("#payMoney").val();
        var payDate = $("#payDate").val();
        if (payMoney.trim() == "" || payDate.trim() == "") {
            alert("打款金额或打款时间不能为空！");
            return;
        }
        applyTokenDo(uploadFile);
    }

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

    //保存图片路径到数据库
    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};

        $.ajax({
            dataType : "json",
            url : "${contextPath}/order/bdTempleteUpload",
            type : "post",
            data : parameters,
            success : function(result) {
                if(result.success){
                    uploadFileSuccess();
                }else
                    alert(result.message);
            }
        });
    }
</script>
<script>
    function downloadBillOrder() {
        var year = $("#yearBill").val();
        var month = $("#monthBill").val();
        var data = {"year":year,"month":month};
        window.open('${contextPath}/order/downloadBillOrder?year='+year + '&month='+month);
    }

    function confirmBills() {
        var year = $("#yearBill").val();
        var month = $("#monthBill").val();
        var data = {"year":year,"month":month};
        $.ajax({
            dataType : "json",
            url : "${contextPath}/order/confirmBillOrder",
            type : "post",
            data : data,
            success : function(result) {
                if (result != null) {
                    if (result.success) {
                        $("#confirmBill").html("已确认");
                        $("#confirmBill").attr('disabled',true);
                    }
                    alert(result.message);
                }
            }
        });
    }

    function getTotalCost(data) {
        $.ajax({
            dataType : "json",
            url : "${contextPath}/order/getTotalCost",
            type : "post",
            data : data,
            success : function(result) {
                if (result != null) {
                    $("#addServiceCost").html(result.addServiceCost);
                    $("#reduceServiceCost").html(result.reduceServiceCost);
                    $("#sumServiceCost").html(result.sumServiceCost);
                    $("#dealBf").html(result.dealBf);
                    if (result.confirmBill) {
                        $("#confirmBill").html("已确认");
                        $("#confirmBill").attr('disabled',true);
                    } else {
                        $("#confirmBill").html("对账单确认无误");
                        $("#confirmBill").attr('disabled',false);
                    }
                    if (result.orderTime) {
                        var time = result.orderTime ;
                        var arr = time.split("-");
                        if (arr.length > 2) {
                            $("#yearBill").val(arr[0]);
                            $("#monthBill").val(arr[1]);
                        }
                    }

                    if (result.currentMon) {
                        alert("该月账单未生成。。")
                    }
                }
            }
        });
    }

    $(function () {

    });
</script>