var pageNo = 1;
var totalPages = 0;

//检测对象列表
getListDataAjax();

//获取检测对象列表 ajax请求
function getListDataAjax(queryParam = {}, pageNo = 1) {

    queryParam.pageNo = pageNo;
    // queryParam.pageSize = 4;

    ajaxRequest(DEVICE_CHECK_LIST, "POST", queryParam, function(result) {
        let data = result.RESULT.pageList;
        let items = '';
        if (result.RESULT.totalCount > 0) {
            data.forEach(function(item, key) {
                items += "<tr>" +
                    "<td class='status' data-user='" + JSON.stringify(item) + "' data-id=" + item.id + "></td>" +
                    "<td>" + item.xh + "</td>" +
                    "<td>" + item.object_name + "</td>" +
                    "<td>" + item.company_name + "</td>" +
                    "<td>" + item.add_people + "</td>" +
                    "<td>" + getFormatDate(item.add_time.time) + "</td>" +
                    "</tr>"
            })
        }
        $('#dataList').html(items);

        totalPages = result.RESULT.totalPages;
        $('#totalPage').html(totalPages); //总共多少页
        $('#dataTotal').html(result.RESULT.totalCount); //总共多少条数据
        $('#currentPage').val(pageNo); //当前页面

        let pageFrom = (pageNo - 1) * result.RESULT.pageSize + 1; //开始
        let pageTo = result.RESULT.pageNo * result.RESULT.pageSize; //结束

        pageTo = pageTo > result.RESULT.totalCount ? result.RESULT.totalCount : pageTo;

        $('#pageFrom').html(pageFrom);
        $('#pageTo').html(pageTo);

        // 无数据时
        if (!data.length) {
            $('.pager.has-data').hide()
            $('.pager.no-data').show()
        } else {
            $('.pager.has-data').show()
            $('.pager.no-data').hide()
        }

        if (pageNo < totalPages) {
            $('#nextPageButton,#lastPageButton').removeClass('disabled');
        } else {
            $('#nextPageButton,#lastPageButton').addClass('disabled');
        }
        if (pageNo === 1) {
            $('#firstPageButton,#prevPageButton').addClass('disabled');
        } else {
            $('#firstPageButton,#prevPageButton').removeClass('disabled');
        }
    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}

//获取检测对象设备列表 ajax请求

getTypeListDataAjax()

function getTypeListDataAjax(queryParam = {}) {

    ajaxRequest(DEVICE_CHECK_DEVICE_LIST, "POST", queryParam, function(result) {

        let data = result.pageList;
        let items = '';
        data.forEach(function(item, key) {
            items += ` <input type="checkbox" name="device_code" value="${item.ownerCode}" lay-skin="primary" title="${item.ownerName}" >`
        })

        $('#checkselfblock').html(items);
        $('#checkselfblock2').html(items);
        layui.use(['form'], function() {
            var form = layui.form;
            form.render('checkbox');
        });

    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}

//按钮搜索
$('#buttonClick').on('click', function() {
    pageNo = 1
    getListDataAjax(getSearchParamObj());
})

//拼接搜索条件
function getSearchParamObj() {
    let queryParam = {};
    let object_name = $('#object_name').val();
    let start_add_time = $('#start_add_time').val();
    let end_add_time = $('#end_add_time').val()
    queryParam.object_name = object_name;
    queryParam.start_add_time = start_add_time;
    queryParam.end_add_time = end_add_time;
    return queryParam;
}

//重置表单
$('.reset').click(resetForm)

//重置表单
function resetForm() {
    pageNo = 1;
    $("#object_name").val("");
    $("#start_add_time").val("");
    $("#end_add_time").val("");
    getListDataAjax(getSearchParamObj());
}

let dataDefaultTree = [];

//获取建筑楼层房间树结构 ajax请求
function getBuildTree() {

    ajaxRequest(BUILD_TREE_LIST, "POST", {}, function(result) {

        let data = result.data;
        let treeArray = []

        //遍历第一级
        data.forEach(function(item, index) {
            let treeObj = {}
            treeObj.id = item.id;
            treeObj.title = item.buildName;

            //遍历第二级
            if (item.child) {
                treeObj.children = [];
                item.child.forEach(function(itemChild, indexChild) {
                    let treeChildObj = {};
                    treeChildObj.id = itemChild.id;
                    treeChildObj.title = itemChild.floorName;

                    //遍历第三级
                    if (itemChild.child) {
                        treeChildObj.children = [];
                        let treeChildChildObj = {};
                        let childChildData = itemChild.child;
                        childChildData.forEach(function(itemChildChild, indexChildChild) {
                            treeChildChildObj.id = itemChildChild.id;
                            treeChildChildObj.title = itemChildChild.roomName;
                            treeChildObj.children.push(treeChildChildObj);
                        })
                    }
                    treeObj.children.push(treeChildObj);
                })
            }
            treeArray.push(treeObj)
        })

        dataDefaultTree = treeArray
        let items = '';
        let companyItems = '';
        let companyDepartmentItems = '<option value="">请选择</option>';

        // data.forEach(function (item, key) {
        //     items += `<li  data-id=${item.ownerId} ><span data-id=${item.ownerId}  class="treeCompany"><img  class="img" src="images/login.png" alt=""> ${item.ownerName}  (${item.userNumber})</span>`;
        //     if (item.child) {
        //         let data = item.child;
        //         items += `<ul class="child-three">`;
        //         data.forEach(function (item, key) {
        //             items += `<li   data-id=${item.departmentId} ><span  data-id=${item.departmentId}  class="treeDepartment"><img class="img" src="images/login.png" alt="">${item.departmentName}</span></li>`
        //         });
        //         items += ` </ul>`;
        //     }
        //     `</li>`

        //     companyItems += `<option value="${item.ownerId}">${item.ownerName}</option>`

        //     if (key == 0) {
        //         let departmentObj = item.child;
        //         if (departmentObj) {
        //             departmentObj.forEach(function (item, key) {
        //                 companyDepartmentItems += `<option value="${item.id}">${item.departmentName}</option>`
        //             })
        //             $('#departmentId').html(companyDepartmentItems);
        //             $('#departmentIdUpdate').html(companyDepartmentItems);
        //         }
        //     }
        // })

        // $('#child-two').html(items);
        // $('#companyId').html(companyItems);
        // $('#companyId2').html(companyItems);
        // treeClickSearch();

    }, function(errorMsg) {
        alert("请求数据失败!");
    })

}

//单位下拉 ajax请求
//单位下拉
getNameList()

function getNameList() {

    ajaxRequest(DEVICE_TYPE_COMPANYLIST, "POST", {}, function(result) {
        let data = result.RESULT;
        let items = '<option value="">请选择</option>';

        data.forEach(function(item, key) {
            items += `<option value="${item.owner_id}">${item.owner_name}</option>`
        })

        $('#getNameList').html(items);
        $('#getNameList2').html(items);

    }, function(errorMsg) {
        alert("请求数据失败!");
    })

}

//建筑下拉
getBuildingList()

function getBuildingList() {

    ajaxRequest(BUILD_TREE_LIST, "POST", {}, function(result) {
        let data = result.data;
        let items = '';
        data.forEach(function(item, key) {
            items += `<option value="${item.id}">${item.buildName}</option>`
        })
        $('#getBuildingList').append(items);
        $('#getBuildingList2').append(items);
    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}

// 建筑与楼层
linkFloor('#getBuildingList')
linkFloor('#getBuildingList2')

function linkFloor(element) {
    $(element).on('change', function() {
        $("#getRoomList").html("<option value=''>请选择</option>");
        $("#getFloorList").html("<option value=''>请选择</option>");
        $("#getRoomList2").html("<option value=''>请选择</option>");
        $("#getFloorList2").html("<option value=''>请选择</option>");

        //获取公司id
        let buildId = $(this).find('option:selected').val();
        getTypeListDataAjax({ "owner_xh": buildId })
        if ($('#getBuildingList').val() || $('#getBuildingList2').val()) {
            ajaxRequest(BUILD_TREE_LIST, "POST", { "buildId": buildId }, function(result) {
                let floorItems = '<option value="">请选择</option>';
                let buildObj = result.data;
                if (buildObj) {
                    buildObj.forEach(function(item, key) {
                        floorItems += `<option value="${item.floorId}">${item.floorName}</option>`
                    })
                    $('#getFloorList').html(floorItems);
                    $('#getFloorList2').html(floorItems);
                } else {
                    $('#getFloorList').html(floorItems);
                    $('#getFloorList2').html(floorItems);
                }
            }, function(errorMsg) {
                alert("请求数据失败!");
            })
        }
    })
}

// 楼层与房间联动
linkRoom('#getFloorList')
linkRoom('#getFloorList2')

function linkRoom(element) {
    $(element).on('change', function() {
        $("#getRoomList").html("<option value=''>请选择</option>");
        $("#getRoomList2").html("<option value=''>请选择</option>");

        //获取楼层id
        let floorName = $(this).find('option:selected').val();
        let buildName = $('#getBuildingList').val()

        if ($('#getFloorList').val() || $('#getFloorList2').val()) {
            getTypeListDataAjax({ "louyu": floorName })
            ajaxRequest(BUILD_TREE_LIST, "POST", { "floorId": floorName }, function(result) {

                let roomItems = '<option value="">请选择</option>';
                let floorObj = result.data;

                floorObj.forEach(function(item, key) {
                    roomItems += `<option value="${item.roomId}">${item.roomName}</option>`
                })

                $('#getRoomList').html(roomItems);
                $('#getRoomList2').html(roomItems);

            }, function(errorMsg) {
                alert("请求数据失败!");
            })
        } else {
            getTypeListDataAjax({ "owner_xh": buildName })
        }
    })
}

$('#getRoomList').on('change', function() {
    //获取楼层id
    let roomId = $(this).find('option:selected').val();
    if ($('#getRoomList').val() || $('#getRoomList2').val()) {
        getTypeListDataAjax({ "rtmp": roomId })
    } else {
        let floorName = $('#getFloorList').val()
        getTypeListDataAjax({ "louyu": floorName })
    }
})

$('#getRoomList2').on('change', function() {
    //获取楼层id
    let roomId = $(this).find('option:selected').val();
    if ($('#getRoomList2').val()) {
        getTypeListDataAjax({ "rtmp": roomId })
    } else {
        let floorName = $('#getFloorList2').val()
        getTypeListDataAjax({ "louyu": floorName })
    }
})

//分页操作
$('#firstPageButton').on('click', function() {
    pageNo = 1;
    getListDataAjax(getSearchParamObj(), 1);
})

$('#lastPageButton').on('click', function() {
    pageNo = totalPages;
    getListDataAjax(getSearchParamObj(), pageNo);
})

$('#prevPageButton').on('click', function() {
    pageNo -= 1;
    getListDataAjax(getSearchParamObj(), pageNo);
})

$('#nextPageButton').on('click', function() {
    pageNo += 1;
    getListDataAjax(getSearchParamObj(), pageNo);
})

/*新增 修改 关闭 弹框*/
var layer = layui.layer;
var layerCreateIndex = '';
var layerUpdateIndex = ''
layui.use('layer', function() {

    //新增弹框
    $('.add').click(function() {

            //重新渲染表单
            // $('#addDeviceCheckForm')[0].reset()

            // layui.use(['form'], function() {
            //     var form = layui.form;
            //     form.render('checkbox');
            // });

            layerCreateIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                skin: 'yourclass',
                area: ['1000px', '400px'],
                content: $(".addDataOut"),
                success: function() {
                    $('.clsBtn,.cancel').click(function() {
                        layer.close(layerCreateIndex);
                    })
                }
            })
        }),
        //修改弹框信息 
        $('.edit').click(function() {

            //获取检测对象设备列表 ajax请求
            getTypeListDataAjax()

            if (!$('.pure-table tr').has('.checked').length) {
                layer.msg('请选择一条需要修改的信息!', { icon: 5 });
            } else {
                let userInfo = $('.pure-table tr').find('.checked').data('user');
                $('.editDataOut input[name=object_name]').val(userInfo.object_name)
                $('.editDataOut select[name=company_code]').val(userInfo.company_code)
                $('.editDataOut input[name=id]').val(userInfo.id)

                // 建筑赋值
                $('.editDataOut select[name=build]').val(userInfo.build)

                // 楼层下拉展示及赋值
                if ($('#getBuildingList2').val()) {
                    listFloor()

                    function listFloor() {
                        let buildId = $('#getBuildingList2').find('option:selected').val();
                        ajaxRequest(BUILD_TREE_LIST, "POST", { "buildId": buildId }, function(result) {
                            let floorItems = '<option value="">请选择</option>';
                            let buildObj = result.data;

                            if (buildObj) {
                                buildObj.forEach(function(item, key) {
                                    floorItems += `<option value="${item.floorId}">${item.floorName}</option>`
                                })
                                $('#getFloorList2').html(floorItems);
                            } else {
                                $('#getFloorList2').html(floorItems);
                            }
                        }, function(errorMsg) {
                            alert("请求数据失败!");
                        })
                    }
                }
                $('.editDataOut select[name=floor]').val(userInfo.floor)

                // 房间下拉展示及赋值
                if ($('#getFloorList2').val()) {
                    listRoom()

                    function listRoom() {
                        let floorId = $('#getFloorList2').find('option:selected').val();
                        ajaxRequest(BUILD_TREE_LIST, "POST", { "floorId": floorId }, function(result) {
                            let roomItems = '<option value="">请选择</option>';
                            let floorObj = result.data;
                            if (floorObj) {
                                floorObj.forEach(function(item, key) {
                                    roomItems += `<option value="${item.roomId}">${item.roomName}</option>`
                                })
                                $('#getRoomList2').html(roomItems);
                            } else {
                                $('#getRoomList2').html(roomItems);
                            }
                        }, function(errorMsg) {
                            alert("请求数据失败!");
                        })
                    }
                }
                $('.editDataOut select[name=room]').val(userInfo.room)

                let buildName = $('#getBuildingList2').find('option:selected').val();
                let floorName = $('#getFloorList2').find('option:selected').val();
                let roomName = $('#getRoomList2').find('option:selected').val();

                // 根据建筑楼层房间赋值，来渲染列表
                getTypeListDataAjax({ "owner_xh": buildName, "louyu": floorName, "rtmp": roomName, })

                // 复选框赋值
                var checkValue = userInfo.device_code_list;
                if (checkValue) {
                    checkValue.forEach(function(item, key) {
                        if (item.device_code) {
                            $(".editDataOut input:checkbox[value=" + item.device_code + "]").attr('checked', 'true')
                        }
                    })
                }

                layui.use(['form'], function() {
                    var form = layui.form;
                    form.render('checkbox');
                });

                layerUpdateIndex = layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    area: ['1000px', '400px'],
                    content: $(".editDataOut"),
                    success: function() {
                        $('.clsBtn,.cancel').click(function() {
                            layer.close(layerUpdateIndex);
                        })
                    }
                });
            }
        })

    //删除信息
    $('.delete').click(function() {
        if (!$('.pure-table tr').has('.checked').length) {
            //layer.msg('请选择一条需要修改的信息');
            layer.msg('请选择一条需要删除的信息!', { icon: 5 });
        } else {
            let dataId = $('.pure-table tr').find('.checked').data('id');
            ajaxRequest(DEVICE_CHECK_DELETE, "POST", { "ID_LIST": [{ "id": dataId }] }, function(result) {
                $(".pure-table tbody tr.selected").remove()
                let data = result
                layer.close(layer.layerCreateIndex);
                layer.msg('删除成功!', { icon: 6 });
                getListDataAjax()
            }, function(errorMsg) {
                alert("用户删除失败!");

            }, 2)
        }
    })
})


/* 新增发送请求 */
$('#addData').click(function() {

    let formAllParam = $("#addDeviceCheckForm").serializeArray();

    let allParam = {};
    let deviceCodeArr = [];
    for (let key in formAllParam) {
        if (formAllParam[key].name == 'device_code') {
            deviceCodeArr.push(formAllParam[key].value)
        } else {
            allParam[formAllParam[key].name] = formAllParam[key].value
        }
    }
    allParam.device_code = deviceCodeArr

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "object_name": "请填写对象名称",
        "company_code": "请选择单位",
    });

    if (res.code == -1) {
        alert(res.msg);
        return;
    }

    //验证通过 请求ajax

    ajaxRequest(DEVICE_CHECK_ADD, "POST", { "ID_LIST": [allParam] }, function(result) {
        layer.close(layerCreateIndex);
        layer.msg('添加成功!', { icon: 6 });
        getListDataAjax();

    }, function(errorMsg) {
        alert("异常错误!");
    }, 2)
})

/* 修改发送请求 */
$('#updataData').click(function() {

    //获取表单的值 并转换成对象
    let formAllParam = $("#editDeviceCheckForm").serializeArray();

    let allParam = {};
    let deviceCodeArr = [];
    for (let key in formAllParam) {
        if (formAllParam[key].name == 'device_code') {
            deviceCodeArr.push(formAllParam[key].value)
        } else {
            allParam[formAllParam[key].name] = formAllParam[key].value
        }
    }

    allParam.device_code = deviceCodeArr

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "object_name": "请填写对象名称",
        "company_code": "请选择单位",
    });

    if (res.code == -1) {
        alert(res.msg);
        return;
    }

    ajaxRequest(DEVICE_CHECK_UPDATE, "POST", { "ID_LIST": [allParam] }, function(result) {
        layer.close(layerUpdateIndex);
        layer.msg('修改成功!', { icon: 6 });
        getListDataAjax();
    }, function(errorMsg) {
        alert("数据修改失败!");
    }, 2)
})