<template>
    <section class="content">
        <div class="box box-primary">
            <section class="content-header">
                <h1 id="itemTitle"></h1>
            </section>

            <section class="content">

                <div class="header-section">
                    <div class="pool-line-name">常规线</div>
                    <div class="dataCount">
                        <p>
                            <span>奖池线包含组数：</span>
                            <span id="baseLineGroupCount"></span>
                        </p>
                        <p>
                            <span>奖池线礼物数：</span>
                            <span id="baseLinePrizeCount"></span>
                        </p>
                        <p>
                            <span>总礼物价值：</span>
                            <span id="baseLinePrizeValue"></span>
                        </p>
                        <p>
                            <span>单线比：</span>
                            <span id="baseLinePrizeRate"></span>
                        </p>
                        <p>
                            <button class="btn btn-primary js-deploy">发布</button>
                        </p>
                    </div>
                </div>

                <div class="group-table-section">
                    <div class="prize-group-wrapper js-normal-prize-group-wrapper">
                        <div class="header-wrapper">
                            <div class="title">普通礼物组</div>
                            <div class="right-content js-no-editing">
                                <div class="undeploy js-deploy-status">未发布</div>
                                <div class="action-btn-wrap"><button class="btn btn-primary js-edit-group"
                                        data-pool-type="1">编辑</button></div>
                            </div>
                            <div class="right-content right-content-edit js-editing">
                                <div class="action-btn-wrap">
                                    <button class="btn btn-primary js-add-prize" data-pool-type="1">新增</button>
                                    <button class="btn btn-danger js-save-edit" data-pool-type="1">保存</button>
                                    <button class="btn btn-default js-cancel-edit" data-pool-type="1">取消</button>
                                </div>
                            </div>
                        </div>
                        <div class="data-wrapper">
                            <div>
                                <span>礼物个数：</span>
                                <span class="js-prize-total-count"></span>
                            </div>
                            <div>
                                <span>礼物价值：</span>
                                <span class="js-prize-total-value"></span>
                            </div>
                        </div>
                        <table class="prize-group-table table table-hover table-striped">
                            <tr>
                                <th>名称</th>
                                <th>平台价值</th>
                                <th>个数</th>
                                <th>总价值</th>
                                <th>核算概率</th>
                                <th>展示概率</th>
                            </tr>
                            <!--                            <tr>-->
                            <!--                                <td>糖果</td>-->
                            <!--                                <td>1</td>-->
                            <!--                                <td>123</td>-->
                            <!--                                <td>21333</td>-->
                            <!--                                <td>21.223%</td>-->
                            <!--                                <td>21.221%</td>-->
                            <!--                            </tr>-->
                        </table>
                    </div>
                    <div class="prize-group-wrapper js-senior-prize-group-wrapper">
                        <div class="header-wrapper">
                            <div class="title">高级礼物组</div>
                            <div class="right-content js-no-editing">
                                <div class="undeploy js-deploy-status">未发布</div>
                                <div class="action-btn-wrap"><button class="btn btn-primary js-edit-group"
                                        data-pool-type="2">编辑</button></div>
                            </div>
                            <div class="right-content right-content-edit js-editing">
                                <div class="action-btn-wrap">
                                    <button class="btn btn-primary js-add-prize" data-pool-type="2">新增</button>
                                    <button class="btn btn-danger js-save-edit" data-pool-type="2">保存</button>
                                    <button class="btn btn-default js-cancel-edit" data-pool-type="2">取消</button>
                                </div>
                            </div>
                        </div>
                        <div class="data-wrapper">
                            <div>
                                <span>礼物个数：</span>
                                <span class="js-prize-total-count"></span>
                            </div>
                            <div>
                                <span>礼物价值：</span>
                                <span class="js-prize-total-value"></span>
                            </div>
                        </div>
                        <table class="prize-group-table table table-hover table-striped">
                            <tr>
                                <th>名称</th>
                                <th>平台价值</th>
                                <th>个数</th>
                                <th>总价值</th>
                                <th>核算概率</th>
                                <th>展示概率</th>
                            </tr>
                            <!--                        <tr>-->
                            <!--                            <td>糖果</td>-->
                            <!--                            <td>1</td>-->
                            <!--                            <td>123</td>-->
                            <!--                            <td>21333</td>-->
                            <!--                            <td>21.223%</td>-->
                            <!--                            <td>21.221%</td>-->
                            <!--                        </tr>-->
                        </table>
                    </div>
                </div>
            </section>
        </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">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">x</span>
                    </button>

                    <h4 class="modal-title" id="addModalLabel">新增礼物</h4>
                </div>

                <div class="modal-body">
                    <form action="" class="form-horizontal" id="addForm">
                        <!-- 礼物组 -->
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label">礼物组：</label>

                            <div class="col-sm-8">
                                <input type="hidden" id="prizePoolType" name="prizePoolType" disabled class=""
                                    placeholder="">
                                <input type="text" id="prizePoolName" name="prizePoolName" disabled class="" placeholder="">
                            </div>
                        </div>
                        <!-- 选择奖品 -->
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label">选择奖品：</label>
                            <div class="col-sm-8">
                                <select name="awardType" id="awardType" data-btn-class="btn btn-warning">
                                    <!-- <option value=""></option> -->
                                </select>

                                <select name="awardChoose" id="awardChoose" data-btn-class="btn btn-warning">
                                    <!-- <option value=""></option> -->
                                </select>
                            </div>
                        </div>
                        <!-- 奖品id -->
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label">奖品id：</label>

                            <div class="col-sm-8">
                                <input type="text" id="addPrizeId" name="addPrizeId" disabled class="" placeholder="">
                            </div>
                        </div>
                        <!-- 奖品个数 -->
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label">奖品个数：</label>

                            <div class="col-sm-8">
                                <input type="text" id="jackpotNumber" name="jackpotNumber" class=" validate[required]"
                                    placeholder="单行输入">
                            </div>
                        </div>

                    </form>
                </div>

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

    </div>
    <div class="modal fade" id="tipModal" 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">提示信息</h4>
                </div>
                <div class="modal-body" id="tipMsg"></div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="deployConfirmModal" 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">本次奖池线发布</h4>
                </div>
                <div class="modal-body">
                    <div>期望值 <span id="deployedPrizeRate"></span> 变为 <span id="currPrizeRate"></span></div>
                    <div>当前奖池线: <span id="currPoolLineId"></span></div>
                    <div>生效奖池线: <span id="activePoolLineId"></span></div>
                    <div>确认发布?</div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-default" type="button" id="deployCancel">取消发布</button>
                    <button class="btn btn-primary" type="button" id="deployConfirm">确认发布</button>
                </div>
            </div>
        </div>
    </div>
</template>

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

export default {
    name: "PoolItemAdminView",
    setup() {
        return {};
    },
    created() {
        this.$nextTick(function () {
            this.initData();
        });
    },
    methods: {
        initData() {
            $(function () {
                const POOL_TYPE = {
                    normal: 1,
                    senior: 2,
                }

                const POOL_NAME = {
                    1: '普通礼物组',
                    2: '高级礼物组',
                }

                // 展示概率的属性名
                const SHOWRATE_FIELD_NAME = "showRatio";
                const PRIZE_NUM_FIELD_NAME = "prizeNum";

                const RATE_SCALE = 1000;

                var prizeMap = {};
                var typeObj = {};

                function calculateStatisticsDatas(normalPrizeItems, seniorPrizeItems) {
                    let normalPrizeCount = 0;
                    let normalPrizeTotalValue = 0;
                    normalPrizeItems.forEach(item => {
                        normalPrizeCount += item.prizeNum;
                        normalPrizeTotalValue += item.prizeNum * item.platformValue
                    })
                    let seniorPrizeCount = 0;
                    let seniorPrizeTotalValue = 0;
                    seniorPrizeItems.forEach(item => {
                        seniorPrizeCount += item.prizeNum;
                        seniorPrizeTotalValue += item.prizeNum * item.platformValue
                    })

                    const totalPrizeCount = normalPrizeCount * seniorPrizeCount + seniorPrizeCount;
                    const totalPrizeValue = normalPrizeTotalValue * seniorPrizeCount + seniorPrizeTotalValue;

                    let prizeRate = 0;
                    if (totalPrizeCount != 0) {
                        prizeRate = parseFloat(totalPrizeValue) / (totalPrizeCount * 10)
                    }

                    return {
                        normalPrizeCount,
                        normalPrizeTotalValue,
                        seniorPrizeCount,
                        seniorPrizeTotalValue,
                        totalPrizeCount,
                        totalPrizeValue,
                        prizeRate,
                    };
                }

                function renderStatisticsDatas(statisticsDatas) {
                    $('#baseLineGroupCount').text(statisticsDatas.seniorPrizeCount);
                    $('#baseLinePrizeCount').text(statisticsDatas.totalPrizeCount);
                    $('#baseLinePrizeValue').text(statisticsDatas.totalPrizeValue);
                    $('#baseLinePrizeRate').text(statisticsDatas.prizeRate.toFixed(4));
                }

                function changeDateValue(poolType, propName, idx, inputValue) {
                    let prizeGroup;
                    if (poolType == POOL_TYPE.normal) {
                        prizeGroup = editingNormalPrizeGroup;
                    } else if (poolType == POOL_TYPE.senior) {
                        prizeGroup = editingSeniorPrizeGroup;
                    } else {
                        throw Error("unkonw prize pool type")
                    }
                    if (SHOWRATE_FIELD_NAME == propName) {
                        inputValue = (parseFloat(inputValue) * RATE_SCALE).toFixed(0);
                    } else if (PRIZE_NUM_FIELD_NAME == propName) {
                        inputValue = parseInt(inputValue);
                    }
                    prizeGroup.prizeItems[idx][propName] = inputValue;
                    // prizeGroup.isUndeploy = true;

                    reRenderPage({
                        normalPrizeGroup: editingNormalPrizeGroup,
                        seniorPrizeGroup: editingSeniorPrizeGroup,
                    })
                }

                function inputChanged(e) {
                    const propName = $(e.target).attr("name");
                    const idx = $(e.target).attr("data-idx");
                    const poolType = $(e.target).attr("data-pool-type");
                    const inputValue = e.target.value;
                    console.debug("input change", e, propName, idx, poolType, inputValue);
                    changeDateValue(poolType, propName, idx, inputValue);
                }

                function removePirzeItem(e) {
                    const idx = $(e.target).attr("data-idx");
                    const poolType = $(e.target).attr("data-pool-type");
                    let prizeList = editingNormalPrizeGroup.prizeItems;
                    if (poolType == POOL_TYPE.senior) {
                        prizeList = editingSeniorPrizeGroup.prizeItems;
                    }
                    if (prizeList.length == 1) {
                        $('#tipMsg').text('奖池中至少要有一个奖品');
                        $('#tipModal').modal('show');
                        return;
                    }
                    if (confirm("你确定要从奖池中移除该奖品吗？")) {
                        prizeList.splice(idx, 1);
                        console.debug("removePirzeItem prizeList", prizeList)
                        reRenderPage({
                            normalPrizeGroup: editingNormalPrizeGroup,
                            seniorPrizeGroup: editingSeniorPrizeGroup,
                        });
                    }
                }

                function renderPrizeGroup(poolType, prizeGroup, statisticsDatas, isEdit) {
                    let wrapperClassName = '.js-normal-prize-group-wrapper';
                    let totalPrizeCount = statisticsDatas.normalPrizeCount;
                    let totalPrizeValue = statisticsDatas.normalPrizeTotalValue;
                    if (poolType == POOL_TYPE.senior) {
                        wrapperClassName = '.js-senior-prize-group-wrapper';
                        totalPrizeCount = statisticsDatas.seniorPrizeCount;
                        totalPrizeValue = statisticsDatas.seniorPrizeTotalValue;
                    }
                    console.debug("wrapperClassName", wrapperClassName);
                    $(`${wrapperClassName} .js-prize-total-count`).text(totalPrizeCount);
                    $(`${wrapperClassName} .js-prize-total-value`).text(totalPrizeValue);
                    if (isEdit) {
                        console.debug("show editing action btns")
                        $(`${wrapperClassName} .js-no-editing`).hide();
                        $(`${wrapperClassName} .js-editing`).show();
                    } else {
                        console.debug("hide editing action btns")
                        $(`${wrapperClassName} .js-no-editing`).show();
                        $(`${wrapperClassName} .js-editing`).hide();
                        if (prizeGroup.isUndeploy) {
                            $(`${wrapperClassName} .js-deploy-status`).show();
                        } else {
                            $(`${wrapperClassName} .js-deploy-status`).hide();
                        }
                    }

                    const groupTableDom = $(`${wrapperClassName} .prize-group-table`);
                    $(`${wrapperClassName} .prize-group-table input`).unbind("change");
                    $(`${wrapperClassName} .prize-group-table .js-remove-item`).unbind("click");
                    groupTableDom.html("<thead><tr>\n" +
                        "                                <th>名称</th>\n" +
                        "                                <th>平台价值</th>\n" +
                        "                                <th>个数</th>\n" +
                        "                                <th>总价值</th>\n" +
                        "                                <th>核算概率</th>\n" +
                        // "                                <th>展示概率</th>\n" +
                        "                            </tr></thead>");
                    const prizeItems = prizeGroup.prizeItems;
                    groupTableDom.append("<tbody>")
                    prizeItems.forEach((item, idx) => {
                        let accountingRate = 0
                        if (poolType == POOL_TYPE.normal) {
                            // 普通礼物组核算概率 = 该礼物的个数*奖池线包含组数/礼物线总礼物数
                            accountingRate = parseFloat(item.prizeNum) * statisticsDatas.seniorPrizeCount / statisticsDatas.totalPrizeCount * 100;
                        } else if (poolType == POOL_TYPE.senior) {
                            // 高级礼物组核算概率 = 该礼物的个数/礼物线总礼物数
                            accountingRate = parseFloat(item.prizeNum) / statisticsDatas.totalPrizeCount * 100;
                        }
                        const tds = [];
                        if (isEdit) {
                            tds.push(`<td><i class="glyphicon glyphicon-remove js-remove-item" data-idx="${idx}" data-pool-type="${poolType}"></i>${item.prizeName}</td>`);
                        } else {
                            tds.push(`<td>${item.prizeName}</td>`)
                        }
                        tds.push(`<td>${item.platformValue}</td>`);
                        if (isEdit) {
                            tds.push(`<td><input name="prizeNum" data-idx="${idx}" data-pool-type="${poolType}" value="${item.prizeNum}"></td>`)
                        } else {
                            tds.push(`<td>${item.prizeNum}</td>`)
                        }
                        tds.push(`<td>${item.prizeNum * item.platformValue}</td>`);
                        tds.push(`<td>${accountingRate.toFixed(3)}%</td>`);
                        // if (isEdit) {
                        //     let disabled = false
                        //     if (poolType == POOL_TYPE.normal && idx == 0) {
                        //         disabled = true;
                        //     }
                        //     tds.push(`<td><input ${disabled ? "disabled" : ""} name="showRatio" data-idx="${idx}" data-pool-type="${poolType}" value="${parseFloat(item.showRatio)/RATE_SCALE.toFixed(3)}">%</td>`)
                        // } else {
                        //     tds.push(`<td>${parseFloat(item.showRatio)/RATE_SCALE.toFixed(3)}%</td>`)
                        // }
                        let row = `<tr>${tds.join()}</tr>`;

                        groupTableDom.append(row);
                    })
                    groupTableDom.append("</tbody>")

                    // 注册输入框变更事件
                    $(`${wrapperClassName} .prize-group-table input`).bind('change', inputChanged);
                    // 注册删除事件
                    $(`${wrapperClassName} .prize-group-table .js-remove-item`).bind("click", removePirzeItem);
                }
                let normalPrizeGroupCache;
                let seniorPrizeGroupCache;
                let deployedNormalPrizes;
                let deployedSeniorPrizes;
                let statisticsDatas;
                let deployedStatisticsDatas;
                let editingNormalPrizeGroup;
                let currentPoolLineId;
                let maxLineId;
                let editingSeniorPrizeGroup;
                let isNormalPrizeEditing = false;
                let isSeniorPrizeEditing = false;
                function renderPageWhenInit(groupData) {
                    const normalPrizeGroup = groupData.normalPrizeGroup;
                    const seniorPrizeGroup = groupData.seniorPrizeGroup;
                    normalPrizeGroupCache = normalPrizeGroup;
                    seniorPrizeGroupCache = seniorPrizeGroup;
                    deployedNormalPrizes = groupData.deployedNormalPrizes
                    deployedSeniorPrizes = groupData.deployedSeniorPrizes
                    currentPoolLineId = groupData.currentPoolLineId
                    maxLineId = groupData.maxLineId
                    editingNormalPrizeGroup = null;
                    editingSeniorPrizeGroup = null;
                    isNormalPrizeEditing = false;
                    isSeniorPrizeEditing = false;
                    statisticsDatas = calculateStatisticsDatas(normalPrizeGroup.prizeItems, seniorPrizeGroup.prizeItems);
                    deployedStatisticsDatas = calculateStatisticsDatas(deployedNormalPrizes, deployedSeniorPrizes);
                    renderStatisticsDatas(statisticsDatas);
                    renderPrizeGroup(POOL_TYPE.normal, normalPrizeGroup, statisticsDatas, false)
                    renderPrizeGroup(POOL_TYPE.senior, seniorPrizeGroup, statisticsDatas, false)
                }

                function getPageInfo() {
                    $.get('/admin/linearlyPool/getPrizeGroupsInfo', {
                    }, function (res) {
                        console.log(res);

                        const data = res.data;

                        renderPageWhenInit(data);
                    })
                }
                getPageInfo();

                function deepClone(o) {
                    // 判断如果不是引用类型，直接返回数据即可
                    if (typeof o === 'string' || typeof o === 'number' || typeof o === 'boolean' || typeof o === 'undefined') {
                        return o
                    } else if (Array.isArray(o)) { // 如果是数组，则定义一个新数组，完成复制后返回
                        // 注意，这里判断数组不能用typeof，因为typeof Array 返回的是object
                        console.log(typeof [])  // --> object
                        var _arr = []
                        o.forEach(item => { _arr.push(deepClone(item)) })
                        return _arr
                    } else if (typeof o === 'object') {
                        var _o = {}
                        for (let key in o) {
                            _o[key] = deepClone(o[key])
                        }
                        return _o
                    }
                }

                $('.js-edit-group').on('click', function () {
                    const poolType = $(this).attr('data-pool-type');
                    // 进入编辑状态,则使用深度拷贝复制2组数据
                    if (!editingNormalPrizeGroup || editingNormalPrizeGroup == null) {
                        editingNormalPrizeGroup = deepClone(normalPrizeGroupCache);
                    }
                    if (!editingSeniorPrizeGroup || editingSeniorPrizeGroup == null) {
                        editingSeniorPrizeGroup = deepClone(seniorPrizeGroupCache);
                    }
                    let prizeGroup;
                    if (poolType == POOL_TYPE.normal) {
                        prizeGroup = editingNormalPrizeGroup;
                        isNormalPrizeEditing = true;
                    } else if (poolType == POOL_TYPE.senior) {
                        prizeGroup = editingSeniorPrizeGroup;
                        isSeniorPrizeEditing = true;
                    } else {
                        throw Error("unkonw prize pool type")
                    }
                    const statisticsDatasCopy = deepClone(statisticsDatas)
                    renderPrizeGroup(poolType, prizeGroup, statisticsDatasCopy, true)

                });

                function reRenderPage(groupData) {
                    console.debug("reRenderPage groupData", groupData)
                    const normalPrizeGroup = groupData.normalPrizeGroup;
                    const seniorPrizeGroup = groupData.seniorPrizeGroup;
                    statisticsDatas = calculateStatisticsDatas(normalPrizeGroup.prizeItems, seniorPrizeGroup.prizeItems);
                    renderStatisticsDatas(statisticsDatas);
                    renderPrizeGroup(POOL_TYPE.normal, normalPrizeGroup, statisticsDatas, isNormalPrizeEditing)
                    renderPrizeGroup(POOL_TYPE.senior, seniorPrizeGroup, statisticsDatas, isSeniorPrizeEditing)
                }

                $('.js-cancel-edit').on('click', function () {
                    const poolType = $(this).attr('data-pool-type');
                    console.debug("js-cancel-edit ", poolType, normalPrizeGroupCache, seniorPrizeGroupCache);
                    let normalPrizeGroup = normalPrizeGroupCache;
                    if (isNormalPrizeEditing && poolType != POOL_TYPE.normal) {
                        // 普通组在编辑,并且当前取消编辑的不是普通组,则使用编辑中的数据来重新渲染页面
                        normalPrizeGroup = editingNormalPrizeGroup;
                    }
                    let seniorPrizeGroup = seniorPrizeGroupCache;
                    if (isSeniorPrizeEditing && poolType != POOL_TYPE.senior) {
                        seniorPrizeGroup = editingSeniorPrizeGroup;
                    }
                    if (poolType == POOL_TYPE.normal) {
                        editingNormalPrizeGroup = null;
                        isNormalPrizeEditing = false;
                    } else if (poolType == POOL_TYPE.senior) {
                        editingSeniorPrizeGroup = null;
                        isSeniorPrizeEditing = false;
                    }

                    reRenderPage({
                        normalPrizeGroup,
                        seniorPrizeGroup,
                    })
                });

                $('.js-save-edit').on('click', function () {
                    const poolType = $(this).attr('data-pool-type');
                    let prizeGroup;
                    if (poolType == POOL_TYPE.normal) {
                        // 普通组在编辑,并且当前取消编辑的不是普通组,则使用编辑中的数据来重新渲染页面
                        prizeGroup = editingNormalPrizeGroup;
                        isNormalPrizeEditing = false;
                    } else if (poolType == POOL_TYPE.senior) {
                        prizeGroup = editingSeniorPrizeGroup;
                        isSeniorPrizeEditing = false;
                    } else {
                        throw Error("unkonw prize pool type")
                    }

                    if (!prizeGroup.isUndeploy) {
                        // 不是未发布状态的,则要将prizeItem的id清除掉
                        const prizeItems = prizeGroup.prizeItems;
                        prizeItems.forEach((item, idx) => {
                            item.id = null;
                        });
                    }

                    console.debug("js-save-edit prizeGroup", prizeGroup);

                    $.ajax({
                        type: "post",
                        url: "/admin/linearlyPool/saveDraft",
                        data: JSON.stringify({
                            poolItems: prizeGroup.prizeItems,
                            prizePoolType: poolType,
                        }),
                        dataType: "json",
                        contentType: 'application/json',
                        success: function (json) {
                            if (json.success) {
                                $("#tipMsg").text("保存成功");
                                $("#tipModal").modal('show');
                                getPageInfo();
                            } else {
                                $("#tipMsg").text("保存失败." + json.message);
                                $("#tipModal").modal('show');
                            }
                        }
                    });
                });
                function getDataFormBack() {
                    $.get('/admin/prize/total/list', {}, function (res) {
                        if (res.code == 200) {
                            // console.log(res);
                            for (var i = 0; i < res.data.length; i++) {
                                // id对象存储
                                var id = '' + res.data[i].id;
                                prizeMap[id] = res.data[i];

                                // Type对象存储
                                var type = '' + res.data[i].prizeType;

                                console.log(type);

                                if (!typeObj[type]) {
                                    typeObj[type] = [];
                                }
                                typeObj[type].push(res.data[i]);

                            }
                            console.log(prizeMap, typeObj);
                        }
                    });
                }
                getDataFormBack();
                function clearModal() {
                    $('#addForm').find('input[type=text],select,input[type=hidden]').each(function () {
                        $(this).val('');
                    });
                    $('#editForm').find('input[type=text],select,input[type=hidden]').each(function () {
                        $(this).val('');
                    });
                }
                // 添加按钮事件
                $('.js-add-prize').on('click', function () {
                    $('#awardType').find('option').remove();
                    const poolType = $(this).attr('data-pool-type');
                    for (var key in typeObj) {
                        var $prizeType = '';
                        switch (key) {
                            case '8':
                                $prizeType = '谢谢参与';
                                break;
                            case '1':
                                $prizeType = '钻石';
                                break;
                            case '2':
                                $prizeType = '礼物';
                                break;
                            case '3':
                                $prizeType = '座驾';
                                break;
                            case '4':
                                $prizeType = '头饰';
                                break;
                            case '5':
                                $prizeType = '背景';
                                break;
                            case '6':
                                $prizeType = '实体奖品';
                                break;
                            case '7':
                                $prizeType = '靓号';
                                break;
                            case '15':
                                $prizeType = '虚拟货币';
                                break;
                        }
                        var str = '<option value=' + key + '>' + $prizeType + '</option>';
                        $('#awardType').append(str);
                    }
                    clearModal();
                    $('#prizePoolType').val(poolType);
                    $('#prizePoolName').val(POOL_NAME[poolType]);
                    $('#addModal').modal('show');
                });

                // select监听事件
                $('#addModal').find('#awardType').on('change', function () {
                    $('#awardChoose').find('option').remove();
                    var key = $(this).val();
                    console.log(key);
                    // var str = '<option></option>';
                    // $('#awardChoose').append(str);
                    var str;
                    for (var i in typeObj[key]) {
                        str = '<option value=' + typeObj[key][i].id + '>' + typeObj[key][i].prizeName + '</option>';
                        $('#awardChoose').append(str);
                    }
                    $('#addPrizeId').val(typeObj[key][0].id);
                });

                // select监听事件
                $('#addModal').find('#awardChoose').on('change', function (e) {
                    const chosenPrizeId = $(this).val()
                    // console.debug("awardChoose change", e, chosenPrizeId)
                    $('#addPrizeId').val(chosenPrizeId);
                });

                // 保存按钮事件
                $('#addSave').on('click', function () {
                    const chosenPrizeId = $('#awardChoose').val()
                    const poolType = parseInt($('#prizePoolType').val());
                    const currAllPrizeItems = [...editingNormalPrizeGroup.prizeItems, ...editingSeniorPrizeGroup.prizeItems];
                    for (let i = 0; i < currAllPrizeItems.length; i++) {
                        const exsistsPrize = currAllPrizeItems[i];
                        if (exsistsPrize.prizeId == chosenPrizeId) {
                            $('#tipMsg').text('所选的奖品已添加到奖池中,不能重复添加');
                            $('#tipModal').modal('show');
                            return;
                        }
                    }

                    const prize = prizeMap[chosenPrizeId];
                    const newPoolItem = {
                        prizeId: parseInt(chosenPrizeId),
                        prizeName: prize.prizeName,
                        prizeNum: parseInt($('#jackpotNumber').val()),
                        prizePoolType: poolType,
                        prizeType: prize.prizeType,
                        platformValue: prize.platformValue,
                        showRatio: 0,
                    }
                    let prizeList = editingNormalPrizeGroup.prizeItems;
                    if (poolType == POOL_TYPE.senior) {
                        prizeList = editingSeniorPrizeGroup.prizeItems;
                    }
                    // 按平台价值递增排序
                    let insertIdx = prizeList.length;
                    for (let i = 0; i < prizeList.length; i++) {
                        const exsistsPrize = prizeList[i];
                        if (newPoolItem.platformValue < exsistsPrize.platformValue) {
                            insertIdx = i;
                            break;
                        }
                    }
                    prizeList.splice(insertIdx, 0, newPoolItem);

                    reRenderPage({
                        normalPrizeGroup: editingNormalPrizeGroup,
                        seniorPrizeGroup: editingSeniorPrizeGroup,
                    });

                    $('#addModal').modal('hide');
                });

                $('#addCancel').on('click', function () {
                    $('#addModal').modal('hide');
                });

                // 发布
                $('.js-deploy').on('click', function () {
                    if (isSeniorPrizeEditing || isNormalPrizeEditing) {
                        $('#tipMsg').text('当前有礼物组未报错,请先保存礼物组后再尝试发布');
                        $('#tipModal').modal('show');
                        return;
                    }
                    if (!normalPrizeGroupCache.isUndeploy && !seniorPrizeGroupCache.isUndeploy) {
                        $('#tipMsg').text('没有待发布的修改');
                        $('#tipModal').modal('show');
                        return;
                    }
                    console.debug('js-deploy data', normalPrizeGroupCache, seniorPrizeGroupCache)
                    if ((normalPrizeGroupCache.prizeItems.length <= 0) ||
                        (seniorPrizeGroupCache.prizeItems.length <= 0)) {
                        $('#tipMsg').text('所有的礼物组都必须至少添加一个奖品');
                        $('#tipModal').modal('show');
                        return;
                    }

                    $('#deployedPrizeRate').text(deployedStatisticsDatas.prizeRate.toFixed(4));
                    $('#currPrizeRate').text(statisticsDatas.prizeRate.toFixed(4));
                    $('#currPoolLineId').text(currentPoolLineId);
                    $('#activePoolLineId').text(maxLineId + 1);

                    $('#deployConfirmModal').modal('show');
                })
                $('#deployCancel').on('click', function () {
                    $('#deployConfirmModal').modal('hide');
                })

                $('#deployConfirm').on('click', function () {
                    $.ajax({
                        type: "post",
                        url: "/admin/linearlyPool/deploy",
                        dataType: "json",
                        contentType: 'application/json',
                        success: function (json) {
                            if (json.success) {
                                $("#tipMsg").text("发布成功.当前奖池线: " + json.data.currentPoolLineId + ". 生效奖池线: " + json.data.willActiveLineId);
                                $("#tipModal").modal('show');
                                getPageInfo();
                            } else {
                                $("#tipMsg").text(json.message);
                                $("#tipModal").modal('show');
                            }
                        }
                    });
                    $('#deployConfirmModal').modal('hide');
                })
            })
        }
    },

};
</script>

<style scoped>
.pool-line-name {
    font-size: 20px;
}

.dataCount {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 10px;
}

.dataCount>p {
    padding: 5px;
    border-radius: 5px;
    /*background: #ccc;*/
    margin-right: 20px;
}

.tips {
    color: red;
    font-size: 14px;
}

.qry_col {
    float: left;
}

.group-table-section {
    display: flex;
    width: 100%;
}

.group-table-section .prize-group-wrapper {
    width: 50%;
}

.prize-group-wrapper .header-wrapper {
    display: flex;
    justify-content: space-between;
    max-width: 512px;
}

.prize-group-wrapper .header-wrapper .title {
    font-size: 20px;
}

.prize-group-wrapper .header-wrapper .right-content {
    display: flex;
    justify-content: flex-start;
}

.prize-group-wrapper .header-wrapper .right-content.right-content-edit {
    display: none;
}

.prize-group-wrapper .header-wrapper .action-btn-wrap button:not(last-child) {
    margin-right: 10px;
}

.prize-group-wrapper .header-wrapper .right-content .undeploy {
    color: red;
    margin-right: 10px;
}

.prize-group-wrapper .data-wrapper {
    display: flex;
    margin-top: 12px;
}

.prize-group-wrapper .data-wrapper div {
    margin-right: 20px;
}

.prize-group-wrapper .prize-group-table {
    margin-top: 12px;
    margin-right: 10px;
    max-width: 1024px;

}

.prize-group-wrapper .prize-group-table .glyphicon-remove {
    color: red;
    cursor: pointer;

}

#deployConfirmModal .modal-body {
    display: flex;
    flex-direction: column;
    align-items: center;

}

#deployConfirmModal .modal-body #currPrizeRate {
    color: red;

}

#deployConfirmModal .modal-body div:first-child {
    margin-bottom: 10px;
}

#deployConfirmModal .modal-body div:last-child {
    margin-top: 10px;
}</style>