var pageNo = 1;
var totalPages = 0;

//列表渲染
getListDataAjax();

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

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

    ajaxRequest(WORK_MANAGE_LIST, "POST", queryParam, function(result) {
        let data = result.RESULT.pageList;
        let items = '';
        if (result.RESULT.totalCount > 0) {
            data.forEach(function(item, key) {
                var clzt = item.clzt == 1 ? '未处理' : item.clzt == 2 ? '已处置，通过' : '已处置，未通过';
                var clztClassName = item.clzt == 2 ? 'processed' : 'unprocess';
                var cz_time = item.cz_time ? getFormatDate(item.cz_time) : '';
                items += "<tr>" +
                    "<td class='status' data-id=" + item.id + " data-user='" + JSON.stringify(item) + "'></td>" +
                    "<td>" + item.xh + "</td>" +
                    "<td>" + item.company_name + "</td>" +
                    "<td>" + getFormatDate(item.add_time.time) + "</td>" +
                    "<td>" + item.work_order_name + "</td>" +
                    "<td>" + item.work_order_type_name + "</td>" +
                    "<td>" + item.work_order_content + "</td>" +
                    "<td class='" + clztClassName + "'>" + clzt + "</td>" +
                    "<td>" + item.cz_people + "</td>" +
                    "<td>" + cz_time + "</td>" +
                    "</tr>"
            })
        }
        $('#dataList').html(items);
        $('#totalCount').html(result.totalCount)
        $('#handled').html(result.yclCount)
        $('#unhandle').html(result.wclCount)
        $('#handleRate').html(result.cll)

        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("请求数据失败!");
    })
}

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

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

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

//重置表单
function resetForm() {
    pageNo = 1
    $("#work_order_name").val("");
    $("#clzt").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);
})


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

    ajaxRequest(DEVICE_TYPE_COMPANYLIST, "POST", {}, function(result) {
        let data = result.RESULT;
        let items = '';
        data.forEach(function(item, key) {
            items += `<option value="${item.owner_id}">${item.owner_name}</option>`
        })
        $('#getNameList').append(items);
        $('#getNameList2').append(items);

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

/*新增 修改 关闭 弹框*/
var layer = layui.layer;
var layerCreateIndex = '';
var layerUpdateIndex = ''
layui.use('layer', function() {
    //新增弹框
    $('.add').click(function() {
            layerCreateIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                skin: 'yourclass',
                area: ['400px', '400px'],
                content: $(".addDataOut"),
                success: function() {
                    $('.clsBtn,.cancel').click(function() {
                        layer.close(layerCreateIndex);
                    })
                }
            })
        }),
        //处置弹框信息 
        $('.handle').click(function() {
            if (!$('.pure-table tr').has('.checked').length) {
                layer.msg('请选择一条需要修改的信息!', { icon: 5 });
            } else {
                let userInfo = $('.pure-table tr').find('.checked').data('user');
                //2 、3 已经处理过  1 未处理
                if (userInfo.clzt === 2 || userInfo.clzt === 3) {
                    $('.handleDataOut textarea[name=clnr]').attr({ readonly: 'true' })
                    $('#handleUpdate').addClass('disabled')
                    $('.clztRadio').hide();
                    $('.clztInput').show();
                    $('.handleDataOut input[name=clztInput]').val(userInfo.clzt_name)
                } else {
                    $('.handleDataOut textarea[name=clnr]').removeAttr("readonly")
                    $('#handleUpdate').removeClass('disabled');
                    $('.clztRadio').show();
                    $('.clztInput').hide();
                }
                $('.handleDataOut input[name=work_order_name]').val(userInfo.work_order_name)
                $('.handleDataOut input[name=add_time]').val(getFormatDate(userInfo.add_time.time))
                $('.handleDataOut textarea[name=clnr]').val(userInfo.clnr)
                $('.handleDataOut input[name=id').val(userInfo.id)
                layerUpdateIndex = layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    area: ['410px', '400px'],
                    content: $(".handleDataOut"),
                    success: function() {
                        $('.clsBtn,.cancel').click(function() {
                            layer.close(layerUpdateIndex);
                        })
                    }
                });
            }
        })

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

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

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

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "work_order_name": "请输入工单名称",
        "work_order_content": "请输入工单内容",
        "work_order_type": "请选择工单类型",
        "company_code": "请选择所属单位",
    });

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

    //验证通过 请求ajax
    ajaxRequest(WORK_MANAGE_ADD, "POST", allParam, function(result) {
        layer.close(layerCreateIndex);
        layer.msg('添加成功!', { icon: 6 });
        getListDataAjax();
    }, function(errorMsg) {
        alert("异常错误!");
    })
})

/* 处置发送请求 */
$('#handleUpdate').click(function() {
    //获取表单的值 并转换成对象
    let allParam = serializeArrayToObj($("#handleDataForm").serializeArray());
    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "clnr": "请输入处理内容",
    });
    if (res.code == -1) {
        alert(res.msg);
        return;
    }
    ajaxRequest(WORK_MANAGE_HANDLE, "POST", allParam, function(result) {
        layer.close(layerUpdateIndex);
        layer.msg('处置成功!', { icon: 6 });
        getListDataAjax();
    }, function(errorMsg) {
        alert("数据修改失败!");
    })
})