let tableIns;
let tablePlayerLog;
let tablePlayerProfit;
let tree;
let userId;
let bHasData = false;
let openIndex;
let mainTableUrl = "/backstage_ble/findAll";
let mainSaveUrl = "/backstage_ble/save";
let mainDeleteUrl = "/backstage_ble/delete";
let mainUnbindUrl = "/backstage_ble/unbind";
// let propList = [[${propList}]];
// console.log("propList:",propList);
layui.use(['element', 'form', 'table', 'layer', 'laydate', 'tree', 'util'], function () {
    let table = layui.table;
    let form = layui.form;//select、单选、复选等依赖form
    form.verify({
        // positiveInteger: [/^(([0-9]+[\.]?[0-9]+)|[1-9])$/, '只能填写正整数'],//必填，且只能输入正整数
        positiveInteger: [/^[1-9]\d*$/, '只能填写正整数'],//必填，且只能输入正整数
    });

    let element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    let laydate = layui.laydate;
    tree = layui.tree;
    // let height = document.documentElement.clientHeight;
    //用户列表
    tableIns = table.render({
        elem: '#mainTable'
        , url: ctx + mainTableUrl
        , method: 'POST'
        //请求前参数处理
        , request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'rows' //每页数据量的参数名，默认：limit
        }
        , where: {sidx: "desc", sord: "createTime"}
        , response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
            , countName: 'records' //规定数据总数的字段名称，默认：count
            , dataName: 'rows' //规定数据列表的字段名称，默认：data
        }
        //响应后数据处理
        , parseData: function (res) { //res 即为原始返回的数据
            $("#addForm")[0].reset();
            userId = null;
            form.render();
            var data = res.data;
            console.log("返回的地址数据：", data);
            if (data.rows && data.rows.length > 0) {
                bHasData = true;
                // userId = data.rows[0].userId;//记录当前访问的userId
                // let _findData = {userId: data.rows[0].userId, sidx: "desc", sord: "createTime"};
                // if (!tablePlayerLog) {
                //     initPlayerLog(table, _findData);
                // } else {
                //     playerLogReload(_findData);
                // }
                //
                // if(!tablePlayerProfit){
                //     initPlayerProfit(table, _findData);
                // }else{
                //     playerProfitReload(_findData);
                // }
            }

            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "records": data.records, //解析数据长度
                "rows": data.rows //解析数据列表
            };
        }
        , toolbar: '#mainTableToolbarDemo'
        , title: '列表'
        , cols: [[
            {field: 'bluetoothId', title: '蓝牙ID', sort: true}
            , {field: 'userId', title: '用户id', sort: true}
            , {field: 'bluetoothName', title: '蓝牙名字', sort: true}
            , {field: 'bluetoothMac', title: '蓝牙地址', sort: true}
            , {
                field: 'bluetoothStatus', title: '设备状态', templet: '#bindButton', sort: true
            }
            , {
                field: 'bluetoothType', title: '设备类型', templet: function (d) {
                    if (d.bluetoothType == 1) {
                        return '<span style="color: red">普通绑带</span>';
                    } else if (d.bluetoothType == 2) {
                        return '<span style="color: green">沙袋绑带</span>';
                    } else if (d.bluetoothType == 3) {
                        return '<span style="color: green">手柄蓝牙</span>';
                    } else {
                        return '未添加:' + d.bluetoothType;
                    }
                }, sort: true
            }
            , {
                field: 'isShare', title: '是否分享', templet: function (d) {
                    if (d.isShare == 1) {
                        return '<span style="color: red">共享</span>';
                    } else if (d.isShare == 0) {
                        return '<span style="color: green">不共享</span>';
                    } else {
                        return '未添加:' + d.isShare;
                    }
                }, sort: true
            }
            , {field: 'identifier', title: '设备标识', 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
    });

    //头工具栏事件
    table.on('toolbar(test)', function (obj) {
        switch (obj.event) {
            case 'query':
                let queryByInput = $("#queryByInput").val();
                let query = {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , done: function (res, curr, count) {
                        //完成后重置where，解决下一次请求携带旧数据
                        this.where = {};
                    }
                };
                if (!queryByInput) {
                    queryByInput = "";
                }else{
                    query.where = {bluetoothMac: queryByInput};
                }
                tableIns.reload(query);
                $("#queryByInput").val(queryByInput);
                break;

            case 'addNewRow':
                // $("#tableId").css("display", "none");
                $("input[name='itemId']").removeAttr("readonly");
                $("#tableTime").css("display", "none");
                $("#saveBtn").css("display", "none");
                $("#addBtn").css("display", "block");
                $('#bluetoothTypeAdd').find("option").remove();
                $('#bluetoothTypeAdd').append(new Option("普通绑带", "1", ));
                $('#bluetoothTypeAdd').append(new Option("沙袋绑带", "2", ));
                $('#bluetoothTypeAdd').append(new Option("手柄蓝牙", "3", true));
                $('#isShareAdd').find("option").remove();
                $('#isShareAdd').append(new Option("不共享", "0", true));
                $('#isShareAdd').append(new Option("共享", "1", ));
                form.render("select");
                $("#addForm")[0].reset();
                form.val("addForm", defaultBLEData);
                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_add_div')
                });
                break;
        }
    });

    //监听行工具事件
    table.on('tool(test)', function (obj) {
        let data = obj.data;
        //编辑
        if (obj.event === 'edit') {

            $('#bluetoothType').find("option").remove();
            $('#bluetoothType').append(new Option("普通绑带", "1", data.bluetoothType === 1));
            $('#bluetoothType').append(new Option("沙袋绑带", "2", data.bluetoothType === 2));
            $('#bluetoothType').append(new Option("手柄蓝牙", "3", data.bluetoothType === 3));

            $('#isShare').find("option").remove();
            $('#isShare').append(new Option("不共享", "0", true));
            $('#isShare').append(new Option("共享", "1", ));
            form.render("select");

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

            $("#tableTime").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.bluetoothId}, function (data) {
                    if (!data.flag) {
                        layer.msg(data.msg, {icon: 2, time: 2000}, function () {
                        });
                        return;
                    }
                    obj.del();
                    tableIns.reload();
                });
                layer.close(index);
            });
        } else if(obj.event === 'unBind'){
            layer.confirm('真的解除绑定么?', function (index) {
                $.post(ctx + mainUnbindUrl, {id: data.bluetoothId}, function (data) {
                    if (!data.flag) {
                        layer.msg(data.msg, {icon: 2, time: 2000}, function () {
                        });
                        return;
                    }
                    tableIns.reload();
                });
                layer.close(index);
            });
        }
    });


    //日期选择器
    laydate.render({
        elem: '#expiredTimeDate',
        format: "yyyy-MM-dd HH:mm:ss"
    });

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

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


/**
 * 提交保存
 */
function comFormSave(isAddNew) {
    let comForm = $("#comForm").serializeObject();
    $.post(ctx + mainSaveUrl, comForm, function (data) {
        if (!data.flag) {
            layer.msg(data.msg, {icon: 2, time: 2000}, function () {
            });
            return;
        }
        layer.close(openIndex);
        tableIns.reload();
    });
}

function comFormAdd() {
    let addForm = $("#addForm").serializeObject();
    $.post(ctx + mainSaveUrl, addForm, function (data) {
        if (!data.flag) {
            layer.msg(data.msg, {icon: 2, time: 2000}, function () {
            });
            return;
        }
        layer.close(openIndex);
        tableIns.reload();
    });
}
