<template>
    <section class="content">
        <div class="box box-primary">
            <div class="box-body">
                <section class="content-header">
                    <h1 id="itemTitle"></h1>
                </section>
                <section class="content">
                    <div id="table"></div>
                    <div id="toolbar">
                        奖品类别：<select name="prizeType" id="prizeType" class="input-m">
                            <option value="0">--全部--</option>
                            <option value="1">金币</option>
                            <option value="2">线上礼物</option>
                            <option value="3">座驾</option>
                            <option value="4">头饰</option>
                            <option value="6">实体奖品</option>
                            <option value="10">锤子</option>
                            <option value="11">贵族爵位</option>
                            <option value="12">萝卜</option>
                            <option value="13">祝福语</option>
                            <option value="14">铭牌</option>
                        </select>
                        <button id="add" class="btn btn-default">
                            <i class="glyphicon glyphicon-plus"></i>增加
                        </button>
                        <button id="btnSearch" class="btn btn-sm btn-primary">查询</button>
                    </div>
                </section>
            </div>
        </div>
    </section>
    <div class="modal fade" id="activityAwardModal" 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="modalLabel">活动奖品信息</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="activityAwardForm">
                        <div class="form-group" id="addModalLabel">
                            <label for="addType" class="col-sm-3 control-label">奖品类型：</label>

                            <div class="col-sm-8" style="padding-top:7px;">
                                <select name="addType" id="addType" data-btn-class="btn btn-warning">
                                    <option value="1">金币</option>
                                    <option value="2">线上礼物</option>
                                    <option value="3">座驾</option>
                                    <option value="4">头饰</option>
                                    <option value="6">实体奖品</option>
                                    <option value="10">锤子</option>
                                    <option value="11">贵族爵位</option>
                                    <option value="12">萝卜</option>
                                    <option value="14">铭牌</option>
                                </select>
                            </div>
                        </div>

                        <!-- 线上礼物 -->
                        <div class="form-group giftChoose awardList">
                            <label for="giftChoose" class="col-sm-3 control-label">选择礼物：</label>

                            <div class="col-sm-8">
                                <select name="giftChoose" id="giftChoose" class="combobox">
                                </select>
                            </div>
                        </div>

                        <!-- 座驾 -->
                        <div class="form-group carChoose awardList">
                            <label for="carChoose" class="col-sm-3 control-label">选择座驾：</label>

                            <div class="col-sm-8">
                                <select name="carChoose" id="carChoose" class="combobox">
                                </select>
                            </div>
                        </div>

                        <!-- 头饰 -->
                        <div class="form-group headwearChoose awardList">
                            <label for="headwearChoose" class="col-sm-3 control-label">选择头饰：</label>

                            <div class="col-sm-8">
                                <select name="headwearChoose" id="headwearChoose" class="combobox">
                                </select>
                            </div>
                        </div>

                        <!-- 贵族 -->
                        <div class="form-group nobleChoose awardList">
                            <label for="nobleChoose" class="col-sm-3 control-label">选择爵位：</label>

                            <div class="col-sm-8">
                                <select name="nobleChoose" id="nobleChoose" class="combobox">
                                    <option value="1">男爵</option>
                                    <option value="2">子爵</option>
                                    <option value="3">伯爵</option>
                                    <option value="4">侯爵</option>
                                    <option value="5">公爵</option>
                                    <option value="6">国王</option>
                                    <option value="7">皇帝</option>
                                </select>
                            </div>
                        </div>

                        <!-- 头饰 -->
                        <div class="form-group nameplateChoose awardList">
                            <label for="nameplateChoose" class="col-sm-3 control-label">选择头饰：</label>

                            <div class="col-sm-8">
                                <select name="nameplateChoose" id="nameplateChoose" class="combobox">
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="prizeName" class="col-sm-3 control-label">奖品名称:</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control validate[required]" name="prizeName" id="prizeName">
                                <input type="hidden" id="prizeId" name="id">
                            </div>
                        </div>

                        <div class="form-group refValue">
                            <label for="refValue" class="col-sm-3 control-label">使用天数:</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" name="refValue" id="refValue">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">奖品图:</label>
                            <div class="col-sm-8">
                                <img src="" id="imgUrl" style="width:90px;height:90px;" alt="">
                                <input type="file" id="uploadFile" name="uploadFile"
                                    accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                                <button class="btn btn-success" type="button" id="uploadBtn">上传</button>
                                <input type="hidden" id="prizeImgUrl" name="prizeImgUrl"
                                    class="form-control validate[required]" />
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="save">保存</button>
                </div>
            </div>
        </div>
    </div>
    <div id="imgMask"><img src="" alt=""></div>
</template>
<script>
import TableHelper from '@/utils/bootstrap-table-helper';
export default {
    name: "ActivityAwardAdminView",
    setup() { },
    created() {
        this.$nextTick(function () {
            this.initData();
        });
    },
    methods: {
        initData() {
            $(function () {
                var $form = $('#activityAwardForm');
                var $awardList = $('.awardList');
                $('#table').bootstrapTable('destroy');
                // 清空分页组件的容器
                $('.fixed-table-pagination').empty();
                $('#table').bootstrapTable({
                    columns: [
                        { field: 'id', title: '奖励id', align: 'center', valign: 'middle', width: '10%' },
                        {
                            field: 'prizeType', title: '奖品类别', align: 'center', valign: 'middle', width: '20%', formatter: function (val, row, index) {
                                switch (val) {
                                    case 1:
                                        return '金币';
                                    case 2:
                                        return '在线礼物';
                                    case 3:
                                        return '座驾';
                                    case 4:
                                        return '头饰';
                                    case 5:
                                        return '背景';
                                    case 6:
                                        return '实物';
                                    case 7:
                                        return '靓号';
                                    case 8:
                                        return '全麦礼物';
                                    case 9:
                                        return '随机靓号';
                                    case 10:
                                        return '锤子';
                                    case 11:
                                        return '贵族爵位';
                                    case 12:
                                        return '萝卜';
                                    case 14:
                                        return '铭牌';
                                }
                            }
                        },
                        { field: 'prizeName', title: '奖品名称', align: 'center', valign: 'middle', width: '20%' },
                        {
                            field: 'prizeImgUrl', title: '奖品图片', align: 'center', width: '10%', formatter: function (val, row, index) {
                                return "<img src='" + val + "' width='60' height='60'>";
                            }
                        },
                        { field: 'referenceValue', title: '使用天数', align: 'center', valign: 'middle', width: '20%' },
                        {
                            field: 'createTime',
                            title: '创建时间',
                            align: 'center',
                            width: '10%',
                            valign: 'middle',
                            formatter: function (val, row, index) {
                                if (val) {
                                    var date = new Date(val);
                                    return date.format("yyyy-MM-dd hh:mm:ss");
                                } else {
                                    return '-';
                                }
                            }
                        },
                        {
                            field: 'updateTime',
                            title: '更新时间',
                            align: 'center',
                            width: '10%',
                            valign: 'middle',
                            formatter: function (val, row, index) {
                                if (val) {
                                    var date = new Date(val);
                                    return date.format("yyyy-MM-dd hh:mm:ss");
                                } else {
                                    return '-';
                                }
                            }
                        },
                        {
                            field: 'tmp',
                            title: '操作',
                            align: 'center',
                            width: '10%',
                            valign: 'middle',
                            formatter: function (val, row, index) {
                                var key = row.id;
                                return "<button class='btn btn-sm btn-success opt-edit' data-id=" + key + ">编辑</button>";
                            }
                        }
                    ],
                    cache: false,
                    striped: true,
                    showRefresh: false,
                    pageSize: 10,
                    pagination: true,
                    pageList: [10, 20, 30, 50],
                    sidePagination: "server", //表示服务端请求
                    //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
                    //设置为limit可以获取limit, offset, search, sort, order
                    queryParamsType: "undefined",
                    queryParams: function queryParams(params) {   //设置查询参数
                        var param = {
                            pageSize: params.pageSize,
                            pageNumber: params.pageNumber,
                            prizeType: $('#prizeType').val()
                        };
                        return param;
                    },
                    uniqueId: 'id',
                    toolbar: '#toolbar',
                    url: '/admin/activityAward/list.action',
                    onLoadSuccess: function () {  //加载成功时执行
                        console.log("load success");
                    },
                    onLoadError: function () {  //加载失败时执行
                        console.log("load fail");
                    }
                });
                combineDataFromBack();
                $('#btnSearch').on('click', function () {
                    TableHelper.doRefresh('#table');
                });
                $('#table').on('click', '.opt-edit', function () {
                    clearAwardList();
                    $('.refValue').hide();
                    var id = parseInt($(this).data('id'));
                    var data = $('#table').bootstrapTable('getRowByUniqueId', id);
                    var prizeType = data.prizeType;
                    if (prizeType == 2) {
                        $awardList.eq(0).show().siblings('.awardList').hide();
                        $awardList.eq(0).find('select').val(data.referenceId);
                        let $selected = $awardList.eq(0).find('select option:selected');
                        let referenceId = $selected.val();
                        let awardName = $selected.text();
                        $awardList.eq(0).find('input[type="text"]').val(awardName);
                        $awardList.eq(0).find('input[type="hidden"]').val(referenceId);
                    } else if (prizeType == 3) {
                        $awardList.eq(1).show().siblings('.awardList').hide();
                        $awardList.eq(1).find('select').val(data.referenceId);
                        let $selected = $awardList.eq(1).find('select option:selected');
                        let referenceId = $selected.val();
                        let awardName = $selected.text();
                        $awardList.eq(1).find('input[type="text"]').val(awardName);
                        $awardList.eq(1).find('input[type="hidden"]').val(referenceId);
                        $('#refValue').val(data.referenceValue);
                        $('.refValue').show();
                    } else if (prizeType == 4) {
                        $awardList.eq(2).show().siblings('.awardList').hide();
                        $awardList.eq(2).find('select').val(data.referenceId);
                        let $selected = $awardList.eq(2).find('select option:selected');
                        let referenceId = $selected.val();
                        let awardName = $selected.text();
                        $awardList.eq(2).find('input[type="text"]').val(awardName);
                        $awardList.eq(2).find('input[type="hidden"]').val(referenceId);
                        $('#refValue').val(data.referenceValue);
                        $('.refValue').show();
                    } else if (prizeType == 11) {
                        $awardList.eq(3).show().siblings('.awardList').hide();
                        $awardList.eq(3).find('select').val(data.referenceId);
                        let $selected = $awardList.eq(3).find('select option:selected');
                        let referenceId = $selected.val();
                        let awardName = $selected.text();
                        $awardList.eq(3).find('input[type="text"]').val(awardName);
                        $awardList.eq(3).find('input[type="hidden"]').val(referenceId);
                        $('#refValue').val(data.referenceValue);
                        $('.refValue').show();
                    } else if (prizeType == 14) {
                        $awardList.eq(4).show().siblings('.awardList').hide();
                        $awardList.eq(4).find('select').val(data.referenceId);
                        let $selected = $awardList.eq(4).find('select option:selected');
                        let referenceId = $selected.val();
                        let awardName = $selected.text();
                        $awardList.eq(4).find('input[type="text"]').val(awardName);
                        $awardList.eq(4).find('input[type="hidden"]').val(referenceId);
                        $('#refValue').val(data.referenceValue);
                        $('.refValue').show();
                    } else {
                        $awardList.hide();
                    }
                    $('#addType').val(data.prizeType);
                    $('#prizeName').val(data.prizeName);
                    $('#prizeId').val(data.id);
                    $('#imgUrl').attr('src', data.prizeImgUrl);
                    $('#prizeImgUrl').val(data.prizeImgUrl);
                    $('#activityAwardModal').modal("show");
                    console.log(data);
                });
                $('#addType').on('change', function () {
                    clearAwardList();
                    $awardList.each(function () {
                        $(this).hide();
                    });
                    $('.refValue').hide();
                    var val = parseInt($(this).val());
                    if (val == 2) {
                        $awardList.eq(0).show().siblings('.awardList').hide();
                    } else if (val == 3) {
                        $awardList.eq(1).show().siblings('.awardList').hide();
                        $('.refValue').show();
                    } else if (val == 4) {
                        $awardList.eq(2).show().siblings('.awardList').hide();
                        $('.refValue').show();
                    } else if (val == 11) {
                        $awardList.eq(3).show().siblings('.awardList').hide();
                        $('.refValue').show();
                    } else if (val == 14) {
                        $awardList.eq(4).show().siblings('.awardList').hide();
                        $('.refValue').show();
                    }
                })
                $('#save').on('click', function () {
                    if ($('#activityAwardForm').validationEngine('validate')) {
                        var prizeType = parseInt($('#addType').val());
                        var referenceId = getReferenceIdAndStatus(prizeType);
                        console.log(referenceId);
                        if (referenceId === false && prizeType != 1 && prizeType != 5) {
                            $("#tipMsg").text("请输入完整的信息");
                            $("#tipModal").modal('show');
                            return;
                        }
                        var refValue = $('#refValue').val();
                        if (prizeType == 3 || prizeType == 4 || prizeType == 11 || prizeType == 14) {
                            if (!refValue) {
                                $("#tipMsg").text("使用天数必填");
                                $("#tipModal").modal('show');
                                return;
                            }
                        } else {
                            refValue = 0;
                        }
                        $.ajax({
                            type: "post",
                            url: "/admin/activityAward/save",
                            data: {
                                id: $('#prizeId').val(),
                                prizeType: $('#addType').val(),
                                prizeName: $('#prizeName').val(),
                                prizeImgUrl: $("#prizeImgUrl").val(),
                                referenceId: referenceId,
                                referenceValue: refValue
                            },
                            dataType: 'json',
                            success: function (json) {
                                if (json.code == 200) {
                                    $("#activityAwardModal").modal('hide');
                                    $("#tipMsg").text("保存成功");
                                    $("#tipModal").modal('show');
                                    TableHelper.doRefresh("#table");
                                } else {
                                    $("#tipMsg").text("保存失败，错误码：" + json.message);
                                    $("#tipModal").modal('show');
                                }
                            }
                        })
                    }
                });
                $('#uploadBtn').on('click', function () {
                    $.ajaxFileUpload({
                        fileElementId: 'uploadFile',
                        url: '/admin/upload/img',
                        type: 'post',
                        dataType: 'json',
                        secureuri: false,
                        async: true,
                        success: function (json) {
                            if (json.path) {
                                if (json.path != '') {
                                    $('#imgUrl').attr('src', json.path);
                                    $('#prizeImgUrl').val(json.path);
                                } else {
                                    console.log('图片上传失败');
                                }
                            } else {
                                $('#tipMsg').text(json.msg);
                                $('#tipModal').modal('show');
                            }
                        },
                        error: function (data, status, e) {
                            console.log(e);
                        }
                    })
                });
                $('#add').on('click', function () {
                    let isEdit = false;
                    clearModal();
                    $('#activityAwardModal').modal('show');
                })
                $('#table').on('mouseenter', 'img', function (e) {
                    console.log($(this), e.clientX);
                    var src = $(this).attr('src');
                    $('#imgMask img').attr('src', src);
                    $('#imgMask').show();
                    $('#imgMask').css({
                        top: e.clientY + 20,
                        left: e.clientX + 20
                    })
                })
                $('#table').on('mouseleave', 'img', function (e) {
                    console.log('移出');
                    $('#imgMask').hide();
                });
                function combineDataFromBack() {
                    $.get('/admin/gift/' +
                        'getAllGiftList?consumeType=1&consumeType=2', function (res) {
                            if (res.code == 200) {
                                var data = res.data;
                                for (var key in data) {
                                    var str = '<option value="' + data[key].giftId + '">' + data[key].giftName + '</option>';
                                    $('#giftChoose').append(str);
                                }
                                $('#giftChoose').combobox();
                            }
                        })
                    $.get('/admin/headwear/total/list', {}, function (res) {
                        if (res.code == 200) {
                            for (var i = 0; i < res.data.length; i++) {
                                //                        var dress = res.data;
                                var str = '<option value="' + res.data[i].headwearId + '">' + res.data[i].name + '</option>';
                                $('#headwearChoose').append(str);
                            }
                        }
                        $('#headwearChoose').combobox();
                    })
                    $.get('/admin/car/goods/total/list', {}, function (res) {
                        if (res.code == 200) {
                            for (var i = 0; i < res.data.length; i++) {
                                //                        car.push(res.data[i]);
                                var str = '<option value="' + res.data[i].id + '">' + res.data[i].name + '</option>';
                                $('#carChoose').append(str);
                            }
                        }
                        $('#carChoose').combobox();
                    })
                    $.get('/admin/nameplate//total/list', {}, function (res) {
                        if (res.code == 200) {
                            for (var i = 0; i < res.data.length; i++) {
                                //                        car.push(res.data[i]);
                                var str = '<option value="' + res.data[i].id + '">' + res.data[i].name + '</option>';
                                $('#nameplateChoose').append(str);
                            }
                        }
                        $('#nameplateChoose').combobox();
                    })
                }
                function getReferenceIdAndStatus(prizeType) {
                    console.log(prizeType);
                    var referenceId = 0;
                    var val;
                    switch (prizeType) {
                        case 2:
                            // 线上礼物
                            val = $form.find('input[name="giftChoose"]').val();
                            referenceId = val ? val : false;
                            break;
                        case 3:
                            // 座驾
                            val = $form.find('input[name="carChoose"]').val();
                            referenceId = val ? val : false;
                            break;
                        case 4:
                            // 头饰
                            val = $form.find('input[name="headwearChoose"]').val();
                            referenceId = val ? val : false;
                            break;
                        case 11:
                            val = $form.find('#nobleChoose').val();
                            referenceId = val ? val : false;
                            break;
                        case 14:
                            val = $form.find('#nameplateChoose').val();
                            referenceId = val ? val : false;
                            break;
                    }
                    return referenceId;
                }
                function clearModal() {
                    $('#activityAwardForm').find('input[type=text],select,input[type=hidden],input[type=file]').each(function () {
                        $(this).val('');
                    });
                    $('.awardList').hide();
                    $('#activityAwardForm').find('img').attr('src', '');
                    $('#activityAwardForm').find('.combobox-container').removeClass('combobox-selected');
                    // $('#addForm').find('select option').attr('selected',false);
                }
                function clearAwardList() {
                    $('.awardList').find('input').val('');
                }
            })
        }
    }
};
</script>

<style scoped>
#prizeType {
    margin-right: 10px;
}

.btn {
    margin: 0 4px;
}

.input-group-addon {
    width: 0;
}

#uploadBtn,
#addUploadBtn {
    margin-top: 4px;
}

#skipUrlSort,
#bannerStatus,
#addSkipUrlSort,
#addBannerStatus {
    height: 34px;
}

.attention {
    line-height: 30px;
    display: inline-block;
    margin-top: 4px;
    color: red;
}

.awardList {
    display: none;
}

#imgMask {
    position: absolute;
    top: 0;
    left: 0;
    width: 90px;
    height: 90px;
    padding: 4px;
    background: #fff;
    z-index: 999;
    display: none;
}

#imgMask img {
    width: 100%;
    height: 100%;
    vertical-align: top;
}

.refValue {
    display: none;
}
</style>
