<?php
require_once('loginCheck.php');
require_once('header.php');
?>

<div class="container-fluid" id="layerUI">
    <div class="box-inner">
        <div style="display:none;">
            <label class=" control-label">用于layer中获取当前活动ID</label>
            <input type="number" id="curActivityID">

            <label class="control-label">弹出index</label>
            <input type="number" id="addQuestionLayerIndex">

            <label class=" control-label">活动ID</label>
            <input type="number" id="resetID">

            <label class="control-label">弹出index</label>
            <input type="number" id="resetLayerIndex">
        </div>

        <div class="box-content">
            <div class="row-fluid alert alert-success">
                <strong>温馨提示：</strong>行家APP中需要使用哪个问卷活动，请在加载H5的URL中加入参数<strong>[activityID=问卷活动ID]</strong>
                如：http://xx.pingan.com.cn/pingan_h5?appToken=1111&activityID=123
            </div>
			<div class="row-fluid alert alert-danger">
                <strong>注意事项：</strong>自定义背景尺寸：宽：750，高：1624 &nbsp;&nbsp;<strong>自定义标题尺寸：</strong>：宽不超过500，高不超过200
            </div>
            <div class="row-fluid">
                <button type="button" class="btn btn-default" id="btnAddActivity">新增问卷活动</button>
            </div>
            <div class="row-fluid">
                <div class="span12">

                    <table border="0" cellspacing="0" cellpadding="2" class="layui-hide" id="activityTable">

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

        <div class="box-content" id="questionListHTML" style="display:none;">
            <div class="row-fluid">
                <button type="button" class="btn btn-default" id="btnAddQuestion">新增题目</button>
            </div>
            <div class="row-fluid">
                <div class="span12">

                    <table border="0" cellspacing="0" cellpadding="2" class="layui-hide" id="questionTable">

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

        <div class="box-content" id="questionHTML" style="display:none;">
            <table class="table table-bordered table-striped responsive" id="tmpQuestionTb">
                <tbody>
                    <tr id="quOrder">
                        <td width='10%'>
                            <label class="control-label">排序值：</label>
                        </td>
                        <td>
                            <input type="number" class="form-control" id="qOrder">
                        </td>
                    </tr>

                    <tr id="quType">
                        <td width='10%'>
                            <label class="control-label">题目类型：</label>
                            <span><strong style="color:red">*</strong>必选</span>
                        </td>
                        <td>
                            <label class="radio-inline">
                                <input type="radio" name="optionRadio" id="qType1" value="1"> 单选题
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="optionRadio" id="qType2" value="2"> 多选题
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="optionRadio" id="qType3" value="3"> 问答题
                            </label>
                        </td>
                    </tr>

                    <tr id="quContent">
                        <td width='10%'>
                            <label class="control-label">题目内容：</label>
                            <span><strong style="color:red">*</strong>最多50个字符</span>
                        </td>
                        <td>
                            <input type="text" class="form-control" id="qContent" maxlength="50">
                        </td>
                    </tr>

                    <tr id="quOptions">
                        <td width='10%'>
                            <label class="control-label">选项内容：</label>
                            <span><strong style="color:red">*</strong>最少需要2个选项，最多支持8个选项</span>
                            <br /><br />
                            <a class="btn btn-info" onclick="addOpt()">
                                <i class="glyphicon glyphicon-plus icon-white"></i>
                                增加选项
                            </a>
                        </td>
                        <td>
                            <table class="table table-bordered table-striped responsive" id="optionsTable">
                                <tbody>
                                    <tr>
                                        <td width='10%'><label class="control-label">选项1</label></td>
                                        <td>
                                            <input type="text" class="form-control" id="qOptions" placeholder="">
                                        </td>
                                        <td width=50>
                                            <a class="btn btn-info" onclick="delOpt()"><i class="glyphicon glyphicon-trash icon-white" onclick="delOpt()"></i></a>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </td>
                    </tr>

                    <tr id="quAnswers">
                        <td width='10%'>
                            <label class="control-label">正确答案：</label>
                        </td>
                        <td>
                            <label class="checkbox-inline">
                                <input type="checkbox" id="inlineCheckbox1" value="option1"> 多选
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="optionRadio" id="qType3" value="option2"> 单选
                            </label>
                        </td>
                    </tr>
                </tbody>
            </table>
            <button type="button" class="btn btn-default" id="btnUpdateQuestion" style="margin-left:40%;">确定</button>
        </div>

        <div class="box-content" id="userListHTML" style="display:none;">
            <div class="row-fluid">
                <button type="button" class="btn btn-default" id="btnExport">导出数据</button>
            </div>
            <div class="row-fluid">
                <div class="span12">

                    <table border="0" cellspacing="0" cellpadding="2" class="layui-hide" id="userTable">

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

        <div class="box-content" id="activityHTML" style="display:none;">
            <form role="form">
                <div class="form-group">
                    <label class="control-label">输入活动名称</label>
                    <input type="text" class="form-control" id="txtName" placeholder="">
                </div>
                <div class="form-group">
                    <label class="control-label">输入领奖提示</label>
                    <input type="text" class="form-control" id="txtTips" placeholder="">
                </div>
                <button type="button" class="btn btn-default" id="btnUpdateActivity" style="margin-left:40%;">确定</button>
            </form>
        </div>

        <div class="box-content" id="prizeListHTML" style="display:none;">
            <div class="row-fluid alert alert-success">
                <strong>温馨提示1：</strong>抽奖转盘为8等分扇形区域，每个区域的ID为按顺时针方向0点开始的位置从1至8依次递增
            </div>
			<div class="row-fluid alert alert-success">
                <strong>温馨提示2：</strong>奖项名字为转盘上的名字；奖品名字为抽中后弹出的具体奖品名称。如需要“谢谢参与”这种不中奖的情况，请把奖品和奖项名称都改为谢谢参与
            </div>
			<div class="row-fluid alert alert-danger">
                <strong>注意事项：</strong>请确保8个奖品的抽中概率加起来是100% &nbsp;&nbsp;<strong>奖品图片尺寸：</strong>：70x70
            </div>
            <table border="0" cellspacing="0" cellpadding="2" class="layui-hide" id="prizeTable">
            </table>
        </div>

        <div class="box-content" id="modifyRateHTML" style="display:none;">
            <form role="form">
				<div class="form-group">
                    <label class="control-label">输入奖项名字,最多可输入四个字（如：行家初遇、特等奖）</label>
                    <input type="text" class="form-control" id="txtType" placeholder="" maxlength="4">
                </div>
                <div class="form-group">
                    <label class="control-label">输入奖品名字</label>
                    <input type="text" class="form-control" id="txtPrizeName" placeholder="">
                </div>
                <div class="form-group">
                    <label class="control-label">输入抽中概率,支持两位小数（如：2.5%，请输入2.5）</label>
                    <input type="text" class="form-control" id="txtRate" placeholder="" onkeyup="RateNumberCheck(this)">
                </div>
                <div class="form-group">
                    <label class="control-label">输入奖品总数</label>
                    <input type="number" class="form-control" id="txtSum" placeholder="">
                </div>
                <button type="button" class="btn btn-default" id="btnUpdatePrize" style="margin-left:40%;">确定</button>
            </form>
        </div>

        <div class="box-content" id="resetDataHTML" style="display:none;">
            <div class="box-content">
                <div class="alert alert-danger">
                    <strong>请注意!</strong> 本操作将重置所有参与本活动用户的抽奖记录以及奖品列表中的中奖数量!正式上线后请勿重置数据，<strong>本功能仅供测试期间多次抽奖用！</strong>
                </div>
            </div>

            <div class="box-content">
                <button type="button" class="btn btn-danger" onclick="onClickReset();" style="margin-left:40%;">重置</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript" charset="utf-8">
	function RateNumberCheck(obj){
        obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
        obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
        obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
        obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //控制可输入的小数
    }

    $(document).on("click", "#btnAddActivity", function() {
        var contentHTML = document.getElementById("activityHTML");
        layer.open({
            type: 1,
            title: "新增问卷活动",
            area: ['320px', '270px'],
            content: $("#activityHTML"),
            end: function(index, layero) {
                $(document).off("click", "#btnUpdateActivity")
                contentHTML.style.display = 'none';
            },
            success: function(layero, index) {
                $("#txtName").val("");
                $("#txtTips").val("");

                $(document).on("click", "#btnUpdateActivity", function() {
                    var activityName = $("#txtName").val();
                    var activityTips = $("#txtTips").val();
                    $.ajax({
                        type: 'post',
                        dataType: "json",
                        data: {
                            activityName: activityName,
                            activityTips: activityTips
                        },
                        url: "ajax.php?action=addActivity",
                        success: function(result) {
                            if (result && result.code == 200) {
                                console.log("添加成功");
                                window.location.reload();
                                layer.close();
                                contentHTML.style.display = 'none';
                            } else {
                                layer.alert("添加失败");
                            }
                        },
                        error: function(errMsg) {
                            layer.alert("添加出错");
                        }
                    });
                });
            }
        });
    });

    layui.use('table', function() {
        var table = layui.table;
        table.render({
            elem: '#activityTable',
            url: './ajax.php?action=activityList'
                //,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                ,
            page: true,
            limit: 30,
            cols: [
                [{
                        field: 'id',
                        title: '问卷活动ID',
                        width: '5%',
                        align: 'center'
                    },
                    {
                        field: 'activity_name',
                        title: '问卷活动名称',
                        width: '10%',
                        align: 'center'
                    },
                    {
                        field: 'activity_tips',
                        title: '领奖提示',
                        width: '20%',
                        align: 'center'
                    },
					{
						field: 'bg_img',
						title: '自定义背景',
						align: 'center',
						templet: function(d) {
							d.activityID = d.id
							d.type = 'act'
							let btnDel = '<button type="button" id="delBgImg' +  d.id + '" class="btn btn-primary" style="margin-left:5px;margin-top:5px;" onclick="delImg(' + JSON.stringify(d).replace(/"/g, '&quot;') + ', 1);" ><i class="layui-icon">&#x1006;</i></button>';

							let btnUp = '<button type="button" class="btn btn-primary" style="margin-left:5px;margin-top:5px;" id="upBgImg' + d.id + '"><i class="layui-icon">&#xe67c;</i></button>'
							
							let imgURL = d.bg_img ? ('<?php echo URL_FOR_SAVE_PATH; ?>' + d.bg_img) : '""'
							let imgPrev = '<img onclick="showPrizeImg(this)" src=' + imgURL + ' id=bg_img_' + d.id + '>'
							if(d.bg_img != null && d.bg_img.length > 0)
							{
								return imgPrev + btnUp + btnDel
							}
							
							return imgPrev + btnUp
						}
					},
					{
						field: 'title_img',
						title: '自定义标题',
						align: 'center',
						width: '15%',
						templet: function(d) {
							d.activityID = d.id
							d.type = 'act'
							let btnDel = '<button type="button" id="delTitleImg' +  d.id + '" class="btn btn-primary" style="margin-left:5px;margin-top:5px;" onclick="delImg(' + JSON.stringify(d).replace(/"/g, '&quot;') + ', 2);" ><i class="layui-icon">&#x1006;</i></button>';

							let btnUp = '<button type="button" class="btn btn-primary" style="margin-left:5px;margin-top:5px;" id="upTitleImg' + d.id + '"><i class="layui-icon">&#xe67c;</i></button>'
							
							let imgURL = d.title_img ? ('<?php echo URL_FOR_SAVE_PATH; ?>' + d.title_img) : '""'
							let imgPrev = '<img onclick="showPrizeImg(this)" src=' + imgURL + ' id=title_img_' + d.id + '>'
							if(d.title_img != null && d.title_img.length > 0)
							{
								return imgPrev + btnUp + btnDel
							}
							
							return imgPrev + btnUp
						}
					},
                    {
                        title: '操作',
                        align: 'center',
                        templet: function(d) {
                            var edit = '<button type="button" class="btn btn-primary" style="margin-right:5px;margin-top:5px;" onclick="edit(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >修改</button>'

                            var del = '<button type="button" class="btn btn-primary" style="margin-right:5px;margin-top:5px;" onclick="del(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >删除</button>'

                            var user = '<button type="button" class="btn btn-primary" style="margin-right:5px;margin-top:5px;" onclick="showUserList(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >用户列表</button>'

                            var reward = '<button type="button" class="btn btn-primary" style="margin-right:5px;margin-top:5px;" onclick="showPrizeList(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >奖品列表</button>'

                            var question = '<button type="button" class="btn btn-primary" style="margin-right:5px;margin-top:5px;" onclick="showQuestionList(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >题目列表</button>'

                            var reset = '<button type="button" class="btn btn-primary" style="margin-right:5px;margin-top:5px;" onclick="resetData(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >抽奖重置</button>'

							return question + user + reward + reset + edit + del;
                        }
                    }
                ]
            ],
			done:function(res, curr, count){
				for(let i = 0; i < res.data.length; ++i)
				{
					let itemData = res.data[i];
					uploadActImg(itemData.id, 'upBgImg' + itemData.id, 'bg')
					uploadActImg(itemData.id, 'upTitleImg' + itemData.id, 'title')
				}
			}
        });
    });

    function edit(data) {
        var contentHTML = document.getElementById("activityHTML");
        layer.open({
            type: 1,
            title: "修改活动名称",
            area: ['320px', '270px'],
            content: $("#activityHTML"),
            end: function(index, layero) {
                $(document).off("click", "#btnUpdateActivity")
                contentHTML.style.display = 'none';
            },
            success: function(layero, index) {
                $("#txtName").val(data.activity_name);
                $("#txtTips").val(data.activity_tips);

                $(document).on("click", "#btnUpdateActivity", function() {
                    var activityName = $("#txtName").val();
                    var activityTips = $("#txtTips").val();
                    $.ajax({
                        type: 'post',
                        dataType: "json",
                        data: {
                            activityID: data.id,
                            activityName: activityName,
                            activityTips: activityTips
                        },
                        url: "ajax.php?action=modifyActivity",
                        success: function(result) {
                            if (result && result.code == 200) {
                                console.log("修改成功");
                                window.location.reload();
                                layer.close();
                                contentHTML.style.display = 'none';
                            } else {
                                layer.alert("修改失败");
                            }
                        },
                        error: function(errMsg) {
                            layer.alert("修改出错");
                        }
                    });
                });
            }
        });
    }

    $(document).on("click", "#btnAddQuestion", function() {
        let curActivityID = $("#curActivityID").val();
        var contentHTML = document.getElementById("questionHTML");
        layer.open({
            type: 1,
            title: "新增问卷题目",
            area: ['50%', '62%'],
            content: $("#questionHTML"),
            end: function(index, layero) {
                $(document).off("click", "#btnUpdateQuestion")
                contentHTML.style.display = 'none';
            },
            success: function(layero, index) {
                initNewQuestion();
                $("#addQuestionLayerIndex").val(index);

                $(document).on("click", "#btnUpdateQuestion", function() {
                    let activityID = $("#curActivityID").val();;
                    let order = $("#qOrder").val();
                    let question = $("#qContent").val();
                    let options = [];
                    for (let i = 1; i <= totalOptionCount; ++i) {
                        var td = $("#optRow" + i).children("td").eq(1);
                        var optContent = td.find("input").val();
                        options.push(optContent);
                    }

                    let answers = "";
                    let isEmpty = true;
                    if (curQuestionType == 1) {
                        var tmp = []
                        var idx = $("input[name='answerRadio']:checked").val();
                        if (Number(idx) > 0) {
                            tmp.push(Number(idx))
                            answers = JSON.stringify(tmp)
                            isEmpty = false;
                        }
                    } else {
                        var chks = document.getElementsByName('answerCheckBox')
                        var tmp = []
                        for (let i = 0; i < chks.length; i++) {
                            if (chks[i].checked == true) {
                                tmp.push(i + 1)
                                isEmpty = false;
                            }
                        }
                        answers = JSON.stringify(tmp)
                    }

                    if (curQuestionType != 3 && (answers == "" || answers == null || isEmpty)) {
                        layer.alert("正确答案未勾选");
                        return;
                    }

                    $.ajax({
                        type: 'post',
                        dataType: "json",
                        data: {
                            activityID: activityID,
                            order: order,
                            type: curQuestionType,
                            question: question,
                            options: (curQuestionType == 3) ? "" : JSON.stringify(options),
                            answers: (curQuestionType == 3) ? "" : answers,
                        },
                        url: "ajax.php?action=addQuestion",
                        success: function(result) {
                            if (result && result.code == 200) {
                                console.log("添加成功");
                                layui.table.reload('questionTable');
                                let addQuestionLayerIndex = $("#addQuestionLayerIndex").val();
                                layer.close(addQuestionLayerIndex);
                            } else {
                                layer.alert("添加失败");
                            }
                        },
                        error: function(errMsg) {
                            layer.alert("添加出错");
                        }
                    });
                });
            }
        });
    });

    $('input[type=radio][name=optionRadio]').change(function() {
        let type = $("input[name='optionRadio']:checked").val();
        updateTableByQuestionType(type, true);
    });

    let curQuestionType = 1;
    let totalOptionCount = 2;

    function initNewQuestion() {
        $("#qOrder").val(0);

        for (let i = 1; i <= 3; ++i) {
            $("input[name='optionRadio'][value='" + i + "']").prop("checked", (i == 1));
        }
        curQuestionType = 1;
        totalOptionCount = 2;

        $("#qContent").val("");

        var table = $("#optionsTable");
        table.children("tbody").remove();

        var text = '';
        for (let i = 1; i <= totalOptionCount; ++i) {
            text += '<tr id=optRow' + i + '><td width="10%"><label class="control-label">' + ("选项" + i) + '</label></td>'
            text += '<td><input type="text" class="form-control" id=' + ("qOptions" + i) + ' placeholder="输入选项内容" value=""></td>'
            text += '<td width=50></td></tr>'
        }
        table.append(text);

        generateAnswerContent();

        updateTableByQuestionType(curQuestionType);
    }

    function updateTableByQuestionType(type, genAnswer) {
        curQuestionType = type;
        var optionTR = $("#quOptions");
        var answerTR = $("#quAnswers");

        if (type == 3) {
            optionTR.hide();
            answerTR.hide();
        } else {
            optionTR.show();
            answerTR.show();
            if (genAnswer) {
                generateAnswerContent();
            }

        }
    }

    function addOpt() {
        if (totalOptionCount >= 8) {
            layer.alert("最多只支持8个选项")
            return;
        }
        totalOptionCount++;
        var table = $("#optionsTable");

        var text = '';
        text += '<tr id=optRow' + totalOptionCount + '><td width="10%"><label class="control-label">' + ("选项" + totalOptionCount) + '</label></td>'
        text += '<td><input type="text" class="form-control" id=' + ("qOptions" + totalOptionCount) + ' placeholder="输入选项内容" value=""></td>'

        if (totalOptionCount <= 2) {
            text += '<td width=50></td></tr>'
        } else {
            text += '<td width=50><a class="btn btn-info" onclick="delOpt(' + totalOptionCount + ')"><i class="glyphicon glyphicon-trash icon-white"></i></a></td></tr>'
        }

        table.append(text);

        generateAnswerContent();
    }

    function delOpt(optIndex) {
        if (totalOptionCount <= 2) {
            layer.alert("选择题最少需要保留2个选项")
            return;
        }
        var tr = $("#optRow" + optIndex);
        if (tr) {
            var optContentArray = [];
            for (let i = 1; i <= totalOptionCount; ++i) {
                if (optIndex == i) {
                    continue;
                }
                var td = $("#optRow" + i).children("td").eq(1);
                var optContent = td.find("input").val();
                optContentArray.push(optContent);
            }
            tr.remove();
            totalOptionCount--;

            var table = $("#optionsTable");
            table.children("tbody").remove();

            var text = '';
            for (let i = 1; i <= totalOptionCount; ++i) {
                text += '<tr id=optRow' + i + '><td width="10%"><label class="control-label">' + ("选项" + i) + '</label></td>'
                text += '<td><input type="text" class="form-control" id=' + ("qOptions" + i) + ' placeholder="输入选项内容" value="' + optContentArray[i - 1] + '"></td>'
                if (i <= 2) {
                    text += '<td width=50></td></tr>'
                } else {
                    text += '<td width=50><a class="btn btn-info" onclick="delOpt(' + i + ')"><i class="glyphicon glyphicon-trash icon-white"></i></a></td></tr>'
                }

            }
            table.append(text);

            generateAnswerContent();
        }
    }

    function generateAnswerContent() {
        if (curQuestionType == 3) {
            return;
        }
        var answerTD = "";
        for (let i = 1; i <= totalOptionCount; ++i) {
            if (curQuestionType == 1) {
                answerTD += '<label class="radio-inline"><input type="radio" name="answerRadio" id="answerRadio' + i + '" value="' + i + '">选项' + i + '</label>'
            } else if (curQuestionType == 2) {
                answerTD += '<label class="checkbox-inline"><input type="checkbox" name="answerCheckBox" id="answerCheck' + i + '" value="' + i + '">选项' + i + '</label>'
            }
        }
        var td = $("#quAnswers").children("td").eq(1);
        td.html(answerTD);
    }

    function showQuestionList(data) {

        layui.use('table', function() {
            var table = layui.table;
            var contentHTML = document.getElementById("questionListHTML");
            layer.open({
                type: 1,
                title: "【" + data.activity_name + "】的题目列表",
                area: ['70%', '80%'],
                content: $("#questionListHTML"),
                end: function(index, layero) {
                    contentHTML.style.display = 'none';
                },
                success: function(layero, index) {
                    $("#curActivityID").val(data.id);
                    table.render({
                        elem: '#questionTable',
                        url: './ajax.php?action=getQuestionList&activityID=' + data.id,
                        page: true,
                        limit: 30,
                        cols: [
                            [{
                                field: 'id',
                                title: '题目ID',
                                width: 100,
                                align: 'center'
                            }, {
                                field: 'order',
                                title: '顺序值',
                                width: 100,
                                align: 'center'
                            }, {
                                field: 'type',
                                title: '题目类型',
                                width: 100,
                                align: 'center',
                                templet: function(d) {
                                    if (d.type == null) {
                                        return "";
                                    }
                                    let result = "";
                                    switch (parseInt(d.type)) {
                                        case 1:
                                            result = "单选";
                                            break;
                                        case 2:
                                            result = "多选";
                                            break;
                                        case 3:
                                            result = "问答";
                                            break;
                                    }
                                    return result;
                                }
                            }, {
                                field: 'question',
                                title: '题目内容',
                                align: 'center'
                            }, {
                                field: 'options',
                                title: '选项和答案',
                                align: 'center',
                                templet: function(d) {
                                    if (parseInt(d.type) == 3) {
                                        return "无";
                                    }

                                    if (!d.options) {
                                        return "";
                                    }

                                    let result = "";
                                    let options = JSON.parse(d.options);
                                    let answers = d.answer ? JSON.parse(d.answer) : [];

                                    let right = '<span class="label-success label label-default" style="margin-left:10px;margin-right:10px;"><i class="glyphicon glyphicon-ok "></i></span>'
                                    for (let i = 0; i < options.length; ++i) {
                                        let flag = ""
                                        for (let j = 0; j < answers.length; ++j) {
                                            if (answers[j] == (i + 1)) {
                                                flag = right
                                                break;
                                            }

                                        }
                                        result += "选项" + (i + 1) + "：" + options[i] + flag + "<br/>";
                                    }
                                    return result;
                                }
                            }, {
                                title: '操作',
                                width: 150,
                                align: 'center',
                                templet: function(d) {
                                    let edit = '<button type="button" class="btn btn-primary" style="margin-right:5px;margin-top:5px;" onclick="editQuestion(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >修改</button>';

                                    let del = '<button type="button" class="btn btn-primary" style="margin-right:5px;margin-top:5px;" onclick="delQuestion(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >删除</button>';

                                    return edit + del;
                                }
                            }]
                        ]
                    });
                }
            });
        });
    }

    function editQuestion(data) {
        var contentHTML = document.getElementById("questionHTML");
        var questionID = data.id;
        let activityID = data.activity_id;
        layui.use('table', function() {
            var table = layui.table;
            layer.open({
                type: 1,
                title: "修改题目:【ID：" + data.id + "】",
                area: ['50%', '62%'],
                content: $("#questionHTML"),
                end: function(index, layero) {
                    $(document).off("click", "#btnUpdateQuestion")
                    contentHTML.style.display = 'none';
                },
                success: function(layero, index) {
                    $("#addQuestionLayerIndex").val(index);
                    $("#qOrder").val(data.order);

                    for (let i = 1; i <= 3; ++i) {
                        $("input[name='optionRadio'][value='" + i + "']").prop("checked", (i == data.type));
                    }

                    curQuestionType = Number(data.type);

                    let optionData = []
                    if (data.options) {
                        optionData = JSON.parse(data.options)
                        totalOptionCount = optionData.length;
                    } else {
                        totalOptionCount = 0
                    }

                    $("#qContent").val(data.question);

                    var table = $("#optionsTable");
                    table.children("tbody").remove();

                    var text = '';
                    for (let i = 1; i <= totalOptionCount; ++i) {
                        text += '<tr id=optRow' + i + '><td width="10%"><label class="control-label">' + ("选项" + i) + '</label></td>'
                        text += '<td><input type="text" class="form-control" id=' + ("qOptions" + i) + ' placeholder="输入选项内容" value="' + optionData[i - 1] + '"></td>'

                        if (i <= 2) {
                            text += '<td width=50></td></tr>'
                        } else {
                            text += '<td width=50><a class="btn btn-info" onclick="delOpt(' + i + ')"><i class="glyphicon glyphicon-trash icon-white"></i></a></td></tr>'
                        }
                    }
                    table.append(text);

                    var answerTD = "";
                    for (let i = 1; i <= totalOptionCount; ++i) {
                        if (curQuestionType == 1) {
                            answerTD += '<label class="radio-inline"><input type="radio" name="answerRadio" id="answerRadio' + i + '" value="' + i + '">选项' + i + '</label>'
                        } else if (curQuestionType == 2) {
                            answerTD += '<label class="checkbox-inline"><input type="checkbox" name="answerCheckBox" id="answerCheck' + i + '" value="' + i + '">选项' + i + '</label>'
                        }
                    }
                    var td = $("#quAnswers").children("td").eq(1);
                    td.html(answerTD);

                    let answerData = []
                    if (data.answer) {
                        answerData = JSON.parse(data.answer)
                    }
                    for (let i = 0; i < answerData.length; ++i) {
                        let opt = answerData[i]
                        if (curQuestionType == 1) {
                            $("input[name='answerRadio'][value='" + opt + "']").prop("checked", true);
                        } else {
                            $("input[name='answerCheckBox'][value='" + opt + "']").prop("checked", true);
                        }
                    }

                    updateTableByQuestionType(curQuestionType);

                    $(document).on("click", "#btnUpdateQuestion", function() {

                        let order = $("#qOrder").val();
                        let question = $("#qContent").val();
                        let options = [];
                        for (let i = 1; i <= totalOptionCount; ++i) {
                            var td = $("#optRow" + i).children("td").eq(1);
                            var optContent = td.find("input").val();
                            options.push(optContent);
                        }

                        let answers = "";
                        let isEmpty = true;
                        if (curQuestionType == 1) {
                            var tmp = []
                            var idx = $("input[name='answerRadio']:checked").val();
                            if (Number(idx) > 0) {
                                tmp.push(Number(idx))
                                answers = JSON.stringify(tmp)
                                isEmpty = false;
                            }

                        } else {
                            var chks = document.getElementsByName('answerCheckBox')
                            var tmp = []
                            for (let i = 0; i < chks.length; i++) {
                                if (chks[i].checked == true) {
                                    tmp.push(i + 1)
                                    isEmpty = false;
                                }
                            }
                            answers = JSON.stringify(tmp)
                        }

                        if (curQuestionType != 3 && (answers == "" || answers == null || isEmpty)) {
                            layer.alert("正确答案未勾选");
                            return;
                        }

                        $.ajax({
                            type: 'post',
                            dataType: "json",
                            data: {
                                questionID: questionID,
                                activityID: activityID,
                                order: order,
                                type: curQuestionType,
                                question: question,
                                options: (curQuestionType == 3) ? "" : JSON.stringify(options),
                                answers: (curQuestionType == 3) ? "" : answers,
                            },
                            url: "ajax.php?action=modifyQuestion",
                            success: function(result) {
                                if (result && result.code == 200) {
                                    console.log("修改成功");
                                    layui.table.reload('questionTable');
                                    let addQuestionLayerIndex = $("#addQuestionLayerIndex").val();
                                    layer.close(addQuestionLayerIndex);
                                } else {
                                    layer.alert("修改失败");
                                }
                            },
                            error: function(errMsg) {
                                layer.alert("修改出错");
                            }
                        });
                    });
                }
            });
        });
    }

    function delQuestion(data) {
        layer.open({
            content: "确定要刪除题目ID【" + data.id + "】的题目吗?",
            btn: ['确定', '取消'],
            yes: function(index, layero) {
                //确定的回调
                $.ajax({
                    type: 'post',
                    dataType: "json",
                    data: {
                        questionID: data.id
                    },
                    url: "ajax.php?action=delQuestion",
                    success: function(result) {
                        if (result && result.code == 200) {
                            console.log("删除成功");
                            layui.table.reload('questionTable');
                            layer.close(index);
                        } else {
                            layer.alert("删除失败");
                        }
                    },
                    error: function(errMsg) {
                        layer.alert("删除出错");
                    }
                });
            },
            btn2: function(index, layero) {
                    //取消的回调
                }

                ,
            cancel: function() {
                //右上角关闭回调
            }
        });
    }

    $(document).on("click", "#btnExport", function() {
        let curActivityID = $("#curActivityID").val();
        //window.location.href = "ajax.php?action=export&activityID=" + curActivityID
		
		var loading = layer.load(1, {
			shade: [0.5, '#000'],
			time: 10*1000
		});
		$.ajax({
			dataType: "json",
			url: "ajax.php?action=getallusers&activityID=" + curActivityID,
			success: function(result) {
				if (result && result.code == 200) {
					console.log("导出成功");
					
					let data = [];
					for(let i = 0; i < result.data.length; ++i)
					{
						let itemData = result.data[i];
						let optResult = "";
						if(itemData.options)
						{
							let opts = itemData.options.substr(0, itemData.options.length - 1);
							let answers = opts.split(";");
							
							for (let i = 0; i < answers.length; ++i) {
								var info = answers[i];
								info = info.replace(/[,]/g, "_");
								var info = info == "" ? "未选择" : info;
								optResult += "第" + (i + 1) + "题：" + info;
								if(i != answers.length - 1)
								{
									optResult += " "
								}
							}
						}
						
						data.push([itemData.user_id, itemData.user_name, itemData.user_number, itemData.um, optResult, itemData.custom_input, itemData.prize])
					}
					layui.table.exportFile(['用户ID', '员工姓名', '员工工号', 'UM号', '选择题', '问答题', '中奖奖品ID'], data, 'csv', '用户列表');
					layer.close(loading);
				} else {
					layer.close(loading);
					layer.alert("导出失败");
				}
			},
			error: function(errMsg) {
				layer.close(loading);
				layer.alert("导出错误");
			}
		});
    });

    function showUserList(data) {
        layui.use('table', function() {
            var table = layui.table;
            var contentHTML = document.getElementById("userListHTML");
            layer.open({
                type: 1,
                title: "参与【" + data.activity_name + "】的用户列表",
                area: ['70%', '80%'],
                content: $("#userListHTML"),
                end: function(index, layero) {
                    contentHTML.style.display = 'none';
                },
                success: function(layero, index) {
                    $("#curActivityID").val(data.id);
                    table.render({
                        elem: '#userTable',
                        url: './ajax.php?action=userinfo&activityID=' + data.id,
                        page: true,
						//toolbar:true,
						//defaultToolbar: ['exports'],
                        limit: 30,
                        cols: [
                            [{
                                field: 'user_id',
                                title: '用户ID',
                                align: 'center'
                            }, {
                                field: 'user_name',
                                title: '员工姓名',
                                align: 'center'
                            }, {
                                field: 'user_number',
                                title: '员工工号',
                                align: 'center'
                            },  {
                                field: 'um',
                                title: 'UM号',
                                align: 'center'
                            }, {
                                field: 'options',
                                title: '选择题',
                                align: 'center',
                                templet: function(d) {
                                    if (d.options == null) {
                                        return "";
                                    }
									
									if(d.options.charAt(d.options.length - 1) == ";")
									{
										d.options = d.options.substr(0, d.options.length - 1);
									}
                                    let answers = d.options.split(";");
                                    let result = "";

                                    for (let i = 0; i < answers.length; ++i) {
                                        var info = answers[i];
                                        var info = info == "" ? "未选择" : info;
                                        result += "第" + (i + 1) + "题：" + info + "<br/>";
                                    }
                                    return result;
                                }
                            }, {
                                field: 'custom_input',
                                title: '问答题',
                                align: 'center'
                            }, {
                                field: 'prize',
                                title: '中奖奖品',
                                align: 'center'
                            }]
                        ]
                    });
                }
            });
        });
    }

    function del(data) {
        layer.open({
            content: "确定要刪除活动【" + data.activity_name + "】吗?",
            btn: ['确定', '取消'],
            yes: function(index, layero) {
                //确定的回调
                $.ajax({
                    type: 'post',
                    dataType: "json",
                    data: {
                        activityID: data.id
                    },
                    url: "ajax.php?action=delActivity",
                    success: function(result) {
                        if (result && result.code == 200) {
                            console.log("删除成功");
                            window.location.reload();;
                        } else {
                            layer.alert("删除失败");
                        }
                    },
                    error: function(errMsg) {
                        layer.alert("删除出错");
                    }
                });
            },
            btn2: function(index, layero) {
                    //取消的回调
                }

                ,
            cancel: function() {
                //右上角关闭回调
            }
        });
    }

    function showPrizeList(data) {
        layui.use('table', function() {
            var table = layui.table;
            var contentHTML = document.getElementById("prizeListHTML");
			var activityID = data.id
            layer.open({
                type: 1,
                title: "【" + data.activity_name + "】的奖品列表",
                area: ['70%', '70%'],
                content: $("#prizeListHTML"),
                end: function(index, layero) {
                    contentHTML.style.display = 'none';
                },
                success: function(layero, index) {
                    table.render({
                        elem: '#prizeTable',
                        url: './ajax.php?action=prizeConfig&activityID=' + activityID,
                        cols: [
                            [{
                                field: 'order',
                                title: '转盘位置',
                                width: '8%',
                                align: 'center'
                            }, {
                                field: 'prize_type',
                                title: '奖项名字',
                                align: 'center'
                            }, {
                                field: 'prize_name',
                                title: '奖品名字',
                                align: 'center'
                            }, {
                                field: 'prize_img',
                                title: '奖品图片',
                                align: 'center',
								templet: function(d) {
									//d.prize_img = "https://img-blog.csdnimg.cn/20201014180756927.png?x-oss-process=image/resize,m_fixed,h_64,w_64"
									
									d.activityID = activityID
									d.type = 'prize'
									let btnDel = '<button type="button" id="btnDel' +  d.id + '" class="btn btn-primary" style="margin-left:5px;margin-top:5px;" onclick="delImg(' + JSON.stringify(d).replace(/"/g, '&quot;') + ', 0);" ><i class="layui-icon">&#x1006;</i></button>';
	
									let btnUp = '<button type="button" class="btn btn-primary" style="margin-left:5px;margin-top:5px;" id="btnUpImage' + d.id + '"><i class="layui-icon">&#xe67c;</i></button>'
									
									let imgURL = d.prize_img ? ('<?php echo URL_FOR_SAVE_PATH; ?>' + d.prize_img) : '""'
									let imgPrev = '<img onclick="showPrizeImg(this)" src=' + imgURL + ' id=prize_img_' + d.id + '>'
									if(d.prize_img != null && d.prize_img.length > 0)
									{
										return imgPrev + btnUp + btnDel
									}
									
									return imgPrev + btnUp
                                }
                            }, {
                                field: 'prize_rate',
                                title: '抽中概率',
                                width: '8%',
                                align: 'center',
                                templet: function(d) {
                                    return d.prize_rate + '%'
                                }
                            }, {
                                field: 'sum',
                                title: '奖品总数',
                                width: '8%',
                                align: 'center'
                            }, {
                                field: 'cur',
                                title: '抽中数量',
                                width: '8%',
                                align: 'center'
                            }, {
                                title: '操作',
                                width: '8%',
                                align: 'center',
                                templet: function(d) {
                                    return '<button type="button" class="btn btn-primary" onclick="editPrize(' + JSON.stringify(d).replace(/"/g, '&quot;') + ');" >修改</button>';
                                }
                            }]
                        ],
						done:function(res, curr, count){
							for(let i = 0; i < res.data.length; ++i)
							{
								let itemData = res.data[i];
								uploadImg(activityID, itemData.id)
							}
						}
                    });
                }
            });
        });
    }

	function uploadImg(activityID, itemID){
		layui.use('upload', function(){
		  var upload = layui.upload;
		  var upInst = upload.render({
				elem: '#btnUpImage' + itemID
				,url: "ajax.php?action=uploadImg"
				,data:{id:itemID, activityID:activityID, type:'prize', img:""}
				,acceptMime: 'image/png'
				,auto:true
				,field:"prizeImg"
				/*,choose:function(obj){
					//预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
					obj.preview(function(index, file, result){
					  console.log(index); //得到文件索引
					  console.log(file); //得到文件对象
					  console.log(result); //得到文件base64编码，比如图片
					  
					  let img = new Image()
					  img.src = result
					  img.onload = function(){
						  if(img.width != 70 && img.height != 70)
						  {
							  layer.alert("奖品图片的长宽像素必须为70")
							  return false
						  }
						  else{
							  obj.upload(index, file)
						  }
					  }
					  //obj.resetFile(index, file, '123.jpg'); //重命名文件名，layui 2.3.0 开始新增
					  
					  //这里还可以做一些 append 文件列表 DOM 的操作
					  
					  //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
					  //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
					});
				}*/
				,done: function(res){
					if(res.code == 200)
					{
						//$('#prize_img_' + itemID).attr("src", res.url)
						layer.msg('上传成功');
						layui.table.reload('prizeTable');
					}
					else{
						layer.alert(res.msg);
					}
				}
			});
		});
	}
	
	function uploadActImg(activityID, tag, imgType)
	{
		layui.use('upload', function(){
		  var upload = layui.upload;
		  var upInst = upload.render({
				elem: '#' + tag
				,url: "ajax.php?action=uploadImg"
				,data:{id:activityID, activityID:activityID, type:'act', img:imgType}
				,acceptMime: 'image/png'
				,auto:true
				,field:"prizeImg"
				,done: function(res){
					if(res.code == 200)
					{
						layer.msg('上传成功');
						layui.table.reload('activityTable');
					}
					else{
						layer.alert(res.msg);
					}
				}
			});
		});
	}

	function showPrizeImg(t) {
		//var t = $(t).find("img");
		//页面层
		layer.open({
			type: 1,
			skin: 'layui-layer-rim', //加上边框
			area: ['500px', '500px'], //宽高 t.width() t.height() 
			shadeClose: true, //开启遮罩关闭
			end: function (index, layero) {
				return false;
			},
			content: '<div style="text-align:center"><img src="' + $(t).attr('src') + '" + " width="50%" height="50%"/></div>'
		});
	}
	
	function delImg(data, idx){
		let type = data.type
		let itemID = data.id
		let activityID = data.activityID
		let imgIdx = idx
		$.ajax({
		type: 'post',
		dataType: "json",
		data: {
			itemID: itemID,
			activityID:activityID,
			type:type,
			imgIdx:imgIdx
		},
		url: "ajax.php?action=delImg",
		success: function(result) {
			if (result && result.code == 200) {
				if(type == 'prize')
				{
					layui.table.reload('prizeTable');
				}
				else{
					layui.table.reload('activityTable');
				}
				
			} else {
				layer.alert("删除失败");
			}
		},
		error: function(errMsg) {
			layer.alert("修改失败");
		}
	});
	}

    function editPrize(data) {
        var contentHTML = document.getElementById("modifyRateHTML");
        layui.use('table', function() {
            var table = layui.table;
            layer.open({
                type: 1,
                title: "修改奖品信息:【ID：" + data.id + "】" + data.prize_name,
                area: ['400px', '430px'],
                content: $("#modifyRateHTML"),
                end: function(index, layero) {
                    $(document).off("click", "#btnUpdatePrize")
                    contentHTML.style.display = 'none';
                },
                success: function(layero, index) {
                    $("#txtType").val(data.prize_type);
                    $("#txtPrizeName").val(data.prize_name);
                    $("#txtSum").val(data.sum);
                    $("#txtRate").val(data.prize_rate);

                    $(document).on("click", "#btnUpdatePrize", function() {
                        var sum = $("#txtSum").val();
                        var rate = $("#txtRate").val();
						rate = Number(rate).toFixed(2);
                        var type = $("#txtType").val();
                        var name = $("#txtPrizeName").val();

                        $.ajax({
                            type: 'post',
                            dataType: "json",
                            data: {
                                itemID: data.id,
                                type: type,
                                name: name,
                                sum: sum,
                                rate: rate
                            },
                            url: "ajax.php?action=modifyItem",
                            success: function(result) {
                                if (result && result.code == 200) {
                                    console.log("修改成功");
                                    table.reload('prizeTable');
                                    layer.close(index);
                                    contentHTML.style.display = 'none';
                                } else {
                                    layer.alert("修改失败");
                                }
                            },
                            error: function(errMsg) {
                                layer.alert("修改失败");
                            }
                        });
                    });
                }
            });
        });
    }

    function resetData(data) {
        var contentHTML = document.getElementById("resetDataHTML");
        layer.open({
            type: 1,
            title: "重置【" + data.activity_name + "】的数据",
            area: ['500px', '260px'],
            content: $("#resetDataHTML"),
            end: function(index, layero) {
                contentHTML.style.display = 'none';
            },
            success: function(layero, index) {
                $("#resetID").val(data.id);
                $("#resetLayerIndex").val(index);
            }
        });
    }

    function onClickReset() {
        layui.use('layer', function() {
            let resetID = $("#resetID").val();
            let resetLayerIndex = $("#resetLayerIndex").val();
            layer.open({
                content: '确定要重置数据吗？',
                btn: ['确定', '取消'],
                yes: function(index, layero) {
                    //确定的回调
                    $.ajax({
                        type: 'post',
                        url: "ajax.php?action=resetdata&activityID=" + resetID,
                        success: function(result) {
                            if (result && result.code == 200) {
                                layer.close(index);
                                parent.layer.close(resetLayerIndex);
                                layer.alert("重置成功");
                            } else {
                                layer.alert("重置失败");
                            }
                        },
                        error: function(errMsg) {
                            layer.alert("重置失败");
                        }
                    });
                },
                btn2: function(index, layero) {
                        //取消的回调
                    }

                    ,
                cancel: function() {
                    //右上角关闭回调
                }
            });
        });
    }
</script>

<?php require_once('footer.php'); ?>