<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="renderer" content="webkit">
    <!-- 移动设备 viewport -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <jsp:include page="../../common.jsp"/>
    <style>
        .layui-table th {
            text-align: center;
        }

        .buttons {
            margin-right: .5rem;
        }
    </style>
    <script type="text/javascript">
        require("js/merchantOrder/merchantOrderList.js");
    </script>
</head>
<body>
<div class="row animated" style="margin: 0;">
    <div class="wrapper wrapper-content mt5 right-content ml5 mr5">
        <div class="toolbar-panel bdd">
            <div class="toolbar-box">
                <div class="toolbar-head clearfix lgraybg pt5 pb10 pl10 bdbd">
                    <!-- 顶部按钮 -->
                    <div class="buttons fl">
                        <a class="layui-btn layui-btn-sm fa fa-search f13" href="javascript:void(0);"
                           onclick="queryMerchantOrderSearch()"><span>搜索</span></a>
                    </div>
                    <div class="buttons fl">
                        <a class="layui-btn layui-btn-sm layui-btn-warm fa fa-check f13" href="javascript:void(0);"
                           onclick="syncPluginOrder()"><span>同步</span></a>
                    </div>
                    <div class="buttons fl">
                        <a class="layui-btn layui-btn-sm layui-btn-normal fa fa-download f13" href="javascript:void(0);"
                           onclick="downloadSettleFile()"><span>下载对账文件</span></a>
                    </div>
                    <div class="tools fr">
                        <a href="javascript:void(0);" class="collapse dblock f14 dgray mr5">
                            <i class="fa-2x fa fa-angle-double-up"></i>
                        </a>
                    </div>
                </div>
            </div>

            <!--搜索条件 -->
            <div class="toolbar-body">
                <form class="layui-form" action="" style="margin-top: 10px">
                    <div class="layui-form-item">
<%--                        <div class="layui-inline">--%>
<%--                            <label class="layui-form-label">用户ID</label>--%>
<%--                            <div class="layui-input-inline">--%>
<%--                                <input type="text" placeholder="请输入用户ID" id="userId" name="userId" class="layui-input">--%>
<%--                            </div>--%>
<%--                        </div>--%>

                        <div class="layui-inline">
                            <label class="layui-form-label">订单号：</label>
                            <div class="layui-input-inline">
                                <input type="text" id="orderNumber" name="orderNumber" placeholder="请输入订单号"
                                       class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">商户名称：</label>
                            <div class="layui-input-inline">
                                <input type="text" id="alias" name="alias" placeholder="请输入商户名称" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">商户编号：</label>
                            <div class="layui-input-inline">
                                <input type="text" id="merchantCode" name="merchantCode" placeholder="商户编号" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">订单类型：</label>
                            <div class="layui-input-inline">
                                <select id="orderType" name="orderType">
                                    <option value="">请选择订单类型</option>
                                    <option value="1">主扫</option>
                                    <option value="2">被扫</option>
                                    <option value="3">会员充值</option>
                                    <option value="4">POS</option>
                                    <option value="5">主扫充值</option>
                                    <option value="6">扫码王收款</option>
                                    <option value="7">H5</option>
                                    <option value="8">升级消费</option>
                                    <option value="9">小程序</option>
                                    <option value="10">线上店</option>
                                    <option value="11">缴费通</option>
                                    <option value="99">插件</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">支付方式：</label>
                            <div class="layui-input-inline">
                                <select id="payTypeCode" name="payTypeCode">
                                    <option value="">请选择交易状态</option>
                                    <option value="sxfPay0|aliPay">支付宝</option>
                                    <option value="sxfPay1|wechatPay">微信</option>
                                    <option value="sxfPay2|bank">银联</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">交易状态：</label>
                            <div class="layui-input-inline">
                                <select id="status" name="status">
                                    <option value="">请选择交易状态</option>
                                    <option value="5">待付款</option>
                                    <option value="1">交易成功</option>
                                    <option value="0">交易失败</option>
                                    <option value="2">退款成功</option>
                                    <option value="3">退款失败</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">结算类型：</label>
                            <div class="layui-input-inline">
                                <select id="settlementType" name="settlementType">
                                    <option value="">请选择</option>
                                    <option value="0">D0</option>
                                    <option value="1">D1</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">订单来源：</label>
                            <div class="layui-input-inline">
                                <select id="aisleSwitch" name="aisleSwitch">
                                    <option value="">请选择</option>
                                    <c:forEach items="${channelList}" var="c">
                                        <option value="${c.id eq 1 ? 2 : c.id}">${c.channelName}</option>
                                    </c:forEach>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">开始日期</label>
                            <div class="layui-input-inline">
                                <input type="text" placeholder="开始日期" id="date1" name="startTime" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">结束日期</label>
                            <div class="layui-input-inline">
                                <input type="text" placeholder="结束日期" id="date2" name="endTime" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>
                    </div>
                    <br>
                    <div class="mt10 mb20" style="position: relative;">
                        <button type="button" id="gofile1"
                                style="position: absolute;right: 30px;padding: 5px;bottom: 0px;background-color: #ff5e5f;color: #fff;border-radius: 8px;">
                            批量导出
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="box-flex  fw600 f18" style="justify-content:space-around;padding: 1rem;align-items: center;">
    <div>交易总额：<span id="transAmountCount" style="color:#ff5e5f;"></span>元</div>
    <div>退款总额：<span id="refundAmountCount" style="color:#ff5e5f;"></span>元</div>
    <div>实收总额：<span id="normalAmountCount" style="color:#ff5e5f;"></span>元</div>
    <div>收益总额：<span id="profitAmountCount" style="color:#ff5e5f;"></span>元</div>
    <div style="font-size: 1rem;">
        <div>交易分润：<span id="transProfitAmountCount" style="color:#ff5e5f;"></span>元</div>
        <div>笔数分润：<span id="numberAmountCount" style="color:#ff5e5f;"></span>元</div>
        <div>升级分润：<span id="upAmountCount" style="color:#ff5e5f;"></span>元</div>
    </div>
    <div>推广分润：<span id="shareAmountCount" style="color:#ff5e5f;"></span>元</div>
    <div>粉丝分润：<span id="fansAmountCount" style="color:#ff5e5f;"></span>元</div>
    <div>实际收益：<span id="actualAmountCount" style="color:#ff5e5f;"></span>元</div>
</div>

<div class="mb50 mt10">
    <div class="whitebg pl10 pr10">
        <table class="layui-hide" id="merchantOrderList" lay-filter="merchantOrderList"></table>
    </div>
</div>
</body>

<script id="orderTypeSearch" type="text/html">
    {{# if (d.orderType == "1") { }}
    <span>主扫</span>
    {{# } else if(d.orderType == "2") {}}
    <span>被扫</span>
    {{# } else if(d.orderType == "3") {}}
    <span>会员充值</span>
    {{# } else if(d.orderType == "4") {}}
    <span>POS</span>
    {{# } else if(d.orderType == "5") {}}
    <span>主扫充值</span>
    {{# } else if(d.orderType == "6") {}}
    <span>扫码王收款</span>
    {{# } else if(d.orderType == "7") {}}
    <span>H5</span>
    {{# } else if(d.orderType == "8") {}}
    <span>升级消费</span>
    {{# } else if(d.orderType == "9") {}}
    <span>小程序</span>
    {{# } else if(d.orderType == "10") {}}
    <span>线上店</span>
    {{# } else if(d.orderType == "11") {}}
    <span>缴费通</span>
    {{# } else if(d.orderType == "99") {}}
    <span>插件</span>
    {{# } }}
</script>

<script id="payTypeCodeSearch" type="text/html">
    {{# if (d.payTypeCode == "sxfPay0" || d.payTypeCode == "aliPay") { }}
    <span>支付宝</span>
    {{# } else if(d.payTypeCode == "sxfPay1" || d.payTypeCode == "wechatPay") {}}
    <span>微信</span>
    {{# } else if(d.payTypeCode == "sxfPay2" || d.payTypeCode == "bank") {}}
    <span>银联</span>
    {{# } }}
</script>

<script id="lineBar" type="text/html">
    {{# if (d.status == '5' || d.status == '7')  {}}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="suppleOrder">补单</a>
    {{# } }}
</script>

<script id="dealStatus" type="text/html">
    {{# if (d.status == "0") { }}
    <span style="color: red">交易失败</span>
    {{# } else if(d.status == "1") {}}
    <span style="color: green">交易成功</span>
    {{# } else if(d.status == "2") {}}
    <span style="color: green">退款成功</span>
    {{# } else if(d.status == "3") {}}
    <span style="color: red">退款失败</span>
    {{# } else if(d.status == "5") {}}
    <span style="color: blue">待付款</span>
    {{# } else if(d.status == "7") {}}
    <span style="color: blue">待付款(待确认)</span>
    {{# } }}
</script>


<script type="text/template" id="settle">
    <form class="layui-form" id="settleForm" style="margin-top: 2rem;">
        <div class="layui-form-item" style="width: 300px;">
            <label class="layui-form-label">日期</label>
            <div class="layui-input-block">
                <input type="text" name="date" id="accountDate" style="cursor: pointer" placeholder="日期"  autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="width: 300px;">
            <label class="layui-form-label">通道</label>
            <div class="layui-input-block">
                <select class="layui-select" id="channel" name="channel" >
                    <option value="">请选择</option>
                    <option value="4">银盛</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item" style="width: 300px;">
            <label class="layui-form-label">类型</label>
            <div class="layui-input-block">
                <select class="layui-select" id="type" name="type" >
                    <option value="">请选择</option>
                    <option value="1">清算文件</option>
                    <option value="2">交易文件</option>
                </select>
            </div>
        </div>
    </form>
</script>

<script type="text/javascript">
    var layer;
    var form;
    var table;
    var laydate;
    var dropdown;
    //form表单样式
    layui.use(['table', 'layer', 'form', 'laydate', 'dropdown'], function () {
        layer = layui.layer;
        form = layui.form;
        table = layui.table;
        laydate = layui.laydate;
        dropdown = layui.dropdown;
        form.render();
        laydate.render({
            elem: '#date1',//指定元素
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss'
        });
        laydate.render({
            elem: '#date2', //指定元素
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss'
        });

        //执一个 table 实例
        table.render({
            elem: '#merchantOrderList'
            , id: 'merchantOrderList'
            , url: ctx + '/merchantOrder/queryMerchantOrderByPage' //数据接口
            , autoSort: false
            , where: {
                userId: $('#userId').val()
                , orderNumber: $('#orderNumber').val()
                , payTypeCode: $('#payTypeCode').val()
                , alias: $('#alias').val()
                , orderType: $("#orderType :selected").val()
                , status: $("#status :selected").val()
                , startTime: $('#date1').val()
                , endTime: $('#date2').val()
                , settlementType: $('#settlementType').val()
                , aisleSwitch: $('#aisleSwitch').val()
            }
            , response: {
                statusName: 'code' //数据状态的字段名称，默认：code
                , countName: 'count' //数据总数的字段名称，默认：count
                , dataName: 'data' //默数据列表的字段名称，认：data
                , statusCode: 200
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.merchantOrderList, //解析数据列表，
                    "resultData": res.resultData
                };
            }
            , request: {
                pageName: 'currPage' //页码的参数名称，默认：page
                , limitName: 'size' //每页数据量的参数名，默认：limit
            }
            , title: '订单列表'
            , page: true //开启分页
            , toolbar: '#toolBar' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            , defaultToolbar: ['filter']
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[ //表头
                {type: 'numbers', fixed: 'left'}
                // , {field: 'userId', title: '用户ID', align: "center", fixed: 'left'}
                , {
                    field: 'orderNumber', align: "center", minWidth: 150, title: '订单号', templet: function (d) {
                        return d.orderNumber + "<br/>" + d.transNo + "<br/>" + d.thirdTransNo + "<br/>" + d.mercOrderNo;
                    }
                }
                // , {field: 'transNo',align:"center", title: '商户单号',width: 280}
                , {field: 'merchantName', align: "center", minWidth: 150, title: '商户名称'}
                , {field: 'merchantCode', align: "center", minWidth: 180, title: '商户编号'}
                , {field: 'orderType', align: "center", minWidth: 100, title: '类型', templet: '#orderTypeSearch'}
                , {field: 'payTypeCode', align: "center", minWidth: 90, title: '支付方式', templet: '#payTypeCodeSearch'}
                , {
                    field: 'consumeFee', align: "center", minWidth: 110, title: '订单金额', templet: function (d) {
                        return d.consumeFee.toFixed(2);
                    }
                }
                , {
                    field: 'mercFee', align: "center", title: '手续费', templet: function (d) {
                        if (!d.mercFee || d.mercFee == 0) {
                            return "0.00";
                        } else {
                            return d.mercFee;
                        }
                    }
                }
                , {
                    field: 'cashFee', align: "center", title: '提现手续费', templet: function (d) {
                        if (!d.cashFee || d.cashFee == 0) {
                            return "0.00";
                        } else {
                            return d.cashFee;
                        }
                    }
                }
                , {
                    field: 'enterFee', align: "center", minWidth: 110, title: '实际到账', templet: function (d) {
                        if(d.enterFee){
                            return d.enterFee;
                        }
                        return "0.00";
                    }
                }
                , {
                    field: 'mercRate', align: "center", minWidth: 100, title: '商户费率%', templet: (d) => {
                        return (d.mercRate / 100) + "%";
                    }
                }
                // , {
                //     field: 'aisleRate', align: "center", minWidth: 100, title: '通道费率%', templet: (d) => {
                //         return (d.aisleRate / 100) + "%";
                //     }
                // }
                , {
                    field: 'platformRevenue', align: "center", minWidth: 90, title: '平台收益', templet: function (d) {
                        if (!d.platformRevenue || d.platformRevenue == 0) {
                            return "0.00";
                        } else {
                            return d.platformRevenue;
                        }
                    }
                }
                , {
                    field: 'profitShareMoney', align: "center", minWidth: 90, title: '推广分润', templet: function (d) {
                        if (!d.profitShareMoney) {
                            return "0.00";
                        } else {
                            return d.profitShareMoney;
                        }
                    }
                }
                , {
                    field: 'fansShareMoney', align: "center", minWidth: 90, title: '粉丝分润', templet: function (d) {
                        if (!d.fansShareMoney) {
                            return "0.00";
                        } else {
                            return d.fansShareMoney;
                        }
                    }
                }
                , {
                    field: 'marketAmt', align: "center", title: '奖励积分', minWidth: 90, templet: function (d) {
                        if (!d.marketAmt) {
                            return "0.00";
                        } else {
                            return d.marketAmt;
                        }
                    }
                }
                , {
                    field: 'practical', align: "center", title: '实际收益', minWidth: 90, templet: function (d) {
                        if (!d.practical) {
                            return "0.00";
                        } else {
                            return d.practical;
                        }
                    }
                }
                , {
                    title: '创建/交易时间', minWidth: 155, align: "center", templet: function (d) {
                        var orderTime = layui.util.toDateString(d.createDt, 'yyyy-MM-dd HH:mm:ss');
                        if (d.transDt != null) {
                            orderTime = orderTime + "<br/>" + layui.util.toDateString(d.transDt, 'yyyy-MM-dd HH:mm:ss')
                        }
                        return orderTime;
                    }
                }
                , {field: 'ip', align: "center", minWidth: 150, title: '付款IP'}
                , {field: 'ipAddress', align: "center", minWidth: 250, title: '付款地址'}
                , {field: 'drType', align: "center", minWidth: 80, title: '卡类型',templet: function (d){
                    if(d.drType){
                        if(d.drType == "1"){
                            return "储蓄卡";
                        }else if(d.drType == "2"){
                            return "信用卡";
                        }else{
                            return "其他";
                        }
                    }else{
                        return "-";
                    }
                  }}
                , {
                    field: 'status',
                    align: "center",
                    minWidth: 100,
                    title: '交易状态',
                    templet: '#dealStatus',
                    fixed: 'right'
                }
                , {field: 'right', title: '操作', align: 'center', toolbar: '#lineBar', fixed: 'right'}
            ]]
            , done: function (res) {
                // dropdown.suite();
                if (res.resultData == null) {
                    $("#transAmountCount").html(0);
                    $("#refundAmountCount").html(0);
                    $("#profitAmountCount").html(0);
                    $("#shareAmountCount").html(0);
                    $("#fansAmountCount").html(0);
                    $("#actualAmountCount").html(0);

                    $("#transProfitAmountCount").html(0);
                    $("#numberAmountCount").html(0);
                    $("#upAmountCount").html(0);
                } else {
                    $("#transAmountCount").html(res.resultData.transAmountCount);
                    $("#refundAmountCount").html(res.resultData.refundAmountCount);
                    $("#normalAmountCount").html((parseFloat(res.resultData.transAmountCount) - parseFloat(res.resultData.refundAmountCount)).toFixed(2));
                    $("#profitAmountCount").html(res.resultData.profitAmountCount);
                    $("#shareAmountCount").html(res.resultData.shareAmountCount);
                    $("#fansAmountCount").html(res.resultData.fansAmountCount);
                    $("#actualAmountCount").html(res.resultData.actualAmountCount);

                    $("#transProfitAmountCount").html(res.resultData.transProfitAmountCount);
                    $("#numberAmountCount").html(res.resultData.numberAmountCount);
                    $("#upAmountCount").html(res.resultData.upAmountCount);
                }
            }
        });
        //监听行工具事件
        table.on('tool(merchantOrderList)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'suppleOrder') {
                suppleOrder(data);
            }
        });


    });

    function downloadSettleFile(){
        let openIndex = layer.open({
            type: 1,
            closeBtn: 1,
            title: '下载对账文件',
            offset: 'm', //具体配置参考：offset参数项
            area: ['450px', '500px'],
            content: $("#settle").html(),
            btn: ['确认','取消'],
            btnAlign: 'r'	, //按钮居中
            shade: 0.3 ,//不显示遮罩
            success:function (){
                laydate.render({
                    elem: '#accountDate', //指定元素
                    format: 'yyyy-MM-dd'
                });
                form.render("select");
            },
            yes: function() {
                let accountDate = $("#accountDate").val();
                let channel = $("#channel").val();
                let type = $("#type").val();
                if(!accountDate){
                    return layer.msg("日期必填");
                }
                if(!channel){
                    return layer.msg("所属通道必填");
                }
                if(!type){
                    return layer.msg("文件类型必填");
                }
                let index = layer.load(1, {shade: [0.1, '#000']});
                let url = ctx + "/merchantOrder/getChannelFileUrl";
                $.ajax({
                    url:url,
                    type:'POST',
                    data:{
                        accountDate:accountDate,
                        channel:channel,
                        type:type
                    },
                    dataType: 'json',
                    success:function (res){
                        layer.close(index);
                        layer.close(openIndex);
                        layer.msg(res.message,{icon:res.code == 200 ? 1 : 2})
                        if(res.code == 200){
                            window.location.href = res.data;
                        }
                    }
                })
            }
        });
    }

    function suppleOrder(data) {
        // var id = $(this).attr("data-id");
        var id = data.id;
        layer.confirm('是否确认对订单ID为【' + id + '】发起补单？', function () {
            var index = layer.load(1, {shade: [0.1, '#000']});
            $.ajax({
                url: '${ctx}/merchantOrder/suppleOrder/' + id,
                type: 'post',
                dataType: "json",
                success: function (res) {
                    layer.close(index);
                    if (res.code == 200) {
                        layer.msg(res.message, {icon: 1});
                        $("#queryForm").submit();
                    } else {
                        layer.msg(res.message, {icon: 5});
                    }
                }
            })
        })
    }

    //查询
    function queryMerchantOrderSearch() {
        table.reload('merchantOrderList', {
            page: {
                curr: 1
            }
            , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                userId: $('#userId').val()
                , orderNumber: $('#orderNumber').val()
                , payTypeCode: $('#payTypeCode').val()
                , alias: $('#alias').val()
                , orderType: $("#orderType :selected").val()
                , status: $("#status :selected").val()
                , startTime: $('#date1').val()
                , endTime: $('#date2').val()
                , settlementType: $("#settlementType").val()
                , aisleSwitch: $("#aisleSwitch").val()
                , merchantCode: $("#merchantCode").val()
            }
        });
    }

    /**
     * 同步插件订单
     */
    function syncPluginOrder() {
        let startTime = $("#date1").val();
        let endTime = $("#date2").val();
        if (!startTime || !endTime) {
            layer.msg("请在“开始日期”和“结束日期”指定需要同步的数据的日期");
            return;
        }
        let daysBetween = getDaysBetween(startTime, endTime);
        if (parseFloat(daysBetween) >= 1) {
            layer.msg("日期相差超过一天");
            return;
        }
        var url = ctx + "/merchantOrder/syncPluginOrder"
        var dialog = layer.msg('正在同步...', {icon: 16, time: 0, shade: [0.3, '#000', false]});
        $.post(url, {'startDate': startTime, 'endDate': endTime}, (res) => {
            layer.close(dialog);
            if (res.code == 200) {
                layer.msg("数据同步成功", {icon: 1});
            } else {
                layer.msg(res.message, {icon: 2});
            }
        })
    }

    function getDaysBetween(dateString1, dateString2) {
        var startDate = Date.parse(dateString1);
        var endDate = Date.parse(dateString2);
        var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
        return days;
    }
</script>
<script type="text/javascript">
    $("#gofile1").on("click", function () {
        window.location.href = ctx + '/merchantOrder/dowloadExcel';
        /*  $("#ExTable").table2excel({
             exclude  : ".noExl",                                       //过滤位置的 css 类名
             filename : "Excel" + new Date().getTime(),        //文件名称
             name: "Excel Document Name.xlsx",
             exclude_img: true,
             exclude_links: true,
             exclude_inputs: true
         }); */
    });
</script>
</html>

