<template>
    <div class="container">
        <section class="content-header">
            <h1 id="itemTitle"></h1>
        </section>
        <section class="content">
            <div id="toolbar">
                <div class="summary col-sm-12">
                    <div class="col-sm-2 width30">
                        <span>今日实际奖池金额：</span>
                        <span><span class="dayGoldNum">0</span><button class="btn btn-primary editGoldNum marginLeft20"
                                type="button" goldType="1" title="今日实际奖池金额">编辑</button></span>
                    </div>
                    <div class="col-sm-2 width30">
                        <span>实际奖池默认金额：</span>
                        <span><span class="dayDefGoldNum">0</span><button class="btn btn-primary editGoldNum marginLeft20"
                                type="button" goldType="2" title="实际奖池默认金额">编辑</button></span>
                    </div>
                    <div class="col-sm-2 width30">
                        <span>展示奖池累计金币值：</span>
                        <span><span class="dayShowGoldNum">0</span><button class="btn btn-primary editGoldNum marginLeft20"
                                type="button" goldType="3" title="展示奖池累计金币值">编辑</button></span>
                    </div>
                </div>

                <div class="col-sm-1">

                </div>

                <div class="col-sm-12">
                    <input type="hidden" value="1" id="prizeTypeVal" />
                    <form action="" id="searchForm" method="POST">

                        奖池类型：<select name="prizeType" id="prizeType" data-btn-class="btn btn-warning">
                            <option value="1">普通奖池</option>
                            <option value="2">白名单奖池</option>
                        </select>

                    </form>
                    <button class="btn btn-primary" id="searchBtn">搜索</button>
                    <button class="btn btn-primary" id="add">添加奖品</button>
                </div>

                <div class="summary col-sm-12">
                    <div class="col-sm-2">
                        <span>奖池类型：</span>
                        <span class="prizeTypeNum"></span>
                    </div>
                    <div class="col-sm-2">
                        <span>奖品种类数：</span>
                        <span class="typeNum" whiteNum="0" ordinaryNum="0">0</span>
                    </div>
                    <div class="col-sm-2">
                        <span>总期望值(金币)：</span>
                        <span class="dayDisplayGoldNum" whiteNum="0" ordinaryNum="0" ratioValue="0"
                            whiteRatioValue="0">0</span>
                    </div>
                </div>
            </div>
            <div id="table"></div>
        </section>

        <!-- 添加弹窗 -->
        <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel">

            <div class="modal-dialog" role="document">
                <div class="modal-content">

                    <div class="modal-header">
                        <h4 class="modal-title" id="addModalLabel">添加奖品</h4>
                    </div>

                    <div class="modal-body">
                        <form action="" class="form-horizontal" id="addForm">
                            <!-- 奖品个数 -->
                            <div class="form-group">
                                <label class="col-sm-3 control-label">奖池类型：</label>
                                <div class="col-sm-8 prizeTypeNum"></div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">奖品等级：</label>
                                <div class="col-sm-6">
                                    <select name="level" id="level" data-btn-class="btn btn-warning">
                                        <option value="1">一级</option>
                                        <option value="2">二级</option>
                                        <option value="3">三级</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-3 control-label">选择奖品：</label>
                                <div class="col-sm-8">
                                    <select name="goldPrize" id="goldPrize" data-btn-class="btn btn-warning">

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

                            <!-- 中奖率 -->
                            <div class="form-group">
                                <label class="col-sm-3 control-label">中奖率：</label>

                                <div class="col-sm-8">
                                    <input type="text" id="winningRate" name="winningRate"
                                        class="validate[required,max[100]]" placeholder="当前概率不得超过100">%
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">操作人：</label>

                                <div class="col-sm-8">
                                    <input type="text" id="operator" name="operator" class="validate[required]"
                                        placeholder="请输入你的名字">
                                </div>
                            </div>

                        </form>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button class="btn btn-primary" type="button" id="addSave">保存</button>
                    </div>
                </div>
            </div>

        </div>

        <!-- 编辑弹窗 -->
        <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title" id="editModalLabel">编辑奖品</h4>
                    </div>

                    <div class="modal-body">
                        <form action="" class="form-horizontal" id="editForm">
                            <input type="hidden" id="editId" value="">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">中奖率：</label>

                                <div class="col-sm-8">
                                    <input type="text" id="occupationRatio" name="occupationRatio"
                                        class="validate[required,max[100]]" placeholder="当前概率不得超过100">%
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button class="btn btn-primary" type="button" id="editSave">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑弹窗 -->
    <div class="modal fade" id="editGoldNumModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="editGoldNumLabel"></h4>
                </div>

                <div class="modal-body">
                    <form action="" class="form-horizontal" id="editGoldNumForm">
                        <div class="form-group">
                            <label class="col-sm-3 control-label">金额数量：</label>
                            <input type="hidden" value="" id="goldNumType" />
                            <div class="col-sm-8">
                                <input type="text" id="goldNum" name="goldNum" class="validate[required,min[0]]">
                            </div>
                        </div>
                    </form>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button class="btn btn-primary" type="button" id="editGoldNum">保存</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import TableHelper from '@/utils/bootstrap-table-helper';

var ACCURACY = 1000; // 小数点精度
var RATIO_PART = 100000; // 概率换算单位
export default {
    name: "PrizeGoldPoolAdminView",
    setup() {
        return {};
    },
    created() {
        this.$nextTick(function () {
            this.initData();
        });
    },
    methods: {
        initData() {
            $(function () {

                getToolVal();
                $('#table').bootstrapTable('destroy');
                $('#table').bootstrapTable({
                    columns: [
                        { field: 'sel', title: '', align: 'center', checkbox: true, width: '1%', valign: 'middle' },
                        { field: 'id', title: '', align: 'center', valign: 'middle', width: '1%', visible: false },
                        {
                            field: 'sel2', title: '编号', align: 'center', valign: 'middle', width: '5%',
                            formatter: function (value, row, index) {
                                //获取每页显示的数量
                                var pageSize = $('#table').bootstrapTable('getOptions').pageSize;
                                //获取当前是第几页
                                var pageNumber = $('#table').bootstrapTable('getOptions').pageNumber;
                                //返回序号，注意index是从0开始的，所以要加上1
                                return pageSize * (pageNumber - 1) + index + 1;
                            }
                        },
                        {
                            field: 'goldNum', title: '奖品', align: 'center', width: '5%', valign: 'middle',
                            formatter: function (val, row, index) {
                                return val + "金币";

                            }
                        },
                        {
                            field: 'level', title: '奖品等级', align: 'center', width: '15%', valign: 'middle',
                            formatter: function (val, row, index) {
                                if (val == 1) {
                                    return "一级";
                                } if (val == 2) {
                                    return "二级";
                                } else {
                                    return "三级";
                                }
                            }
                        },
                        {
                            field: '', title: '中奖率', align: 'center', valign: 'middle', width: '10%', formatter: function (val, row, index) {
                                if (row.goldPrizeId == 1) {
                                    return "默认奖品"
                                }
                                return row.occupationRatio / ACCURACY + '%';
                            }
                        },
                        {
                            field: '', title: '期望值', align: 'center', valign: 'middle', width: '10%', formatter: function (val, row, index) {
                                if (row.goldPrizeId == 1) {
                                    if (row.prizePoolType == 1) {
                                        return (Number($(".dayDisplayGoldNum").attr("ratioValue"))).toFixed(2);
                                    } else {
                                        return (Number($(".dayDisplayGoldNum").attr("whiteRatioValue"))).toFixed(2);
                                    }
                                }
                                var key = row.prizeId;
                                return (Number(row.occupationRatio * row.goldNum / RATIO_PART)).toFixed(2);
                            }
                        },
                        { field: 'usePrizeNum', title: '今日被抽中数量', align: 'center', valign: 'middle', width: '10%' },
                        {
                            field: 'updateTime',
                            title: '修改时间',
                            align: 'center',
                            valign: 'middle',
                            width: '10%',
                            formatter: function (val, row, index) {
                                if (val) {
                                    var date = new Date(val);
                                    return date.format("yyyy-MM-dd hh:mm:ss");
                                } else {
                                    return '-';
                                }
                            }
                        },
                        { field: 'operator', title: '操作人', align: 'center', width: '5%', valign: 'middle' },
                        {
                            field: 'tmp',
                            title: '操作',
                            align: 'center',
                            width: '10%',
                            valign: 'middle',
                            formatter: function (val, row, index) {
                                var key = row.id;
                                if (row.goldPrizeId != 1) {
                                    var str = "<button class='btn btn-sm btn-success opt-edit' style='margin-right: 4px;' data-id=" + key + ">编辑</button>";
                                    str += "<button class='btn btn-sm btn-success opt-del' style='margin-right: 4px;' data-id=" + key + ">下架</button>"
                                    return str;
                                }

                            }
                        }
                    ],
                    cache: false,
                    striped: true,
                    showRefresh: false,
                    pageSize: 10,
                    pagination: true,
                    pageList: [1, 10, 20, 30, 50],
                    search: false,
                    sidePagination: 'server',
                    queryParamsType: 'undefined',
                    queryParams: function queryParams(params) {
                        var param = {
                            pageNumber: params.pageNumber,
                            pageSize: params.pageSize,
                            prizeType: $('#prizeType').val()
                        };
                        return param;
                    },
                    uniqueId: 'id',
                    toolbar: '#toolbar',
                    url: '/admin/prizeGoldPool/getAll',
                    onLoadSuccess: function (data) {
                        console.log('load success');
                    },
                    onLoadError: function () {
                        console.log('load fail');
                    }
                });



                // 查询按钮
                $('#searchBtn').click(function () {
                    TableHelper.doRefresh('#table');
                    search();
                });

                function search() {
                    $("#prizeTypeVal").val($("#prizeType").val());
                    if (parseInt($("#prizeType").val()) == 1) {
                        $(".prizeTypeNum").html("普通奖池");
                        $(".typeNum").html($(".typeNum").attr("ordinaryNum"));
                        $(".dayDisplayGoldNum").html($(".dayDisplayGoldNum").attr("ordinaryNum"));
                    } else {
                        $(".prizeTypeNum").html("白名单奖池");
                        $(".typeNum").html($(".typeNum").attr("whiteNum"));
                        $(".dayDisplayGoldNum").html($(".dayDisplayGoldNum").attr("whiteNum"));
                    }
                }

                function getGoldPrizeList(type) {
                    debugger;
                    $('#goldPrize').html("");
                    $.get('/admin/prizeGoldPool/prizeList', { type: type }, function (res) {
                        if (res.code == 200) {
                            var j = 0;
                            for (var i = 0; i < res.data.length; i++) {
                                var $opt = $('<option value=""></option>');
                                $('#goldPrize').append($opt);
                                if (res.data[i].level != 1) {
                                    $opt.hide();
                                } else {
                                    if (j == 0) {
                                        $opt.attr("selected", true);
                                        j = 1;
                                    }
                                }
                                $opt.attr('value', res.data[i].id);
                                $opt.attr("class", res.data[i].level)
                                $opt.html(res.data[i].goldNum + "金币");
                            }
                            if (j == 0) {
                                $('#goldPrize').val("");
                            }

                        }
                    })
                }

                function getToolVal() {
                    //页面第一次加载,默认为普通奖池
                    $(".prizeTypeNum").html("普通奖池");
                    $.post('/admin/prizeGoldPool/panelVal', function (res) {
                        if (res.code == 200) {
                            $(".dayGoldNum").html(res.data.remainGoldNum);
                            $(".dayDefGoldNum").html(res.data.defGoldNum);
                            $(".dayShowGoldNum").html(res.data.showGoldNum);

                            $(".typeNum").html(res.data.prizeNum);
                            $(".dayDisplayGoldNum").html(res.data.expectedValue);

                            $(".typeNum").attr("whiteNum", res.data.whitePrizeNum);
                            $(".dayDisplayGoldNum").attr("whiteNum", res.data.whiteExpectedValue);

                            $(".typeNum").attr("ordinaryNum", res.data.prizeNum);
                            $(".dayDisplayGoldNum").attr("ordinaryNum", res.data.expectedValue);

                            $(".dayDisplayGoldNum").attr("ratioValue", res.data.ratioValue);
                            $(".dayDisplayGoldNum").attr("whiteRatioValue", res.data.whiteRatioValue);
                        }
                    })
                }

                $("#level").change(function () {
                    debugger;
                    var level = $(this).children('option:selected').val();
                    var i = 0;
                    $("#goldPrize option").each(function () {
                        $(this).attr("selected", false);
                        if ($(this).hasClass(level)) {
                            $(this).show();
                            if (i == 0) {
                                $(this).attr("selected", true);
                                i = 1;
                            }
                        } else {
                            $(this).hide();
                        }
                    })
                    if (i == 0) {
                        $('#goldPrize').val("");
                    }
                });

                $('.editGoldNum').on('click', function () {
                    debugger;
                    $("#goldNum").val($(this).parent().find(".dayGoldNum").eq(0).html());
                    $('#editGoldNumLabel').val($(this).attr("title"));
                    $("#goldNumType").val($(this).attr("goldType"));
                    $('#editGoldNumModal').modal('show');
                })

                $('#editGoldNum').on('click', function () {
                    if ($('#editGoldNumForm').validationEngine('validate')) {
                        $.ajax({
                            type: 'post',
                            url: '/admin/prizeGoldPool/editGoldNum.action',
                            dataType: 'json',
                            data: {
                                goldNumType: $('#goldNumType').val(),
                                goldNum: $('#goldNum').val()
                            },
                            success: function (res) {
                                if (res.code == 200) {
                                    $("#editGoldNumModal").modal('hide');
                                    $("#tipMsg").text("修改成功");
                                    $("#tipModal").modal('show');

                                    if (parseInt($('#goldNumType').val()) == 1) {
                                        $(".dayGoldNum").html($('#goldNum').val());
                                    }
                                    if (parseInt($('#goldNumType').val()) == 2) {
                                        $(".dayDefGoldNum").html($('#goldNum').val());
                                    }
                                    if (parseInt($('#goldNumType').val()) == 3) {
                                        $(".dayShowGoldNum").html($('#goldNum').val());
                                    }

                                } else {
                                    $("#tipMsg").text("修改失败，错误码：" + res.code);
                                    $("#tipModal").modal('show');
                                }
                            }
                        })
                    }
                })

                $("#add").on('click', function () {
                    $("#level").val(1);
                    getGoldPrizeList($("#prizeType").val())
                    $("#addModal").find(".prizeTypeNum").html($("#prizeType").find("option:selected").text());
                    $("#prizeTypeVal").val($("#prizeType").val());
                    $("#winningRate").val("");
                    $("#operator").val("");
                    $('#addModal').modal('show');
                })

                $('#addSave').on('click', function () {
                    if ($('#addForm').validationEngine('validate')) {
                        if (parseFloat($('#winningRate').val()) % ACCURACY >= ACCURACY) {
                            // 小数位超过3位则不允许设置
                            $('#tipMsg').text('概率最多只允许设置到小数点后3位');
                            $('#tipModal').modal('show');
                            return;
                        }
                        var reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
                        if (!reg.test($('#winningRate').val())) {
                            $('#tipMsg').text('概率只能是数值');
                            $('#tipModal').modal('show');
                            return;
                        }

                        $.ajax({
                            type: 'post',
                            url: '/admin/prizeGoldPool/savePrizeGoldPool.action',
                            dataType: 'json',
                            data: {
                                prizeTypeVal: $("#prizeTypeVal").val(),
                                goldPrizeId: $('#goldPrize').val(),
                                winningRate: $('#winningRate').val() * ACCURACY,
                                operator: $('#operator').val()
                            },
                            success: function (res) {
                                if (res.code == 200) {
                                    $("#addModal").modal('hide');
                                    $("#tipMsg").text("保存成功");
                                    $("#tipModal").modal('show');
                                    TableHelper.doRefresh("#table");
                                    getToolVal();
                                    search();
                                } else {
                                    $("#tipMsg").text("保存失败," + res.message);
                                    $("#tipModal").modal('show');
                                }
                            }
                        })
                    }
                });

                $('#table').on('click', '.opt-edit', function () {
                    var id = $(this).data('id');
                    if (id == 'undefined' || !id) {
                        return;
                    }
                    var data = $('#table').bootstrapTable('getRowByUniqueId', id);
                    $("#occupationRatio").val(data.occupationRatio / ACCURACY);
                    $("#editId").val(id);
                    $('#editModal').modal('show');
                });

                $('#editSave').on('click', function () {
                    if ($('#editForm').validationEngine('validate')) {
                        $.ajax({
                            type: 'post',
                            url: '/admin/prizeGoldPool/editPrizeGoldPollRatio.action',
                            dataType: 'json',
                            data: {
                                id: $('#editId').val(),
                                occupationRatio: $('#occupationRatio').val() * ACCURACY
                            },
                            success: function (res) {
                                if (res.code == 200) {
                                    $("#editModal").modal('hide');
                                    $("#tipMsg").text("保存成功");
                                    $("#tipModal").modal('show');
                                    TableHelper.doRefresh("#table");
                                    getToolVal();
                                    search();
                                } else {
                                    $("#tipMsg").text("保存失败," + res.message);
                                    $("#tipModal").modal('show');
                                }
                            }
                        })
                    }
                });

                $('#table').on('click', '.opt-del', function () {
                    var id = $(this).data('id');
                    if (id == 'undefined' || !id) {
                        $("#tipMsg").text("id参数有误");
                        $("#tipModal").modal('show');
                        return;
                    }

                    if (confirm("确认下架该奖品吗？")) {
                        $.ajax({
                            type: "post",
                            url: "/admin/prizeGoldPool/delPrize.action",
                            data: {
                                id: id
                            },
                            dataType: "json",
                            success: function (json) {
                                if (json.code == 200) {
                                    $("#tipMsg").text("已下架该奖品");
                                    $("#tipModal").modal('show');
                                    TableHelper.doRefresh("#table");
                                    getToolVal();
                                    search();
                                } else {
                                    $("#tipMsg").text("下架失败[" + id + "]," + json.msg);
                                    $("#tipModal").modal('show');
                                }
                            }
                        });
                    }
                })
            })
        }
    },
};
</script>

<style scoped>
.summary {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 50px;
}

.summary div {
    margin-right: 20px;
    display: flex;
    justify-content: flex-between;
    align-items: center;
    height: 100%;
}

#attention {
    color: lightgray;
}

.content {
    height: auto;
}

#searchForm {
    display: inline-block;
}

#btnSearch {
    margin-left: 4px;
}

#toolbar input,
#toolbar select {
    margin-left: 4px;
    margin-right: 4px;
}

.width30 {
    width: 30%;
}

.marginLeft20 {
    margin-left: 20px;
}</style>