<link rel="stylesheet" href="<?php echo base_url();?>public/plugins/datatables/jquery.dataTables.min.css">
<link rel="stylesheet" href="<?php echo base_url();?>public/plugins/datatables/extensions/Responsive/css/dataTables.responsive.css">
<div class="content_wrapper">

    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-12">
                <div class="tabs-container">
                    <ul class="nav nav-tabs">
                        <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">兑换码列表</a></li>
                        <li><a data-toggle="tab" href="#tab-2" aria-expanded="false">兑换记录</a></li>
                    </ul>
                </div>
                <div class="tab-content">
                    <div id="tab-1" class="tab-pane active">
                        <div class="panel-body">
                            <div class="ibox-title" style="border-style: none">
                                <button type="button" class="btn btn-success" data-toggle="modal" data-target="#actionCode" onclick="openNewDialog()">创建兑换码</button>
                                <span style="margin-left: 10%">
                                    <input type="text" placeholder="输入兑换码查询" name="redeemCode" id="redeemCode"/>
                                    <button id="queryAppointCode" class="btn btn-primary">查询</button>
                                </span>
                            </div>
                            <hr style="margin-top: 10px">
                            <div class="ibox float-e-margins">
                                <div class="ibox-content" id="firstTable" style="padding: 0;">
                                    <div class="table-responsive">
                                        <table id="exchangeTable" class="table table-striped table-bordered table-hover" style="width: 99%">
                                            <thead>
                                            <tr>
                                                <th style="width: 60px">ID</th>
                                                <th style="width: 80px">兑换码</th>
                                                <th>奖励 <button onclick="refreshRewardAll()" style="height: 23px;font-size: 12px;float: right" class="btn btn-success">刷新</button></th>
                                                <th>状态</th>
                                                <th style="width: 60px">限制人数</th>
                                                <th style="width: 70px">已领奖人数</th>
                                                <th>指定用户</th>
                                                <th style="width: 120px">创建时间</th>
                                                <th style="width: 120px">过期时间</th>
                                                <th style="width: 120px">注册时间范围(小时)</th>
                                                <th>备注</th>
                                                <th>祝福语模板</th>
                                                <th>弹窗邮件模板</th>
                                            </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="tab-2" class="tab-pane">
                        <div class="panel-body">
                            <div class="ibox-title" style="border-style: none">
                                <span>
                                    <input type="text" placeholder="输入兑换码查询" name="searchRedeemCode" id="searchRedeemCode"/>
                                    <input type="number" placeholder="输入UID查询" name="searchUid" id="searchUid"/>
                                    <button id="queryAppointSearch" class="btn btn-primary">查询</button>
                                </span>
                            </div>
                            <hr style="margin-top: 10px">
                            <div class="ibox float-e-margins">
                                <div class="ibox-content" id="firstTable" style="padding: 0;">
                                    <div class="table-responsive">
                                        <table id="exRecordTable" class="table table-striped table-bordered table-hover" style="width: 99%">
                                            <thead>
                                            <tr>
                                                <th style="width: 60px">ID</th>
                                                <th>兑换码</th>
                                                <th>UID</th>
                                                <th>兑换时间</th>
                                            </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>

</div>

<!-- 操作金币弹出框 -->
<div class="modal fade" id="actionCode" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog"  style="top: 10%;width: 50%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">创建兑换码</h4>
            </div>
            <form class="form-horizontal " role="form" id="redeemCodeForm"  method="post"   data-callBack="updatecode">
                <div class="modal-body">

                    <div class="form-group">
                        <label class="col-sm-3 control-label">兑换码:</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control col-sm-4" placeholder="字符长度6~12,不填写默认生成6位纯数字兑换码" name="code">
                        </div>
                        <div class="col-sm-2">
                            <button type="button" class="btn btn-outline btn-primary" onclick="createPureNumberCode(6)">生成6位纯数字兑换码</button>
                        </div>
                        <div class="col-sm-2" style="margin-left: 20px">
                            <button type="button" class="btn btn-outline btn-primary" onclick="createCode(6)">生成6位字母数字兑换码</button>
                        </div>
                    </div>

                    <div class="form-group addOrDelControl" id="vipDiv">
                        <label class="col-sm-3 control-label">奖励道具:</label>
                        <div class="col-sm-9">
                            <label class="select-inline">
                                <table class="col-sm-12">
                                    <tr>
                                        <td class="formPropsRewardsTag" data-value='[]'></td>
                                        <td class="text-right">
                                            <button type="button"
                                                    class="btn btn-outline btn-success"
                                                    onclick="propsJs.initEdit(this, 'formPropsRewardsTag')">
                                                奖励配置
                                            </button>
                                        </td>
                                    </tr>
                                </table>
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">限制人数:</label>
                        <div class="col-sm-9">
                            <input type="number" class="form-control" placeholder="领取兑换码人数上限" name="limitnum">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-3 control-label">注册时间范围(小时):</label>
                        <div class="input-group col-sm-9" style="padding-left:15px">
                            <input type="text" style="text-align: center" class="form-control" name="register_time_min" value="0">
                            <span class="input-group-addon">-</span>
                            <input type="text" style="text-align: center" class="form-control" name="register_time_max" value="0">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">祝福语模板:</label>
                        <div class="col-sm-4">
                            <select name="blessingId" class="form-control">
                                <option value="0">选择祝福语模板</option>
                                <?php foreach ($blessings as $blessing){?>
                                    <option value="<?=$blessing['iid']?>"><?=$blessing['title']?></option>
                                <?php }?>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-3 control-label">弹窗邮件模板:</label>
                        <div class="col-sm-4">
                            <select name="popUpId" class="form-control">
                                <option value="0">不弹窗</option>
                                <?php foreach ($mailList as $row){?>
                                    <option value="<?=$row['id']?>"><?=$row['title']?></option>
                                <?php }?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">过期时间:</label>
                        <div class="col-sm-4">
                            <input type="text" id="test-limit2" class="form-control" placeholder="兑换码过期日期" name="datetime">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-3 control-label">备注：</label>
                        <div class="col-sm-9">
                            <textarea name="remake" class="form-control" rows="4"></textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">限制用户类型</label>
                        <div class="col-sm-9">
                            <label class="radio-inline">
                                <input type="radio" name="userType" class="typeRadio" value="0" checked> 所有
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="userType" class="typeRadio" value="1"> FB
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="userType" class="typeRadio" value="2"> 游客
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="userType" class="typeRadio" value="3"> VIP
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="userType" class="typeRadio" value="4"> 指定
                            </label>
                        </div>
                    </div>
                    <div class="form-group" id="userLimitDiv" style="display: none">
                        <label class="col-sm-3 control-label">用户限定*: </label>
                        <div class="col-sm-9">
                            <textarea id="userIds" rows="4" onkeyup="checkExport()" class="form-control" placeholder="UID使用换行分割" name="userLimit"><?php echo $info['userLimit']??'';?></textarea>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary " onclick="submitForm()">提交</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="<?php echo base_url();?>public/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url();?>public/plugins/datatables/extensions/Responsive/js/dataTables.responsive.min.js"></script>
<script type="text/javascript">
    laydate.render({
        elem: '#test-limit2'
        ,min: 0
        ,max: 999
    });
    //限定可选时间
    laydate.render({
        elem: '#test-limit3'
        ,type: 'time'
        // ,min: '09:30:00'
        // ,max: '17:30:00'
        ,btns: ['clear', 'confirm']
    });
</script>
<script type="text/javascript">
    let $blessingsMap = {};
    <?php foreach ($blessings as $blessing){?>
    $blessingsMap[<?=$blessing['iid']?>] = '<?=$blessing['title']?>'
    <?php }?>
    let $mailMap = {};
    <?php foreach ($mailList as $row){?>
        $mailMap[<?=$row['id']?>] = '<?=$row['title']?>'
    <?php }?>
    propsJs.initTag('formPropsRewardsTag', SCENE_EXCHANGECODE)

    $('.addOrDelControl').on("click",'.deleteParent',function(){
        $(this).parent().parent().remove();
    });
    $(".typeRadio").change(function(){
        var userType = $(this).val();
        if(userType == 4){
            $("#userLimitDiv").show(300);
        }else{
            $("#userLimitDiv").hide(300);
        }
    });
    function updatecode(response) {
        console.log(response);
        // location.reload();
    }
    function checkExport() {
        var textarea = $('#userIds').val();
        textarea = textarea.replace(/[^0-9\n]/g,"")
        textarea = textarea.replace(/[^0-9\n]/g,"")
        textarea = textarea.replace(/\n\n/g,"\n")
        textarea = textarea.replace(/^\n/g,"")
        // textarea = textarea.replace(/[A-Z]/g,"")
        $('#userIds').val(textarea);
    }

    $(function () {
        var exchangeTable = $("#exchangeTable").DataTable({
            "paging": true,
            "select": true,
            "processing": true,
            "serverSide": true,
            "aLengthMenu": [5, 10, 25, 50, 100, 500],
            "language": {
                'lengthMenu': '每页显示 _MENU_ 记录',
                'zeroRecords': '没有数据',
                'info': ' 第_PAGE_ 页/ _PAGES_页，共 _TOTAL_ 条',
                'infoEmpty': '没有符合条件的记录',
                'search': '查找',
                'infoFiltered': '(从  _MAX_ 条记录中过滤)',
                'paginate': { "first":  "首页 ", "last": "末页", "next": "下一页","previous": "上一页"}

            },
            "ajax": {
                url: rootPath + "exchange/listData",
                type:"post",
                //增加参数查询参数
                data:function(data){
                    setTimeout(() => {
                        propsJs.initTag('tablePropsRewardsTag', SCENE_EXCHANGECODE)
                    }, 1000)
                }
            },
            "lengthChange": true,
            "searching": false,
            "ordering": false,
            "info": true,
            "autoWidth": false,
            "columns": [
                {"data": "id"},
                {"data": "code"},
                {
                    "data": "rwd", render: function (data) {
                        return `<table><tr><td class="tablePropsRewardsTag" data-name='test' data-value='${data}'></td></tr></table>`;
                    }
                },
                {"data": "status"},
                {"data": "limit"},
                {"data": "rwdNum"},
                {
                    "data": "userLimit", render: function (data) {
                        return '<textarea id="textareaId" rows="4" readonly class="form-control" placeholder="使用换行分割" name="userLimit">' + data + '</textarea>';
                    }
                },
                {"data": "time"},
                {"data": "expire"},
                {"data": "registerTimeRange"},
                {"data": "remake"},
                {
                    "data": "blessingId", render: function (data) {
                        console.log(data, $blessingsMap[data])
                        return $blessingsMap[data] ?? '-';
                    }
                },
                {
                    "data": "pop_up_id", render: function (data) {
                        console.log(data, $mailMap[data])
                        return $mailMap[data] ?? '-';
                    }
                },
            ]
        });

        //当点击search按钮时按条件重新加载数据
        $("#searchBtn").click(function(){
            if($("#exchangeForm").valid()) {
                exchangeTable.ajax.reload();
            }
        });

        //当点击search按钮时按条件重新加载数据
        $("#queryAppointCode").click(function () {
            const redeemCode = $('#redeemCode').val();
            exchangeTable.ajax.url("exchange/listData/" + redeemCode)

            exchangeTable.ajax.reload();
            setTimeout(() => {
                propsJs.initTag('tablePropsRewardsTag', SCENE_EXCHANGECODE)
            }, 1000)
        });


        const exRecordTable = $("#exRecordTable").DataTable({
            "paging": true,
            "select": true,
            "processing": true,
            "serverSide": true,
            "aLengthMenu": [5, 10, 25, 50, 100, 500],
            "language": {
                'lengthMenu': '每页显示 _MENU_ 记录',
                'zeroRecords': '没有数据',
                'info': ' 第_PAGE_ 页/ _PAGES_页，共 _TOTAL_ 条',
                'infoEmpty': '没有符合条件的记录',
                'search': '查找',
                'infoFiltered': '(从  _MAX_ 条记录中过滤)',
                'paginate': {"first": "首页 ", "last": "末页", "next": "下一页", "previous": "上一页"}
            },
            "ajax": {
                url: rootPath + "exchange/logData",
                type: "post",
                //增加参数查询参数
                data: function (data) {

                }
            },
            "lengthChange": true,
            "searching": false,
            "ordering": false,
            "info": true,
            "autoWidth": false,
            "columns": [
                {"data": "id"},
                {"data": "code"},
                {"data": "uid"},
                {"data": "time"},
            ]
        });
        //当点击search按钮时按条件重新加载数据
        $("#queryAppointSearch").click(function () {
            const searchCode = $('#searchRedeemCode').val();
            const searchUid = $('#searchUid').val();

            exRecordTable.ajax.url("exchange/logData?code=" + searchCode + "&uid=" + searchUid)
            exRecordTable.ajax.reload();
        });
    });

    function openNewDialog() {
        laydate.render({
            elem: '#test-limit2'
            , type: 'datetime'
            , min: 0
            , max: 999
        })
    }

    function createCode(len) {
        let code = ""
        let randBaseArr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
            "X", "Y", "Z", 1, 2, 3, 4, 5, 6, 7, 8, 9]
        code += ArrayRand(randBaseArr)

        randBaseArr.push(0)
        for (let i = 0; i < len - 1; i++) {
            code += ArrayRand(randBaseArr)
        }

        $('input[name="code"]').val(code)
    }

    function createPureNumberCode(len) {
        let code = ""
        let randBaseArr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        code += ArrayRand(randBaseArr)

        randBaseArr.push(0)
        for (let i = 0; i < len - 1; i++) {
            code += ArrayRand(randBaseArr)
        }
        $('input[name="code"]').val(code)
    }

    function submitForm() {
        const data = $('#redeemCodeForm').toObject()
        data['props'] = $('.formPropsRewardsTag').data('value')
        console.log(data)
        $.ajax({
            url: rootPath + 'exchange/actionCreateCode',
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function (data) {
                if (data.ret == 0) {
                    location.reload();
                }
                alert(data.msg);
                // confirm(data.msg);
            },
            error: function (data) {
                alert(data.msg);
            }
        });
    }
    propsJs.initTag('tablePropsRewardsTag', SCENE_EXCHANGECODE)

    function refreshRewardAll(){
        propsJs.initTag('tablePropsRewardsTag', SCENE_EXCHANGECODE)
    }
</script>