var pageNo = 1;
var totalPages = 0;

var depname = 0;
var companyId = 0;

//单位列表
getListDataAjax();

//获取单位列表 ajax请求
function getListDataAjax(queryParam = {}, pageNo = 1) {

    queryParam.pageNo = pageNo;
    // queryParam.pageSize = 1;

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

        let data = result.pageList;
        let data2 = result.data;
        let items = '';
        let items2 = '';
        data.forEach(function(item, key) {
            items += "<tr>" +
                "<td class='status' data-user='" + JSON.stringify(item) + "'></td>" +
                "<td>" + item.ownerId + "</td>" +
                "<td>" + item.ownerName + "</td>" +
                "<td>" + item.buildingId + "</td>" +
                "<td>" + item.ownerAddress + "</td>" +

                "<td>" + item.ownerMan + "</td>" +
                "<td>" + item.contacts + "</td>" +
                "<td>" + item.createMan + "</td>" +
                "<td>" + getFormatDate(item.createTime) + "</td>" +
                "<td><a class='view-detail'  data-id='" + item.ownerId + "'>详情</a></td>" +
                "</tr>"

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

        })
        $('#dataList').html(items);
        $('#getCompanyName').append(items2);
        $('#getCompanyName2').append(items2);

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

        let pageFrom = (pageNo - 1) * result.pageSize + 1; //开始
        let pageTo = result.pageNo * result.pageSize; //结束
        pageTo = pageTo > result.totalCount ? 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("请求数据失败!");
    })
}

//部门修改单位下拉
getCompanyListAjax();

function getCompanyListAjax() {

    ajaxRequest(COMPANY_LIST, "POST", {}, function(result) {
        let data = result.data;
        let items2 = '<option value="">请选择</option>';
        data.forEach(function(item, key) {
            items2 += `<option value="${item.ownerId}">${item.ownerName}</option>`
        })
        $('#getCompanyName2').html(items2);

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

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

//拼接搜索条件
function getSearchParamObj() {
    let queryParam = {};
    let startTime = $('#startTime').val();
    let endTime = $('#endTime').val()
    let companyName = $('#companyName').val()
    queryParam.startTime = startTime;
    queryParam.endTime = endTime;
    queryParam.companyName = companyName;
    return queryParam;
}

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

//重置表单
function resetForm() {
    pageNo = 1;
    $("#companyName").val("");
    $("#startTime").val("");
    $("#endTime").val("");
    getListDataAjax(getSearchParamObj());
}

//分页操作
$('#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);
})

getBuildingId()

//建筑查询 ajax请求
function getBuildingId() {

    ajaxRequest(BUILDING_LIST, "POST", {}, function(result) {
        $("#loading").empty()
        let data = result.pageList;
        let items = '';
        let items2 = '';

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

        $('#getBuildingId').append(items);
        $('#getBuildingId2').append(items);
        // $('#roleId2').html(roleItems2);
        // $('#roleId3').html(roleItems2);

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

}

/*新增 修改 关闭 弹框*/
var layer = layui.layer;
var layerCreateIndex = '';
var layerUpdateIndex = ''

var layerDepartmentIndex = ''
var layerCreateIndex2 = '';
var layerUpdateIndex2 = ''
layui.use('layer', function() {

    //单位新增弹框
    $('.add').click(function() {
            layerCreateIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                skin: 'yourclass',
                area: ['410px', '350px'],
                content: $(".addCompanyDataOut"),
                success: function() {
                    $('.clsBtn,.cancel').click(function() {
                        layer.close(layerCreateIndex);
                    })
                }
            })
        })
        //单位修改弹框信息
    $('.edit').click(function() {
        if (!$('.pure-table tr').has('.checked').length) {
            layer.msg('请选择一条需要修改的信息!', { icon: 5 });

        } else {
            let userInfo = $('.pure-table tr').find('.checked').data('user');
            $('.editCompanyDataOut input[name=ownerMan]').val(userInfo.ownerMan)
            $('.editCompanyDataOut input[name=ownerName]').val(userInfo.ownerName)
            $('.editCompanyDataOut input[name=ownerAddress]').val(userInfo.ownerAddress)
            $('.editCompanyDataOut input[name=ownerOffice').val(userInfo.ownerOffice)
            $('.editCompanyDataOut select[name=buildingId').val(userInfo.buildingId)
            $('.editCompanyDataOut input[name=xmlx').val(userInfo.xmlx)
            $('.editCompanyDataOut input[name=contacts').val(userInfo.contacts)
            $('.editCompanyDataOut input[name=contactsPhone').val(userInfo.contactsPhone)
            $('.editCompanyDataOut input[name=ownerId').val(userInfo.ownerId)

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

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

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

        // 验证数据是否为空
        let res = validParamIsEmpty(allParam, {
            "ownerMan": "请填写单位负责人",
            "ownerName": "请填写单位名称",
            "ownerAddress": "请填写单位地址",
            "ownerOffice": "请填写办公地址",
            "buildingId": "请选择所属建设",
            "xmlx": "请填写类型",
            "contacts": "请填写单位负责人"
        });
        if (res.code == -1) {
            alert(res.msg);
            return;
        }
        var contactsPhone = checkPhoneFormat(allParam.contactsPhone);
        if (!contactsPhone.status) {
            alert(contactsPhone.message)
            return
        }

        //验证通过 请求ajax
        ajaxRequest(COMPANY_ADD, "POST", allParam, function(result) {
            let data = result.data;
            layer.close(layerCreateIndex);
            layer.msg('添加成功!', { icon: 6 });
            getListDataAjax();
        }, function(errorMsg) {
            alert("添加失败!");

        })
    })

    /* 单位修改发送请求 */
    $('#dataUpdate').click(function() {
        //获取表单的值 并转换成对象
        let allParam = serializeArrayToObj($("#editCompanyForm").serializeArray());

        //验证数据是否为空
        let res = validParamIsEmpty(allParam, {
            "ownerMan": "请填写单位负责人",
            "ownerName": "请填写单位名称",
            "ownerAddress": "请填写单位地址",
            "ownerOffice": "请填写办公地址",
            "buildingId": "请选择所属建设",
            "xmlx": "请填写类型",
            "contacts": "请填写单位负责人"
        });

        if (res.code == -1) {
            alert(res.msg);
            return;
        }
        var contactsPhone = checkPhoneFormat(allParam.contactsPhone);
        if (!contactsPhone.status) {
            alert(contactsPhone.message)
            return
        }

        //验证通过 请求ajax
        ajaxRequest(COMPANY_UPDATE, "POST", allParam, function(result) {
            let data = result.data;
            layer.close(layerUpdateIndex);
            layer.msg('修改成功!', { icon: 6 });
            getListDataAjax();
        }, function(errorMsg) {
            alert("修改失败!");
        })
    })

    //单位删除发送请求
    $('.delete').click(function() {
        if (!$('.pure-table tr').has('.checked').length) {
            layer.msg('请选择一条需要删除的信息!', { icon: 5 });
        } else {

            //  let dataId = $('.pure-table tr').find('.checked').data('id');
            let dataId = $('a.view-detail').data('id');

            ajaxRequest(COMPANY_DELETE, "POST", { "companyId": dataId }, function(result) {

                if (result.flag) {
                    $(".pure-table tbody tr.selected").remove()
                    layer.close(layer.layerCreateIndex);
                    alert(result.msg);

                } else {
                    //服务端返回报错
                    alert(result.msg);
                }
                getListDataAjax()

            }, function(errorMsg) {
                alert("单位删除失败!");
            })
        }
    })
});