<%@ page contentType="text/html; charset=utf-8"
         pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!Doctype html>
<html>
<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>
    </style>
</head>
<body>
<div class="row animated fadeInRight" 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="fl">
                        查询条件
                    </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" id="form1" 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-block">
                                <input type="text" name="userId" id="userId" placeholder="请输入用户ID"
                                       autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <%--                        <div class="layui-inline">--%>
                        <%--                            <label class="layui-form-label">商户名称</label>--%>
                        <%--                            <div class="layui-input-block">--%>
                        <%--                                <input type="text" name="alias" id="alias" placeholder="请输入商户名称"--%>
                        <%--                                       autocomplete="off" class="layui-input">--%>
                        <%--                            </div>--%>
                        <%--                        </div>--%>
                        <input type="hidden" name="condition" id="condition" class="layui-input">
                        <div class="layui-inline">
                            <label class="layui-form-label">日期</label>
                            <div class="layui-input-inline">
                                <input type="text" placeholder="开始日期" readonly id="date1" name="startTime"
                                       autocomplete="off"
                                       class="layui-input layui-disabled">
                            </div>
                            <div class="layui-input-inline">
                                <input type="text" placeholder="结束日期" readonly id="date2" name="endTime"
                                       autocomplete="off"
                                       class="layui-input layui-disabled">
                            </div>
                            <button class="layui-btn layui-btn-primary check-btn layui-border-green" data-v="1"
                                    type="button">今日
                            </button>
                            <button style="margin-left: -4px;" class="layui-btn layui-btn-primary check-btn" data-v="2"
                                    type="button">昨日
                            </button>
                            <%--                            <button class="layui-btn layui-btn-primary check-btn" data-v="3" type="button" >上月</button>--%>
                            <button style="margin-left: -4px;" class="layui-btn layui-btn-primary check-btn" data-v="-1"
                                    type="button">全部
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="mb50 mt10">
        <div class="whitebg pl10 pr10">
            <table class="layui-hide" id="mercTradeDataTab" lay-filter="mercTradeDataTab"></table>
        </div>
    </div>
</div>
<script type="text/html" id="leftBar">
    <a class="layui-btn layui-btn-sm" lay-event="search">
        <i class="layui-icon layui-icon-search"></i>查询
    </a>
</script>

<script type="text/template" id="remarkForm">
    <form class="layui-form" id="form2" style="margin-top: 2rem;">
        <input name="id" id="id" hidden>
        <div class="layui-form-item" style="width: 400px;">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" id="remark" placeholder="备注说明" class="layui-textarea"></textarea>
            </div>
        </div>
    </form>
</script>

<script type="text/html" id="lineBar">
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="followUp">
        复制并跟进
    </a>
    <a class="layui-btn layui-btn-xs" lay-event="pass">
        已通过
    </a>
</script>

<script type="text/html" id="lineBar2">
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="addFollowUp">
        添加
    </a>
    <a class="layui-btn layui-btn-xs" lay-event="followUpRecord">
        查看
    </a>
</script>

<script type="text/html" id="lineBar3">
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="sendNotice">
        <i class="layui-icon layui-icon-release"></i>发送通知
    </a>
</script>

<script>
    layui.use(['table', 'layer', 'laydate', 'form'], function () {
        let table = layui.table;
        let laydate = layui.laydate;
        let form = layui.form;
        let fmt = "YYYY-mm-dd";
        let date = new Date();
        let dateTime = dateChange(0, dateFormat(fmt, date));
        $("#date1").val(dateTime);
        $("#date2").val(dateTime);
        var tableIns = table.render({
            elem: '#mercTradeDataTab'
            , url: ctx + '/mercData/tradePage'
            , id: 'mercTradeData'
            , where: {
                condition: 1,
                startTime: dateTime,
                endTime: dateTime,
            }
            , 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.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , toolbar: '#leftBar' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter']
            , title: '商户交易数据统计'
            , cols: [[
                {type: 'checkbox', fixed: 'left', hidden: true}
                , {field: 'numbers', title: '序号', fixed: 'left', unresize: true, width: 70, type: 'numbers'}
                , {
                    field: 'userId', title: '用户ID / 商户名称', minWidth: 180, templet: function (d) {
                        return d.userId + '&emsp;&emsp;' + d.alias;
                    }
                }
                , {
                    field: 'tradeSumAmt', title: '交易金额', sort: 'true', minWidth: 130, templet: function (d) {
                        if (d.tradeSumAmt) {
                            return d.tradeSumAmt.toFixed(2);
                        }
                        return "-";
                    }
                }
                , {field: 'tradeSumNum', title: '交易笔数', sort: 'true', minWidth: 100}
                , {
                    field: 'prevTradeSumAmt', title: '昨日金额', width: 120, templet: function (d) {
                        if (d.prevTradeSumAmt) {
                            return d.prevTradeSumAmt.toFixed(2);
                        }
                        return "-";
                    }
                }
                , {
                    field: 'prevTradeSumNum', title: '昨日笔数', minWidth: 100, templet: function (d) {
                        if (d.prevTradeSumNum) {
                            return d.prevTradeSumNum;
                        }
                        return "-";
                    }
                }
                , {
                    field: 'amtChain', title: '金额环比%', width: 100, templet: function (d) {
                        if (d.amtChain) {
                            return d.amtChain + "%";
                        }
                        return "-";
                    }
                }
                , {
                    field: 'numChain', title: '笔数环比%', width: 100, templet: function (d) {
                        if (d.numChain) {
                            return d.numChain + "%";
                        }
                        return "-";
                    }
                }
                , {field: 'phone', title: '注册手机号', width: 120}
                , {
                    title: '异地支付', align: "center", templet: (d) => {
                        return '<input type="checkbox" ' + (d.payEcdemicSwitch == "1" ? "checked" : "") + ' lay-filter="switchPayEcdemicSwitch" lay-skin="switch" data-userId="' + d.userId + '" lay-text="开启|关闭">';
                    }
                }
                , {
                    title: '跟进状态', align: "center", width: 80, templet: (d) => {
                        switch (d.followStatus) {
                            case '1':
                                return "<span style='color: #00B83F'>已跟进</span>";
                            case '2':
                                return "<span style='color: #00AA91'>待验证</span>";
                            default:
                                return "<span style='color: red'>待跟进</span>";
                        }
                    }
                }
                , {fixed: 'right', title: '状态操作', toolbar: '#lineBar', width: 170}
                , {fixed: 'right', title: '跟进记录', toolbar: '#lineBar2', width: 130}
                , {fixed: 'right', title: '其他操作', toolbar: '#lineBar3', width: 120}
            ]]
            , request: {
                pageName: 'current' //页码的参数名称，默认：page
                , limitName: 'size' //每页数据量的参数名，默认：limit
            }
            , page: true
        });
        table.on('toolbar(mercTradeDataTab)', function (obj) {
            switch (obj.event) {
                case 'add':
                    // 添加
                    toAdd();
                    break;
                case 'search':
                    var params = serialize($('#form1'));
                    table.reload('mercTradeData', {
                        where: params
                        , page: {
                            size: 10
                            , current: 1
                        }
                    });
                    break;
            }
        });

        table.on('tool(mercTradeDataTab)', function (obj) {
            switch (obj.event) {
                case 'followUp':
                    navigator && navigator.clipboard && navigator.clipboard.writeText(obj.data.phone).then(res => {
                        layer.msg("已复制");
                        layer.confirm("是否已开始跟进？", {title: '跟进确认', icon: 3}, function (index) {
                            $.ajax({
                                url: ctx + '/user/followUpStart'
                                , type: 'POST'
                                , data: {
                                    userId: obj.data.userId
                                }
                                , success: function (d) {
                                    layer.msg(d.message);

                                    if (d.code === 200) {
                                        table.reload('mercTradeData', {
                                            where: params
                                            , page: {
                                                size: 10
                                                , current: 1
                                            }
                                        });
                                        layer.close(index)
                                    }
                                }
                            })
                        });
                    }).catch(err => {

                    })
                    break;
                case 'pass':
                    layer.confirm("是否已跟进？", {title: '跟进确认', icon: 3}, function (index) {
                        $.ajax({
                            url: ctx + '/user/followUpSuccess'
                            , type: 'POST'
                            , data: {
                                userId: obj.data.userId
                            }
                            , success: function (d) {
                                layer.msg(d.message);

                                if (d.code === 200) {
                                    table.reload('mercTradeData', {
                                        where: params
                                        , page: {
                                            size: 10
                                            , current: 1
                                        }
                                    });
                                    layer.close(index)
                                }
                            }
                        })
                    });
                    break;
                case 'followUpRecord':
                    var url = ctx + "/user/followUpData?userId=" + obj.data.userId;
                    parent.layui.index.openTabsPage(url, obj.data.userId + "-跟进详情")
                    break;

                case 'addFollowUp':
                    layer.prompt({
                        formType: 0
                        , title: '添加跟进记录'
                    }, function (value, index, elem) {
                        $.ajax({
                            url: ctx + "/user/addFollowUpRecord"
                            , type: 'POST'
                            , data: {
                                userId: obj.data.userId
                                , remark: value
                            }
                            , success: function (d) {
                                layer.msg(d.message);

                                if (d.code === 200) {
                                    layer.close(index)
                                }
                            }
                        })
                    })
                    break;
                case 'sendNotice':
                    sendNotice(obj.data);
                    break;
            }
        });

        function sendNotice(obj) {
            var url = ctx + '/notice/detail?userId=' + obj.userId;
            var index = layer.open({
                type: 2
                , title: "通知详情"
                , shade: 0.5
                , maxmin: true
                , content: url
                , area: ['753px', '700px']
                , end: function () {
                    time: 1000
                }
            });
        }

        //触发排序事件
        table.on('sort(mercTradeDataTab)', function (obj) { //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var params = serialize($('#form1'));
            params["field"] = obj.field;
            params["order"] = obj.type;
            table.reload('mercTradeData', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                , where: params
            });
            // layer.msg('服务端排序。order by ' + obj.field + ' ' + obj.type);
        });
        form.on('switch(switchPayEcdemicSwitch)', function (data) {
            let userid = $(data.elem).data().userid;
            let param = {};
            param.id = userid;
            param.payEcdemicSwitch = this.checked ? '0' : '1';
            let msg = this.checked ? '开启异地支付' : '关闭异地支付';
            openLayer(msg, param, data);
        })

        function openLayer(title, param, data) {
            // if(param.payEcdemicSwitch == 0){
            //     layer.confirm('确认关闭异地支付吗?',
            //         {icon: 3, title:'提示',cancel:function (){
            //                 $(data.elem).prop('checked', !data.elem.checked)
            //                 layui.form.render();//刷新表格
            //                 layer.msg('您点击了取消！');
            //             }}
            //         , function(index){
            //             layer.close(index);
            //         },
            //         function (){
            //             $(data.elem).prop('checked', !data.elem.checked)
            //             layui.form.render();//刷新表格
            //             layer.msg('您点击了取消！');
            //         }
            //     );
            // }else{
            //     let index = layer.open({
            //         title: title,
            //         shade: 0.5,
            //         maxmin: true,
            //         area: ['550px', '300px'],
            //         content: $("#remarkForm").html(),
            //         btn: ['确认', '取消'],
            //         yes: function () {
            //
            //         }
            //         ,btn2: function(index, layero){
            //             $(data.elem).prop('checked', !data.elem.checked)
            //             layui.form.render();//刷新表格
            //             layer.msg('您点击了拒绝！');
            //             layer.close(index);
            //         }
            //     });
            // }
            let index = layer.open({
                title: title,
                shade: 0.5,
                maxmin: true,
                area: ['550px', '300px'],
                content: $("#remarkForm").html(),
                btn: ['确认', '取消'],
                yes: function () {
                    let remark = $("#remark").val();
                    param.remark = remark;
                    let index = layer.load(1, {shade: [0.1, '#000']});
                    $.ajax({
                        url: '${ctx}/merchantStore/payEcdemicSwitchMerchantStore',
                        method: 'post',
                        data: param,
                        dataType: 'JSON',
                        success: function (res) {
                            layer.close(index);
                            layer.msg(res.msg, {
                                icon: res.resultCode == 1 ? 1 : 2
                            });
                        }
                    })
                }
                , btn2: function (index, layero) {
                    $(data.elem).prop('checked', !data.elem.checked)
                    layui.form.render();//刷新表格
                    layer.msg('您点击了拒绝！');
                    layer.close(index);
                },
                cancel: function () {
                    $(data.elem).prop('checked', !data.elem.checked)
                    layui.form.render();//刷新表格
                    layer.msg('您点击了拒绝！');
                    layer.close(index);
                }
            });
        }

        $(".check-btn").click(function (event) {
            $(".check-btn").each(function (index, e) {
                $(e).removeClass("layui-border-green")
            })
            $(event.target).addClass("layui-border-green");
            let val = $(event.target).data().v;
            let date = new Date();
            if (val == 1) {
                let dateTime = dateChange(0, dateFormat(fmt, date));
                $("#date1").val(dateTime);
                $("#date2").val(dateTime);
            } else if (val == 2) {
                let dateTime = dateChange(-1, dateFormat(fmt, date));
                $("#date1").val(dateTime);
                $("#date2").val(dateTime);
            } else {
                let dateTime = dateChange(-1, dateFormat(fmt, date));
                $("#date1").val("");
                $("#date2").val(dateTime);
            }
            $("#condition").val(val);
            var params = serialize($('#form1'));
            table.reload('mercTradeData', {
                where: params
                , page: {
                    size: 10
                    , current: 1
                }
            });
        })

        function dateFormat(fmt, date) {
            let ret;
            const opt = {
                "Y+": date.getFullYear().toString(),        // 年
                "m+": (date.getMonth() + 1).toString(),     // 月
                "d+": date.getDate().toString(),            // 日
                "H+": date.getHours().toString(),           // 时
                "M+": date.getMinutes().toString(),         // 分
                "S+": date.getSeconds().toString()          // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            };
            for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                }
                ;
            }
            ;
            return fmt;
        }

        function dateChange(num = 1, date = false) {
            if (!date) {
                date = new Date();//没有传入值时,默认是当前日期
                date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
            }
            date += " 00:00:00";//设置为当天凌晨12点
            date = Date.parse(new Date(date)) / 1000;//转换为时间戳
            date += (86400) * num;//修改后的时间戳
            var newDate = new Date(parseInt(date) * 1000);//转换为时间
            return newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate();
        }

        function getPreMonth(date) {
            var arr = date.split('-');
            var year = arr[0]; //获取当前日期的年份
            var month = arr[1]; //获取当前日期的月份
            var day = arr[2]; //获取当前日期的日
            var days = new Date(year, month, 0);
            days = days.getDate(); //获取当前日期中月的天数
            var year2 = year;
            var month2 = parseInt(month) - 1;
            if (month2 == 0) {
                year2 = parseInt(year2) - 1;
                month2 = 12;
            }
            var day2 = day;
            var days2 = new Date(year2, month2, 0);
            days2 = days2.getDate();
            if (day2 > days2) {
                day2 = days2;
            }
            if (month2 < 10) {
                month2 = '0' + month2;
            }
            var t2 = year2 + '-' + month2 + '-' + day2;
            return t2;
        }
    });
</script>
</body>
</html>
