var page = 1;
var totalPages = 0;

var param1 = '';
var param2 = '';

//列表渲染
getListDataAjax();
//获取列表ajax请求
function getListDataAjax(queryParam = {}, page = 1) {
    queryParam.page = page;
    queryParam.limit = 20; //每页显示条数
    queryParam.start = (queryParam.page - 1) * queryParam.limit;
    ajaxRequest(POINT_LIST, "POST", queryParam, function(result) {
        let data = result.RESULT;
        let items = '';
        if (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.spot_name + "</td>" +
                    "<td>" + item.company_name + "</td>" +
                    "<td>" + item.spot_address + "</td>" +
                    "<td>" + item.type_name + "</td>" +
                    "<td>" + item.latest_change_time + "</td>" +
                    "<td ><a class='pointLabel view-detail' data-id=" + item.id + ">查看</a></td>" +
                    "<td ><a class='pointDetail' data-id=" + item.id + "><img src='../../images/tupianbtn.png'></a></td>"
                "</tr>"
            })
            $('#dataList').html(items);
        } else {
            $('#dataList').html('');
        }

        totalPages = result.totalCount / result.limit;
        totalPages = Math.ceil(totalPages);
        $('#totalPage').html(totalPages); //总共多少页
        $('#dataTotal').html(result.totalCount); //总共多少条数据
        $('#currentPage').val(page); //当前页面
        let pageFrom = (page - 1) * result.limit + 1; //开始
        let pageTo = result.page * result.limit; //结束
        pageTo = pageTo > result.totalCount ? result.totalCount : pageTo;
        $('#pageFrom').html(pageFrom);
        $('#pageTo').html(pageTo);

        // 无数据时
        if (!result.totalCount) {
            $('.pager.has-data').hide()
            $('.pager.no-data').show()
        } else {
            $('.pager.has-data').show()
            $('.pager.no-data').hide()
        }
        if (page < totalPages) {
            $('#nextPageButton,#lastPageButton').removeClass('disabled');
        } else {
            $('#nextPageButton,#lastPageButton').addClass('disabled');
        }
        if (page === 1) {
            $('#firstPageButton,#prevPageButton').addClass('disabled');
        } else {
            $('#firstPageButton,#prevPageButton').removeClass('disabled');
        }
    }, function(errorMsg) {
        alert("请求数据失败!");
    }, 3)
}


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


//按钮搜索
$('#buttonSearch').on('click', function() {
    page = 1;
    getListDataAjax(getSearchParamObj());
    param1 = $('#spot_name').val()
    param2 = $('#spot_address').val()
})

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

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

//分页刷新按钮
$('.pg-refresh').click(resetForm);

//重置表单
function resetForm() {
    page = 1;
    $("#spot_name").val("");
    $("#spot_address").val("");
    getListDataAjax(getSearchParamObj());
    param1 = $('#spot_name').val()
    param5 = $('#spot_address').val()
}

//分页操作
$('#firstPageButton').on('click', function() {
    page = 1;
    getListDataAjax(getSearchParamObj(), 1);
})
$('#lastPageButton').on('click', function() {
    page = totalPages;
    getListDataAjax({}, page);
})
$('#prevPageButton').on('click', function() {
    page -= 1;
    getListDataAjax(getSearchParamObj(), page);
})
$('#nextPageButton').on('click', function() {
    page += 1;
    getListDataAjax(getSearchParamObj(), page);
})

layui.use('layer', function() {
    // 新增弹框
    $(document).on('click', '.add', function() {
        layerCreateIndex = layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            skin: 'yourclass',
            area: ['450px', '400px'],
            content: $(".addDataOut"),
            success: function() {
                // getTeamInnerList();
                $('.clsBtn,.cancel').click(function() {
                    innerPage = 1;
                    layer.close(layerCreateIndex);
                })
            }
        })
    })

    //修改弹框信息 
    $('.edit').click(function() {
        let dataId = $('.pure-table #dataList tr').find('.checked').data('id');

        if (!$('.pure-table tr').has('.checked').length) {
            layer.msg('请选择一条需要修改的信息!', { icon: 5 });
        } else {
            let userInfo = $('.pure-table tr').find('.checked').data('user');
            $('.editDataOut input[name=spot_name]').val(userInfo.spot_name)
            $('.editDataOut select[name=company_code]').val(userInfo.company_code)
            $('.editDataOut input[name=spot_address]').val(userInfo.spot_address)
            $('.editDataOut input[name=equipment_code]').val(userInfo.spot_label_analysis)
            $("input[name='spot_type']").each(function() {
                if ($(this).val() != userInfo.spot_type) {
                    $(this).removeAttr("checked");
                } else {
                    $(this).prop("checked", "checked");
                }
            });
            layui.use(['form'], function() {
                var form = layui.form;
                form.render('radio');
            })
            if (userInfo.picture_route) {
                $('#pictureRouteShow').attr('src', userInfo.picture_route)
                $('#pictureRouteShow').css('display', 'block')
            }
            layerUpdateIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                skin: 'yourclass',
                area: ['450px', '400px'],
                content: $(".editDataOut"),
                success: function() {
                    $('.clsBtn,.cancel').click(function() {
                        innerPage = 1;
                        layer.close(layerUpdateIndex);
                    })
                }
            });
        }
    })

    //删除信息
    $('.delete').click(function() {
        if (!$('.pure-table tr').has('.checked').length) {
            //layer.msg('请选择一条需要修改的信息');
            layer.msg('请选择一条需要删除的信息!', { icon: 5 });
        } else {
            let dataId = $('.pure-table #dataList tr').find('.checked').data('id');
            ajaxRequest(POINT_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, {
            "spot_name": "请输入点位名称",
            "company_code": "请选择所属单位/项目",
            "spot_address": "请输入点位地址",
            "equipment_code": "请输入设备编号",
            "spot_type": "请选择设备类型",
        });
        if (res.code == -1) {
            alert(res.msg);
            return;
        }

        //验证文件

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

        //判断文件类型
        var fileExtension = file.substring(file.lastIndexOf(".") + 1).toLowerCase();

        let allowExtension = ['jpg', 'jpeg', 'png', 'gif'];
        if (allowExtension.indexOf(fileExtension.toLowerCase()) < 0) {
            alert("请选择图片文件!");
            return false;
        }

        //上传文件
        uploadImg('pictureRouteAdd', function(data) {
            data = JSON.parse(data); //aa json字符串转对象
            if (data.flag) {
                //将返回的路径 拼接到提交的数据对象里
                allParam['picture_route'] = data.data;

                //验证通过 请求ajax
                ajaxRequest(POINT_ADD, "POST", allParam, function(result) {
                    layer.close(layerCreateIndex);
                    layer.msg('添加成功!', { icon: 6 });
                    getListDataAjax();
                    $('#addDataForm')[0].reset();
                }, function(errorMsg) {
                    alert("异常错误!");
                }, 3)
            } else {
                //这里应该弹出删除失败的 后台返回的原因
                alert('上传图片失败');
                return;
            }
        });
    })
    /* 修改发送请求 */
$('#updateData').click(function() {

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

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "spot_name": "请输入点位名称",
        "company_code": "请选择所属单位/项目",
        "spot_address": "请输入点位地址",
        "equipment_code": "请输入设备编号",
        "spot_type": "请选择设备类型",
    });
    if (res.code == -1) {
        alert(res.msg);
        return;
    }


    //验证文件
    // 判断文件是否为空 
    if ($("input[name='picture_route']").val()) {
        var file = $("input[name='picture_route']").val(); //用户文件内容(文件)
        //判断文件类型
        var fileExtension = file.substring(file.lastIndexOf(".") + 1).toLowerCase();
        let allowExtension = ['jpg', 'jpeg', 'png', 'gif'];
        if (allowExtension.indexOf(fileExtension.toLowerCase()) < 0) {
            alert("请选择图片文件!");
            return false;
        }
    }
    let dataId = $('.pure-table tr').find('.checked').data('id');
    allParam.id = dataId;
    ajaxRequest(POINT_EDIT, "POST", allParam, function(result) {
        layer.close(layerUpdateIndex);
        layer.msg('修改成功!', { icon: 6 });
        getListDataAjax();
    }, function(errorMsg) {
        alert("数据修改失败!");
    }, 2)


})


// 导出 start
$('.export').click(function() {
    getDataExport({ "spot_name": param1, "spot_address": param2 })
})

function getDataExport(queryParam = {}) {
    // 输出base64编码
    const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
    ajaxRequest(POINT_EXPORT, "POST", queryParam, function(result) {
        let data = result.RESULT;
        let newData = [];
        if (data) {
            data.forEach(function(item, index) {
                newData.push({ xh: item.xh, spot_name: item.spot_name, company_name: item.company_name, spot_address: item.spot_address, type_name: item.type_name, latest_change_time: item.latest_change_time })
            });
        }
        let str = '<tr style="text-align:center"><th>序号</th><th>点位名称</th><th>所属单位/项目</th><th>点位地址</th><th>设备类型</th><th>最新更改时间</th></tr>';
        // 循环遍历，每行加入tr标签，每个单元格加td标签
        for (let i = 0; i < newData.length; i++) {
            str += '<tr style="text-align:center">';
            for (const key in newData[i]) {
                // 增加\t为了不让表格显示科学计数法或者其他格式
                str += `<td x:str>${ newData[i][key] + '\t'}</td>`;
            }
            str += '</tr>';
        }
        // Worksheet名
        const worksheet = 'Sheet1'
        const uri = 'data:application/vnd.ms-excel;base64,';

        // 下载的表格模板数据
        const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
        xmlns:x="urn:schemas-microsoft-com:office:excel" 
        xmlns="http://www.w3.org/TR/REC-html40">
        <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`;

        // 通过创建a标签实现
        const link = document.createElement("a");
        link.href = uri + base64(template);
        // 对下载的文件命名
        link.download = "维保点位数据表.xls";
        link.click();

    }, function(errorMsg) {
        alert("请求数据失败!");
    }, 3)
}
// 导出  end


//点位标签弹框
$(document).on('click', 'a.pointLabel', function() {
    let dwId = $(this).data('id');
    layerDepartmentIndex = layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        skin: 'yourclass',
        area: [
            '450px', '430px'
        ],
        content: $(".pointLabelOut"),
        success: function() {
            ajaxRequest(POINT_LIST, "POST", { "id": dwId }, function(result) {
                var data = result.RESULT[0];
                $('#pointDetailUrl').attr('src', BASEURL + data.spot_label_route);
                $('#spotName').html(data.spot_name);
                $('#spotAddress').html(data.spot_address);
                $('#spotLabelAnalysis').html(data.spot_label_analysis);
                $('#data1').html(data.data1);

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

            $('.pointLabelDownload').click(function() {
                cutDiv()
            })

            $('.clsBtn2,.cancel2').click(function() {
                innerPage = 1;
                layer.close(layerDepartmentIndex);
            })
        }
    })
})

//点位详情点击
$(document).on('click', 'a.pointDetail', function() {
    let id = $(this).data('id'); //单位ID
    layerReportIndex = layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        skin: 'yourclass',
        area: [
            '400px', '400px'
        ],
        content: $(".pointDetailOut"),
        success: function() {
            ajaxRequest(POINT_LIST, "POST", { "id": id }, function(result) {
                var data = result.RESULT[0];
                $('#weibaoReportUrl').attr('src', data.picture_route);
            }, function(errorMsg) {
                alert("请求数据失败!");
            }, 3);

            $('.clsBtn3,.cancel3').click(function() {
                layer.close(layerReportIndex);
            })
        }
    })
})



// 点位标签下载 start
var saveFile = function(data, filename) {
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = data;
    save_link.download = filename;
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
}

var downPng = function(canvas) {
    console.log(canvas);
    var img_data1 = Canvas2Image.saveAsPNG(canvas, true).getAttribute('src');
    saveFile(img_data1, 'download.png');
}

var cutDiv = function() {
        var content = document.getElementById("imgOut");
        html2canvas(content, {
            onrendered: function(canvas) {
                downPng(canvas);
            }
        });
    }
    // 点位标签下载 end