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

            <section class="content">
                <div id="table"></div>
                <div id="toolbar">
                    <!-- <form action="" id="searchForm" method="POST">
                    起始时间：<input type="text" name="searchTimeBegin" id="searchTimeBegin" class="input-sm" placeholder="请输入开始时间">
                </form>
                <button class="btn btn-primary" id="searchBtn">搜索</button> -->
                    <button class="btn btn-primary" id="addBtn">新增</button>
                </div>
            </section>
        </div>
    </section>

    <!-- 新增框 -->
    <div class="modal fade" id="addModal" rabindex='-1' role="dialog" aria-labelledby="modalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">x</span>
                    </button>

                    <div class="modal-title" id="addModalLabel">家族PK活动配置</div>
                </div>

                <div class="modal-body">
                    <form action="" id="addForm" class="form-horizontal">

                        <!-- 起始时间 -->
                        <div class="form-group">
                            <div class="col-sm-12" id="attention" style="color:red;">注意：无论选择什么时间都会设置到选择时间所在周的周四</div>
                            <label for="addTimeBegin" class="col-sm-3 control-label">起始时间：</label>

                            <div class="col-sm-8">
                                <input type="text" id="addTimeBegin" name="addTimeBegin" class="validate[required]"
                                    placeholder="请输入时间">
                            </div>
                        </div>

                        <!-- 房间ID -->
                        <div class="form-group">
                            <label for="roomID" class="col-sm-3 control-label">房主66ID：</label>

                            <div class="col-sm-8">
                                <input type="text" id="roomID" name="roomID" class="validate[required] input-sm"
                                    placeholder="多个房间请用英文,隔开" style="width: 400px; border: 1px solid lightgray">
                            </div>
                        </div>

                        <!-- 荣誉奖励 -->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">荣誉奖励：</label>

                            <div class="col-sm-8 selectBox">
                                <!-- <div class="prize" style="display: flex;justify-content: flex-start;">
                                <input type="text" id="hornorPrize1" class="input-sm" name="hornorPrize1" placeholder="" style="border: 1px solid lightgray">

                                <img src="" alt="" id="imgUrl1" style="width: 70px;height: 70px;margin-left:20px;">

                                <input type="file" id="uploadFile1" name="uploadFile" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                                

                                <input type="hidden" id="alertWinPic1" name="alertWinPic1" class="form-control">
                            </div>

                            <div class="prize" style="display: flex;justify-content: flex-start;">
                                <input type="text" id="hornorPrize2" class="input-sm" name="hornorPrize2" placeholder="" style="border: 1px solid lightgray">

                                <img src="" alt="" id="imgUrl2" style="width: 70px;height: 70px;margin-left:20px;">

                                <input type="file" id="uploadFile2" name="uploadFile" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                                

                                <input type="hidden" id="alertWinPic2" name="alertWinPic2" class="form-control">
                            </div>

                            <div class="prize" style="display: flex;justify-content: flex-start;">
                                <input type="text" id="hornorPrize3" class="input-sm" name="hornorPrize3" placeholder="" style="border: 1px solid lightgray">

                                <img src="" alt="" id="imgUrl3" style="width: 70px;height: 70px;margin-left:20px;">

                                <input type="file" id="uploadFile3" name="uploadFile" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                                

                                <input type="hidden" id="alertWinPic3" name="alertWinPic3" class="form-control">
                            </div>

                            <div class="prize" style="display: flex;justify-content: flex-start;">
                                <input type="text" id="hornorPrize4" class="input-sm" name="hornorPrize4" placeholder="" style="border: 1px solid lightgray">

                                <img src="" alt="" id="imgUrl4" style="width: 70px;height: 70px;margin-left:20px;">

                                <input type="file" id="uploadFile4" name="uploadFile" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                               

                                <input type="hidden" id="alertWinPic4" name="alertWinPic4" class="form-control">
                            </div>

                            <div class="prize" style="display: flex;justify-content: flex-start;">
                                <input type="text" id="hornorPrize5" class="input-sm" name="hornorPrize5" placeholder="" style="border: 1px solid lightgray">

                                <img src="" alt="" id="imgUrl5" style="width: 70px;height: 70px;margin-left:20px;">

                                <input type="file" id="uploadFile5" name="uploadFile" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                                

                                <input type="hidden" id="alertWinPic5" name="alertWinPic5" class="form-control">
                            </div>

                            <div class="prize" style="display: flex;justify-content: flex-start;">
                                <input type="text" id="hornorPrize6" class="input-sm" name="hornorPrize6" placeholder="" style="border: 1px solid lightgray">

                                <img src="" alt="" id="imgUrl6" style="width: 70px;height: 70px;margin-left:20px;">

                                <input type="file" id="uploadFile6" name="uploadFile" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                                

                                <input type="hidden" id="alertWinPic6" name="alertWinPic6" class="form-control">
                            </div> -->

                                <select name="" id="prize_first" class="combobox">
                                    <!-- <option value="0">请选择</option> -->
                                </select>

                                <select name="" id="prize_second" class="combobox">
                                    <!-- <option value="0">请选择</option> -->
                                </select>

                                <select name="" id="prize_third" class="combobox">
                                    <!-- <option value="0">请选择</option> -->
                                </select>

                                <select name="" id="prize_four" class="combobox">
                                    <!-- <option value="0">请选择</option> -->
                                </select>

                                <select name="" id="prize_five" class="combobox">
                                    <!-- <option value="0">请选择</option> -->
                                </select>

                                <select name="" id="prize_six" class="combobox">
                                    <!-- <option value="0">请选择</option> -->
                                </select>

                            </div>

                        </div>

                        <!-- 描述 -->
                        <div class="form-group">
                            <label for="introduce" class="col-sm-3 control-label">描述：</label>

                            <div class="col-sm-8">
                                <input type="text" id="introduce" name="introduce" class="validate[required]"
                                    placeholder="">
                            </div>
                        </div>

                        <!-- 上传图片 -->
                        <!-- <div class="form-group">
                        
                        <img src="" alt="" id="imgUrl" style="width: 100px;height: 50px;">

                        <input type="file" id="uploadFile" name="uploadFile" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                        
                        <button class="btn btn-success">上传</button>

                        <input type="hidden" id="alertWinPic" name="alertWinPic" class="form-control validate[required]">
                    </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" data-primary="addSaveData" 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>
</template>

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

export default {
    name: "FamilyPKManageAdminView",
    setup() {
        return {};
    },
    created() {
        this.$nextTick(function () {
            this.initData();
        });
    },
    methods: {
        initData() {
            $(function () {

                // var picker1 = $('#searchTimeBegin').datetimepicker({
                //     format: 'yyyy-mm-dd hh:ii:00',
                //     autoclose: true,
                //     endDate: new Date()
                // });

                var $id = '';

                var selectArr = [];

                var prizeObj = {};

                var picker2 = $('#addTimeBegin').datetimepicker({
                    format: 'yyyy-mm-dd hh:ii:00',
                    autoclose: true,
                    endDate: new Date()
                });

                var main = {
                    init: function () {
                        this.eventRegister();
                        this.valueChange();
                    },

                    eventRegister: function () {

                        // 新增按钮点击事件
                        $('#addBtn').on('click', function () {
                            $('#addModal').modal('show');
                            clearModal();
                        });

                        // 监听荣誉奖励select框变化
                        $('.selectBox').on('change', 'select', function () {
                            switch ($(this).attr('id')) {
                                case 'prize_first':

                                    selectArr.push($(this).val());

                                    break;

                                case 'prize_second':

                                    selectArr.push($(this).val());

                                    break;

                                case 'prize_third':

                                    selectArr.push($(this).val());


                                    break;

                                case 'prize_four':

                                    selectArr.push($(this).val());


                                    break;

                                case 'prize_five':

                                    selectArr.push($(this).val());


                                    break;

                                case 'prize_six':

                                    selectArr.push($(this).val());


                                    break;
                            }
                            console.log(selectArr);
                        });

                        // 添加保存按钮点击事件
                        $('#addSave').on('click', function () {
                            // 获取时间参数
                            var $time = $('#addTimeBegin').val();
                            if ($time == '' || $time == 'undefined') {
                                $('#tipMsg').text('时间项不能为空');
                                $('#tipModal').modal('show');
                                return;
                            }

                            // 获取房间ID参数
                            var idArr = $('#roomID').val().split(',');
                            if ($roomId == '' || $roomId == 'undefined') {
                                $('#tipMsg').text('房间ID不能为空');
                                $('#tipModal').modal('show');
                                return;
                            } else if (idArr.length > 6) {
                                $('#tipMsg').text('参与PK房间数超过6个');
                                $('#tipModal').modal('show');
                                return;
                            }
                            var $roomId = $('#roomID').val();

                            // 获取荣耀奖励参数
                            //                    var prizeArr = [];
                            //                    for(var i = 0 ; i < selectArr.length ; i++) {
                            //                        if(prizeArr.indexOf(selectArr[i]) == -1) {
                            //                            prizeArr.push(selectArr[i]);
                            //                        } else {
                            //                            $('#tipMsg').text('您已选择过相同奖品');
                            //                            $('#tipModal').modal('show');
                            //                            return;
                            //                        }
                            //                    }

                            var awardArr = $('.selectBox').find('input[type="hidden"]');
                            var awardIdArr = [];
                            var awardObj = {}, repeatBol = false;
                            for (var i = 0; i < awardArr.length; i++) {
                                var awardId = awardArr.eq(i).val();
                                if (parseInt(awardId)) {
                                    console.log(awardId);
                                    if (!awardObj[awardId]) {
                                        awardObj[awardId] = 1;
                                        awardIdArr.push(parseInt(awardId));
                                    } else {
                                        repeatBol = true;
                                        break;
                                    }
                                }
                            }

                            // var prizeArr = [];
                            // for(var i = 0 ;  i < $('#addModal').find('.prize').length ; i++) {
                            //     var $prize = $('#addModal').find('.prize').eq(i);
                            //     if($prize.find('input[type=text],input[type=hidden]').val() != '' && $prize.find('img').attr('src') != '') {
                            //         prizeArr.push($prize.find('input[type=text]').val() + '|' + $prize.find('img').attr('src'));
                            //     }else if($prize.find('input[type=text]').val() != '') {
                            //         if($prize.find('img').attr('src') == '') {
                            //             $('#tipMsg').text('奖励'+ (i+1) +'没有对应图片');
                            //             $('#tipModal').modal('show');
                            //             return;
                            //         }
                            //     }else if($prize.find('img').attr('src') != '') {
                            //         if($prize.find('input[type=text]').val() == '' || $prize.find('input[type=text]').val() == 'undefined') {
                            //             $('#tipMsg').text('奖励' + (i+1) + '图片没有对应名称');
                            //             $('#tipModal').modal('show');
                            //             return;
                            //         }


                            //     }


                            // }
                            // 获取描述参数
                            var $introduce = $('#introduce').val();

                            // id
                            var id;
                            if ($id == '' || $id == 'undefined') {
                                id = '';
                            } else {
                                id = $id;
                            }

                            var $award = awardIdArr.join(',');
                            if ($award == 0) {
                                $('#tipMsg').text('礼物不能为空，至少设置一个');
                                $('#tipModal').modal('show');
                                return;
                            }
                            // 保存请求
                            $.post('/admin/familyPkConfig/save', {
                                id: id,
                                startDate: $time,
                                endDate: $time,
                                roomErbanNoListStr: $roomId,
                                description: $introduce,
                                // award: JSON.stringify(prizeArr)
                                award: $award
                            }, function (res) {
                                if (res.code == 200) {
                                    $('#tipMsg').text('保存成功');
                                    $('#tipModal').modal('show');
                                    $('#addModal').modal('hide');
                                    TableHelper.doRefresh('#table');
                                } else if (res.code == 500) {
                                    $('#tipMsg').text(res.message);
                                    $('#tipModal').modal('show');
                                }
                            })
                        })



                        // 编辑按钮点击事件
                        $('#table').on('click', '.opt-edit', function () {
                            $('#addModal').modal('show');
                            var id = $(this).data('id');
                            $id = id;
                            var data = $('#table').bootstrapTable('getRowByUniqueId', id);
                            clearModal();

                            console.log(data);

                            var date = new Date(data.startDate);
                            $('#addModal').find('#addTimeBegin').val(date.format('yyyy-MM-dd hh:mm:ss'));

                            $('#addModal').find('#roomId').val(data.roomErbanNoList);

                            $('#addModal').find('#introduce').val(data.description);

                            var arr = data.award.split(',');
                            var $list = $('#addForm').find('.selectBox select');

                            for (var i = 0; i < arr.length; i++) {
                                $list.eq(i).val(arr[i]);
                                var $target = $list.eq(i).find("option:selected");
                                var awardId = $target.val();
                                var awardText = $target.text();
                                $('.combobox-container').eq(i).find('input[type="text"]').val(awardText);
                                $('.combobox-container').eq(i).find('input[type="hidden"]').val(awardId);
                            }


                        });

                        // 图片选择监听事件
                        // $('.prize').on('change','input[type=file]',function() {

                        //     console.log($(this).attr('id'));
                        //     var id = $(this).attr('id').substring(10,11);
                        //     console.log(id);

                        //     $.ajaxFileUpload({
                        //         fileElementId: $(this).attr('id'),
                        //         url: '/admin/upload/img',
                        //         type: 'post',
                        //         dataType: 'json',
                        //         secureuri: false,
                        //         async: true,
                        //         success: function(json) {
                        //             if(json.path) {
                        //                 if(json.path != ''){
                        //                      $('#imgUrl' + id).attr('src',json.path);
                        //                 } else {
                        //                     console.log('图片上传失败');
                        //                 }
                        //             } else {
                        //                 $('#tipMsg').text(json.msg);
                        //                 $('#tipModal').modal('show');
                        //             }
                        //         },
                        //         error: function(data,status,e) {
                        //             console.log(e);
                        //         }
                        //     })
                        // });
                    },

                    valueChange: function () {
                        $.get('/admin/activityAward/total', {}, function (res) {
                            if (res.code == 200) {
                                for (var i = 0; i < res.data.length; i++) {
                                    var str = '<option value="' + res.data[i].id + '">' + res.data[i].prizeName + '</option>';
                                    $('.selectBox').find('select').append(str);
                                    prizeObj[res.data[i].id] = res.data[i].prizeName
                                }

                                console.log(prizeObj)
                                $('.selectBox').find('select').combobox();
                            }
                        })
                    }
                };
                main.init();


                $('#table').bootstrapTable('destroy');
                $('#table').bootstrapTable({
                    columns: [
                        { field: 'id', title: '编号', align: 'center', valign: 'middle', width: '10%' },
                        {
                            field: 'startDate', title: '开始时间', align: 'center', valign: 'middle', width: '15%', formatter: function (val, row, index) {
                                if (val) {
                                    var date = new Date(val);
                                    return date.format('yyyy-MM-dd hh:mm:ss');
                                } else {
                                    return '-';
                                }
                            }
                        },
                        {
                            field: 'endDate', title: '结束时间', align: 'center', valign: 'middle', width: '15%', formatter: function (val, row, index) {
                                if (val) {
                                    var date = new Date(val);
                                    return date.format('yyyy-MM-dd hh:mm:ss');
                                } else {
                                    return '-';
                                }
                            }
                        },
                        {
                            field: 'award', title: '家族奖励', align: 'center', valign: 'middle', width: '15%', formatter: function (val, row, index) {

                                if (val) {
                                    var arr = val.split(',')
                                    var value = null;
                                    var content = '';
                                    for (var i = 0; i < arr.length; i++) {
                                        value = arr[i];
                                        if (i < arr.length - 1) {
                                            content += (prizeObj[value] + ',');
                                        } else {
                                            content += prizeObj[value];
                                        }
                                    }
                                    return content;
                                }

                                // console.log(JSON.parse(val));//["狗|图片地址"]
                                // if(val) {
                                //     var arr = JSON.parse(val);
                                //     var value = null;
                                //     var content = '';
                                //     for(i in arr) {
                                //         value = arr[i].split('|')[0];
                                //         if(i < arr.length-1) {
                                //             content += (value+',');
                                //         } else {
                                //             content += value;
                                //         }
                                //     }
                                //     return content;
                                // }
                            }
                        },
                        { field: 'roomErbanNoList', title: 'PK家族房主平台号', align: 'center', valign: 'middle', width: '10%' },
                        {
                            field: 'createTime', title: '创建时间', align: 'center', valign: 'middle', width: '15%', formatter: function (val, row, index) {
                                if (val) {
                                    var date = new Date(val);
                                    return date.format('yyyy-MM-dd hh:mm:ss');
                                } else {
                                    return '-';
                                }
                            }
                        },
                        { field: 'description', title: '描述', align: 'center', valign: 'middle', width: '10%' },
                        {
                            field: '', title: '操作', align: 'center', valign: 'middle', width: '10%', formatter: function (val, row, index) {
                                var key = row.id;
                                var startDate = new Date(row.startDate);
                                var endDate = new Date(row.endDate);
                                var curDate = new Date();
                                if (curDate.getTime() >= startDate.getTime()) {
                                    return '<button class="btn btn-primary btn-sm opt-edit" disabled data-id="' + key + '">不可编辑</button>';
                                } else {
                                    return '<button class="btn btn-primary btn-sm opt-edit" data-id="' + key + '">编辑</button>';
                                }
                            }
                        }
                    ],
                    cache: false,
                    striped: true,
                    showRefresh: false,
                    pageSize: 10,
                    pageList: [10, 20, 30, 50],
                    pagination: true,
                    sidePagination: 'server',
                    queryParamsType: 'undefined',
                    queryParams: function queryParams(params) {
                        var param = {
                            pageSize: params.pageSize,
                            pageNumber: params.pageNumber,
                        }
                    },
                    uniqueId: 'id',
                    toolbar: '#toolbar',
                    url: '/admin/familyPkConfig/list',
                    onLOadSuccess: function () {
                        console.log('load success');
                    },
                    onLoadError: function () {
                        console.log('load fail');
                    }
                });

                function clearModal() {
                    $('#addForm').find('input[type=text],input[type=hidden],input[type=file]').each(function () {
                        $(this).val('');
                    })
                    $('#addForm').find('img').attr('src', '');
                    $('#addForm').find('.combobox-container').removeClass('combobox-selected');
                    selectArr = [];
                    // $('#addForm').find('option[value="0"]').attr('selected',true);
                }
            })
        }
    },

};

</script>

<style scoped>.input-group-addon {
    width: 0;
    padding: 5px 12px;
}

.selectBox .combobox-container {
    margin-top: 5px;
}</style>