var pageNo = 1;
var totalPages = 0;

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

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

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

        let data = result.RESULT.pageList;
        let items = '';
        if (result.RESULT.totalCount > 0) {
            data.forEach(function(item, key) {

                let interface_transmission_mode = "";
                if (item.interface_transmission_mode == 1) {
                    interface_transmission_mode = "NB-IOT"
                } else if (item.interface_transmission_mode == 2) {
                    interface_transmission_mode = "Lora-IOT"
                } else {
                    interface_transmission_mode = "2G/4G/5G"
                }

                items += "<tr>" +
                    "<td class='status' data-id=" + item.id + " data-user='" + JSON.stringify(item) + "'></td>" +
                    "<td>" + item.xh + "</td>" +
                    "<td>" + item.interface_name + "</td>" +
                    "<td>" + item.interface_route + "</td>" +
                    "<td>" + item.interface_parameter + "</td>" +
                    "<td>" + interface_transmission_mode + "</td>" +
                    "<td>" + item.interface_explain + "</td>" +
                    "<td><a class='interface-doc' href='" + item.interface_file_route + "' download> 下载</a>  </td> " +
                    // "<td><a class='interface-doc'  href='http://127.0.0.1:5050/images/logo.png' download> 下载</a>  </td> " +
                    "<td>" + item.business + "</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("请求数据失败!");
    })
}

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

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

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

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

function resetForm() {
    pageNo = 1;
    $("#business").val("");
    $("#interface_transmission_mode").val("");
    getListDataAjax(getSearchParamObj());
}

//单位下拉
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);
    }, 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: ['410px', '500px'],
                content: $(".addDataOut"),
                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 datalist = $('.pure-table tr').find('.checked').data('user');

                $('.editDataOut input[name=interface_name]').val(datalist.interface_name)
                $('.editDataOut input[name=interface_route]').val(datalist.interface_route)
                $('.editDataOut input[name=interface_parameter').val(datalist.interface_parameter)
                $('.editDataOut select[name=interface_transmission_mode]').val(datalist.interface_transmission_mode)
                $('.editDataOut input[name=business]').val(datalist.business)
                $('.editDataOut textarea[name=interface_explain').val(datalist.interface_explain)
                $('.editDataOut input[name=id').val(datalist.id)
                    //$('.editDataOut input[name=interface_file_route').val(datalist.interface_file_route)
                    // if (datalist.interface_file_route) {
                    //     $('#systemLogoShow').attr('src', datalist.interface_file_route)
                    //     $('#systemLogoShow').css('display', 'block')
                    // }

                var str = datalist.interface_file_route;
                var index = str.lastIndexOf("/");
                var interface_file_route_name = str.substring(index + 1, str.length)
                if (datalist.interface_file_route) {
                    $('#deviceFileShow').attr('href', datalist.interface_file_route)
                    $('#deviceFileShow').css('display', 'block')
                    $('#deviceFileShow').text(interface_file_route_name)
                }
                layerUpdateIndex = layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    area: ['410px', '520px'],
                    content: $(".editDataOut"),
                    success: function() {
                        $('.clsBtn,.cancel').click(function() {
                            layer.close(layerUpdateIndex);
                        })
                    }
                });

                $('#editDataForm #interface_file_route').off('change').on('change', function() {
                    // 先获取用户上传的文件对象
                    let fileObj = this.files[0];

                    // 生成一个文件读取的内置对象
                    //  let fileReader = new FileReader();
                    // 将文件对象传递给内置对象
                    //     fileReader.readAsDataURL(fileObj); //这是一个异步执行的过程，所以需要onload回调函数执行读取数据后的操作
                    //    console.log('=================2222=====')
                    //    console.log(fileReader)
                    // 将读取出文件对象替换到img标签
                    //  fileReader.onload = function() { // 等待文件阅读器读取完毕再渲染图片
                    // $('#systemLogoShow').attr('src', fileReader.result)
                    //    $('#deviceFileShow').html(fileObj.name)

                    //   $('#deviceFileShow').css('display', 'bloc//k')
                    //}

                    $('#deviceFileShow').html('')
                        // $('#deviceFileShow').css('display', 'block')
                    uploadImg('interface_file_route', function(result) {
                        result = JSON.parse(result);
                        if (!result.flag) {
                            alert('上传图片失败')
                            return;
                        }
                        $('#editDataForm input[name=interface_file_route]').val(result.data)
                    });
                });
            }
        })

    //删除信息
    $('.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_COMMUNICATE_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)
        }
    })
})

let validRequest = {
    "interface_name": "请输入接口名称",
    "interface_route": "请输入接口路径",
    "interface_parameter": "请输入接口参数",
    "interface_transmission_mode": "请选择接口传输方式",
    "business": "请输入所属厂家",
    "interface_explain": "请输入接口说明",
}

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

    //获取表单的值 并转换成对象
    let allParam = serializeArrayToObj($("#addDataForm").serializeArray());
    validRequest.company_code = "请选择单位"
        //验证数据是否为空
    let res = validParamIsEmpty(allParam, validRequest);

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

    //验证文件

    // 判断文件是否为空 
    var file = $("input[name='file']").val(); //用户文件内容(文件)
    if (file == "") {
        alert("请选择上传的目标文件! ")
        return false;
    }

    //上传文件
    uploadImg('addFile', function(data) {
        data = JSON.parse(data); //aa json字符串转对象
        if (data.flag) {
            //将返回的路径 拼接到提交的数据对象里
            allParam['interface_file_route'] = data.data;
            ajaxRequest(DEVICE_COMMUNICATE_ADD, "POST", allParam, function(result) {
                let data = result.data;
                layer.close(layerCreateIndex);
                layer.msg('添加成功!', { icon: 6 });
                getListDataAjax();
            }, function(errorMsg) {
                alert("新增失败!");
            })
        } else {
            return;
        }
    });
})


/* 修改发送请求 */
$('#editDataButton').click(function() {
    //获取表单的值 并转换成对象
    let allParam = serializeArrayToObj($("#editDataForm").serializeArray());
    // let validRequest = {}
    //验证数据是否为
    delete(validRequest.company_code)
    let res = validParamIsEmpty(allParam, validRequest);
    if (res.code == -1) {
        alert(res.msg);
        return;
    }
    ajaxRequest(DEVICE_COMMUNICATE_UPDATE, "POST", allParam, function(result) {
        layer.close(layerUpdateIndex);
        layer.msg('修改成功!', { icon: 6 });
        getListDataAjax();
    }, function(errorMsg) {
        alert("数据修改失败!");
    })

})