let tableIns;
let openIndex;
let multiSelectTag;

let mainTableUrl = "/backstage_user/findAll";
let mainSaveUrl = "/backstage_game/saveBaseInfo";
let mainDeleteUrl = "/backstage_user/delete";
let mainUploadUrl = "/backstage_game/uploadImg";
let mainGameDetailUrl = "/backstage_game/findGameDetail";


layui.config({
    base: ctx + '/common/'
}).extend({
    xmSelect: 'layui/xm-select',
    step: 'step-lay/step',
    dragMove: 'dragMove/dragMove'
})
layui.use(['element', 'form', 'table', 'layer', 'laydate', 'util', 'upload', 'xmSelect', 'step', 'dragMove'], function () {
    let element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    let laydate = layui.laydate;
    let table = layui.table, upload = layui.upload, form = layui.form;//select、单选、复选等依赖form
    let step = layui.step, xmSelect = layui.xmSelect, dragMove = layui.dragMove;//引入工具
    let layer = layui.layer;
    form.verify({
        // positiveInteger: [/^(([0-9]+[\.]?[0-9]+)|[1-9])$/, '只能填写正整数'],//必填，且只能输入正整数
        positiveInteger: [/^[1-9]\d*$/, '只能填写正整数'],//必填，且只能输入正整数
    });
    /**
     * 渲染图片查看
     */
    dragMove.render({
        elem: "#cardBody", //指向图片的父容器
        layerArea: ["960px", "720px"], //弹窗的宽高，同layer的area，默认["960px","720px"]
        layerShade: 0.6, //遮罩的透明度，同layer的shade，默认0.6
        layerMove: false, //触发拖动的元素，同layer的move，这里默认禁止，可设置为'.layui-layer-title'
        maxZoom: 1 //图片能放大的最大倍数，默认1倍
    });
    //主列表渲染
    tableIns = table.render({
        elem: '#mainTable'
        , url: ctx + mainTableUrl
        , method: 'POST'
        //请求前参数处理
        , request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'rows' //每页数据量的参数名，默认：limit
        }
        , where: {sidx: "desc", sord: "registerTime"}
        , response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
            , countName: 'records' //规定数据总数的字段名称，默认：count
            , dataName: 'rows' //规定数据列表的字段名称，默认：data
        }
        //响应后数据处理
        , parseData: function (res) { //res 即为原始返回的数据
            let data = res.data;
            console.log("返回的地址数据：", data);
            // if (data.rows && data.rows.length > 0) {
            // }
            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "records": data.records, //解析数据长度
                "rows": data.rows //解析数据列表
            };
        }
        , toolbar: '#mainTableToolbarDemo'
        , title: '列表'
        , cols: [[
            {field: 'userId', title: '用户ID', sort: true}
            , {field: 'username', title: '用户名称', sort: true}
            , {
                field: 'gender', title: '性别', templet: function (d) {
                    if (d.gender == 0) {
                        return '<span style="color: green">男</span>';
                    } else if (d.gender == 1) {
                        return '<span style="color: red">女</span>';
                    } else {
                        return '未添加:' + d.gender;
                    }
                }, sort: true
            }
            , {field: 'cityCode', title: '城市代码', sort: true}
            , {field: 'birthday', title: '生日', sort: true}
            , {field: 'signature', title: '签名'}
            , {field: 'avatarUrl', title: '头像', templet: '#avatarPicture'}
            , {field: 'height', title: '身高', sort: true}
            , {field: 'weight', title: '体重', sort: true}
            , {field: 'registerTime', title: '注册时间', sort: true}
            , {field: 'status', title: '状态', hide: true, sort: true}
            // , {field: 'createTime', title: '创建时间', hide: true, sort: true}
            // , {field: 'updateTime', title: '更新时间', hide: true, sort: true}
            , {fixed: 'right', title: '操作', width: 140, toolbar: '#mainTableBarDemo'}
        ]]
        , defaultToolbar: ['', 'exports', 'print']
        , page: true
        // , height: height
        , cellMinWidth: 80
    });

    //渲染步骤条
    step.render({
        elem: '#stepForm',
        filter: 'stepForm',
        width: '100%', //设置容器宽度
        stepWidth: '600px',
        height: '1000px',
        stepItems: [{
            title: '填入游戏基本信息'
        }, {
            title: '上传游戏对应图片'
        }, {
            title: '完成'
        }]
    });

    /**
     * 添加新游戏信息时候图片上传
     */
    let uploadIcon = upload.render({
        elem: '#iconAdd'
        , url: ctx + mainUploadUrl
        , data: {
            type: 'icon', gameId: function () {
                return $('#newGameId').val();
            }
        }
        // , auto: false
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#iconImageAdd').attr('src', result); //图片链接（base64）
            });
            // element.progress('iconProgress', '0%'); //进度条复位
            layer.msg('上传中', {icon: 16, time: 0});
            // console.log("before" + JSON.stringify(obj));
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功的一些操作
            //……
            $('#iconTextAdd').html(''); //置空上传失败的状态
            // console.log("done" + JSON.stringify(res));
            layer.msg('上传成功', {icon: 1});
        }
        , error: function () {
            //演示失败状态，并实现重传
            let demoText = $('#iconTextAdd');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadIcon.upload();
            });
        }
    });

    let uploadPicture = upload.render({
        elem: '#pictureAdd'
        , url: ctx + mainUploadUrl
        , data: {
            type: 'picture', gameId: function () {
                return $('#newGameId').val();
            }
        }
        , before: function (obj) {
            obj.preview(function (index, file, result) {
                $('#pictureImageAdd').attr('src', result);
            });
            layer.msg('上传中', {icon: 16, time: 0});
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功的一些操作
            $('#pictureTextAdd').html(''); //置空上传失败的状态
            layer.msg('上传成功', {icon: 1});
        }
        , error: function () {
            //演示失败状态，并实现重传
            let demoText = $('#pictureTextAdd');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadPicture.upload();
            });
        }
        //进度条
        // , progress: function (n, elem, e) {
        //     element.progress('pictureProgress', n + '%'); //可配合 layui 进度条元素使用
        //     if (n == 100) {
        //         layer.msg('上传完毕', {icon: 1});
        //     }
        // }
    });

    //多图片上传
    let uploadScroll = upload.render({
        elem: '#scrollAdd'
        , url: ctx + mainUploadUrl
        , data: {
            type: 'scroll', gameId: function () {
                return $('#newGameId').val();
            }
        }
        , multiple: true
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#scrollImageListAdd').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">')
            });
        }
        , done: function (res) {
            //上传完毕
            layer.msg('上传完毕', {icon: 1});
        }
    });

    /**
     * 修改信息时候图片上传
     */
    let modifyIcon = upload.render({
        elem: '#icon'
        , url: ctx + mainUploadUrl
        , data: {
            type: 'icon', gameId: function () {
                return $('#modifyGameId').val();
            }
        }
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#iconImage').attr('src', result); //图片链接（base64）
            });
            layer.msg('上传中', {icon: 16, time: 0});
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            $('#iconText').html('');
            layer.msg('上传成功', {icon: 1});
        }
        , error: function () {
            //演示失败状态，并实现重传
            let demoText = $('#iconText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                modifyIcon.upload();
            });
        }
    });

    let modifyPicture = upload.render({
        elem: '#picture'
        , url: ctx + mainUploadUrl
        , data: {
            type: 'picture', gameId: function () {
                return $('#modifyGameId').val();
            }
        }
        , before: function (obj) {
            obj.preview(function (index, file, result) {
                $('#pictureImage').attr('src', result);
            });
            layer.msg('上传中', {icon: 16, time: 0});
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功的一些操作
            $('#pictureText').html(''); //置空上传失败的状态
            layer.msg('上传成功', {icon: 1});
        }
        , error: function () {
            //演示失败状态，并实现重传
            let demoText = $('#pictureText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                modifyPicture.upload();
            });
        }
    });

    let modifyScroll = upload.render({
        elem: '#scroll'
        , url: ctx + mainUploadUrl
        , data: {
            type: 'scroll', gameId: function () {
                return $('#modifyGameId').val();
            }
        }
        , multiple: true
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#scrollImageList').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">')
            });
        }
        , done: function (res) {
            //上传完毕
            layer.msg('上传完毕', {icon: 1});
        }
    });

    //头工具栏事件
    table.on('toolbar(test)', function (obj) {
        switch (obj.event) {
            case 'addNewRow':
                $("#tableId").css("display", "none");
                $("input[name='itemId']").removeAttr("readonly");
                $("#tableTime").css("display", "none");
                $("#updateTime").css("display", "none");
                $("#saveBtn").css("display", "none");
                $("#addBtn").css("display", "block");

                $('#gameStatusAdd').find("option").remove();
                $('#gameStatusAdd').append(new Option("下线", "0", true));
                $('#gameStatusAdd').append(new Option("上线", "1"));

                $('#gameTypeAdd').find("option").remove();
                for (let i = 0; i < categoryList.length; i++) {
                    let category = categoryList[i];
                    $('#gameTypeAdd').append(new Option(category.categoryName, category.categoryType));
                }

                $('#platformAdd').find("option").remove();
                $('#platformAdd').append(new Option("Android", "0"));
                $('#platformAdd').append(new Option("IOS", "1"));
                $('#platformAdd').append(new Option("同时支持两个平台", "2", true));

                form.render("select");


                $("#addForm")[0].reset();
                form.render();
                //重置图片信息
                $('#iconImageAdd').attr('src', '');
                $('#pictureImageAdd').attr('src', '');


                // form.val("addForm", defaultBLEData);
                openIndex = layer.open({
                    type: 1,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    title: ['新增数据', 'font-size:18px;'],//数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
                    area: ['80%', '80%'],
                    content: $('#show_add_div')
                });
                break;
            case 'query':
                let queryByLoginName = $("#queryByLoginName").val();
                let query = {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , done: function (res, curr, count) {
                        //完成后重置where，解决下一次请求携带旧数据
                        // this.where = {};
                    }
                };
                if (!queryByLoginName) {
                    queryByLoginName = "";
                }
                //设定异步数据接口的额外参数
                query.where = {username: queryByLoginName};
                tableIns.reload(query);
                $("#queryByLoginName").val(queryByLoginName);
                break;
        }
    });

    //监听行工具事件
    table.on('tool(test)', function (obj) {
        let data = obj.data;
        console.log("data:", data);
        //编辑
        if (obj.event === 'edit') {
            //先查询数据，再显示
            $.post(ctx + mainGameDetailUrl, {gameId: data.gameId}, function (res) {
                if (!res.flag) {
                    layer.msg(res.msg, {icon: 2, time: 2000}, function () {
                    });
                    return;
                }
                let gameInfo = res.data.gameInfo;
                let gamePicturesList = res.data.gamePicturesList;
                let gameTags = res.data.gameTags;

                $('#gameStatus').find("option").remove();
                $('#gameStatus').append(new Option("下线", "0", gameInfo.gameStatus === 0));
                $('#gameStatus').append(new Option("上线", "1", gameInfo.gameStatus === 1));

                $('#gameType').find("option").remove();
                for (let i = 0; i < categoryList.length; i++) {
                    let category = categoryList[i];
                    $('#gameType').append(new Option(category.categoryName, category.categoryType, gameInfo.gameType === category.categoryType));
                }

                $('#platform').find("option").remove();
                $('#platform').append(new Option("Android", "0", gameInfo.platform === 0));
                $('#platform').append(new Option("IOS", "1", gameInfo.platform === 1));
                $('#platform').append(new Option("同时支持两个平台", "2", gameInfo.platform === 2));

                form.render("select");

                //渲染多选tags
                let defaultArray = [];
                for (let i = 0; i < gameTags.length; i++) {
                    let tag = gameTags[i];
                    defaultArray.push(tag.tagId)
                }
                //设置value默认数组
                xmSelect.get('#multiselectTag', true).setValue(defaultArray)


                //重置图片信息
                $('#iconImage').attr('src', domainName + gameInfo.gameIcon);
                $('#pictureImage').attr('src', domainName + gameInfo.gamePicture);
                $('#scrollImageList').children().remove();
                for (let i = 0; i < gamePicturesList.length; i++) {
                    $('#scrollImageList').append('<img src="' + domainName + gamePicturesList[i] + '"  alt="" class="layui-upload-img">')
                }

                $("#tableId").css("display", "block");
                $("input[name='itemId']").attr("readonly", "readonly");

                $("#tableTime").css("display", "block");
                $("#updateTime").css("display", "block");
                $("#saveBtn").css("display", "block");
                $("#addBtn").css("display", "none");
                //回显操作表单
                $("#comForm").form(data);
                form.render();

                openIndex = layer.open({
                    type: 1,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    title: ['修改数据', 'font-size:18px;'],//数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
                    area: ['50%', '80%'],
                    content: $('#show_div')
                });
            });


        } else if (obj.event === 'del') {
            layer.confirm('真的删除这个游戏么?', function (index) {
                // console.log(ctx + mainDeleteUrl);
                $.post(ctx + mainDeleteUrl, {id: data.gameId}, function (data) {
                    if (!data.flag) {
                        layer.msg(data.msg, {icon: 2, time: 2000}, function () {
                        });
                        return;
                    }
                    obj.del();
                    tableIns.reload();
                });
                layer.close(index);
            });
        }
    });


    //日期选择器
    // ['#showTimeDate', '#AddShowTimeDate'].forEach((el, index) => {
    //     laydate.render({
    //         elem:el,
    //         format: "yyyy-MM-dd HH:mm:ss"
    //     });
    // });

    //监听提交
    form.on('submit(comFilter)', function (data) {
        comFormSave();
    });

    form.on('submit(formStep)', function (data) {
        //先存储一次数据，生成数据后，进行下一步
        // let stepForm = $("#stepForm").serializeObject();
        let selectStr = xmSelect.get('#multiselectTagAdd', true).getValue('valueStr');
        data.field.multiSelectTag = selectStr;
        console.log(data.field);
        $.post(ctx + mainSaveUrl, data.field, function (data) {
            if (!data.flag) {
                layer.msg(data.msg, {icon: 2, time: 2000}, function () {
                });
                return;
            }
            // layer.close(openIndex);
            console.log("data:" + data)
            // currentGameInfo = data.data;
            //回显
            $("#stepForm").form(data.data);
            form.render();
            //下一步
            step.next('#stepForm');
        });
        return false;
    });

    form.on('submit(formStep2)', function (data) {
        step.next('#stepForm');
        return false;
    });

    $('.updateGameInfo').click(function () {
        tableIns.reload();
        layer.close(openIndex);
    });

    $('.newGameInfo').click(function () {
        tableIns.reload();
        //重置表单数据
        $("#addForm")[0].reset();
        form.render();
        //重置图片信息
        $('#iconImageAdd').attr('src', '');
        $('#pictureImageAdd').attr('src', '');

        step.next('#stepForm');
    });

    $('.pre').click(function () {
        step.pre('#stepForm');
    });

    $('.next').click(function () {
        step.next('#stepForm');
    });

    $("#saveBtn").css("display", "none");
    $("#addBtn").css("display", "none");
});


function findByUserAddress(form) {
    if (form) {
        //重置数据
        $("#comForm")[0].reset();
        form.render();
    }
    let queryByAddress = $("#queryByAddress").val();
    //获取菜单数据
    if (queryByAddress.length <= 0) {
        layer.msg("输入用户钱包地址查询", {icon: 2, time: 1000}, function () {
        });
        return;
    }
    tableIns.reload({
        page: {
            curr: 1 //重新从第 1 页开始
            , limit: 10
        },
        method: 'POST'
        , url: ctx + "/sys/sysComUsers/findPlayerBackpack"
        , where: {address: queryByAddress, sidx: "desc", sord: "createTime"}
        , done: function (res, curr, count) {
            // console.log(res, curr, count);
            $("input[name='queryByAddress']").val(queryByAddress);
            //this.where={};
            //不清空，有问题：搜索条件会保留
            //清空，  有问题：分页的时候没有搜索条件了,分页会受到影响
        }
    });
}

/**
 * 提交保存
 */
function comFormSave() {
    let comForm = $("#comForm").serializeObject();
    if (!comForm.gameId) {
        layer.msg("选择编辑的对象", {icon: 2, time: 1000}, function () {
        });
        return;
    }
    let selectStr = xmSelect.get('#multiselectTag', true).getValue('valueStr');
    comForm.multiSelectTag = selectStr;

    $.post(ctx + mainSaveUrl, comForm, function (data) {
        if (!data.flag) {
            layer.msg(data.msg, {icon: 2, time: 2000}, function () {
            });
            return;
        }
        layer.close(openIndex);
        tableIns.reload();
    });
}
