var pageNo = 1;
var totalPages = 0;

//设备类型列表
getListDataAjax();

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

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

    ajaxRequest(PROPERTY_LIST, "POST", queryParam, function(result) {
        let data = result.pageList;
        let items = '';
        if (result.totalCount > 0) {
            data.forEach(function(item, key) {
                items += "<tr>" +
                    "<td class='status' data-user='" + JSON.stringify(item) + "' data-id=" + item.register + "></td>" +
                    "<td>" + item.facilityNo + "</td>" +
                    "<td>" + item.facilityName + "</td>" +
                    "<td>" + item.facilityType + "</td>" +
                    "<td>" + item.facilityModel + "</td>" +
                    "<td>" + item.man + "</td>" +
                    "<td>" + item.purchase + "</td>" +
                    "<td>" + item.addrs + "</td>" +
                    "<td>" + getFormatDate(item.buyTime) + "</td>" +
                    "<td>" + item.buyNo + "</td>" +
                    "<td>" + item.invoice + "</td>" +
                    "<td><img src='" + item.qrurl + "' class='enlargeImg'><div class='imgBox'></div</td>" +
                    "</tr>"
            })
        }
        $('#dataList').html(items);
        totalPages = result.totalPages;
        $('#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("请求数据失败!");
    })
}

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

//拼接搜索条件
function getSearchParamObj() {
    let queryParam = {};
    let facilityName = $('#facilityName').val();
    let addrs = $('#addrs').val()
    queryParam.facilityName = facilityName;
    queryParam.addrs = addrs;
    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;
    $("#facilityName").val("");
    $("#addrs").val("");
    getListDataAjax(getSearchParamObj());
}

//类别下拉
getTypeList()

//类别下拉 ajax请求
function getTypeList() {

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

//单位下拉
getCompanyList()

function getCompanyList() {

    ajaxRequest(COMPANY_LIST, "POST", {}, function(result) {
        let data = result.data;
        let items = '';
        data.forEach(function(item, key) {
            items += `<option value="${item.ownerId}">${item.ownerName}</option>`
        })
        $('#getCompanyList').append(items);
        $('#getCompanyList2').append(items);
    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}

// 公司与部门联动 
linkDep('#getCompanyList')
linkDep('#getCompanyList2')

function linkDep(element) {
    $(element).on('change', function() {
        //获取公司id
        let companyName = $(this).find('option:selected').val();
        ajaxRequest(COMPANY_LIST, "POST", { "ownerId": companyName }, function(result) {
            let companyDepartmentItems = '<option value="">请选择</option>';
            let departmentObj = result.data[0].child;
            departmentObj.forEach(function(item, key) {
                companyDepartmentItems += `<option value="${item.departmentId}">${item.departmentName}</option>`
            })
            $('#getDepartmentList').html(companyDepartmentItems);
            $('#getDepartmentList2').html(companyDepartmentItems);
        }, function(errorMsg) {
            alert("请求数据失败!");
        })
    })
}

// 导出 start
$('.export').click(getDataExport)

function getDataExport() {
    // 输出base64编码
    const base64 = s => window.btoa(unescape(encodeURIComponent(s)));

    ajaxRequest(PROPERTY_EXPORT, "POST", {}, function(result) {
        let data = result.data;
        let newData = [];
        data.forEach(function(item, index) {
            newData.push({ facilityNo: item.facilityNo, facilityName: item.facilityName, facilityType: item.facilityType, facilityModel: item.facilityModel, man: item.man, purchase: item.purchase, addrs: item.addrs, buyTime: getFormatDate(item.buyTime), buyNo: item.buyNo, invoice: item.invoice })
        });
        let str = '<tr style="text-align:center"><th>资产编号</th><th>资产名称</th><th>资产类型</th><th>设施型号</th><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>${ 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("请求数据失败!");
    })
}
// 导出  end

/*新增 修改 关闭 弹框*/
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: ['1170px', '400px'],
                content: $(".deviceCheckAdd"),
                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');
                $('.editPropertyOut input[name=facilityName]').val(userInfo.facilityName)
                $('.editPropertyOut input[name=facilityType]').val(userInfo.facilityType)

                // 单位赋值
                $('.editPropertyOut select[name=company]').val(userInfo.company)
                    // 部门下拉展示及赋值
                if ($('#getCompanyList2').val()) {
                    listDepname()

                    function listDepname() {
                        //获取公司id
                        let companyName = $('#getCompanyList2').find('option:selected').val();
                        ajaxRequest(COMPANY_LIST, "POST", { "ownerId": companyName }, function(result) {
                            let companyDepartmentItems = '<option value="">请选择</option>';
                            let departmentObj = result.data[0].child;
                            departmentObj.forEach(function(item, key) {
                                companyDepartmentItems += `<option value="${item.departmentId}">${item.departmentName}</option>`
                            })
                            $('#getDepartmentList2').html(companyDepartmentItems);
                        }, function(errorMsg) {
                            alert("请求数据失败!");
                        })
                    }
                }
                // 部门赋值
                $('.editPropertyOut select[name=department]').val(userInfo.department)

                $('.editPropertyOut input[name=man').val(userInfo.man)
                $('.editPropertyOut input[name=addrs').val(userInfo.addrs)
                $('.editPropertyOut input[name=register').val(userInfo.register)

                layerUpdateIndex = layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    area: ['410px', '400px'],
                    content: $(".editPropertyOut"),
                    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(PROPERTY_DELETE, "POST", { "register": dataId }, function(result) {
                $(".pure-table tbody tr.selected").remove()
                layer.close(layer.layerCreateIndex);
                layer.msg('删除成功!', { icon: 6 });
                getListDataAjax()
            }, function(errorMsg) {
                alert("用户删除失败!");
            })
        }
    })
})


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

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

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "facilityName": "请输入资产名称",
        "facilityType": "请选择资产类别",
        "company": "请选择使用单位",
        "man": "请填写负责人",
        "purchase": "请选择购入方式",
        "price": "请输入单价",
        "addrs": "请输入存放地点",
        "supplier": "请输入供应商",
        "buyTime": "请输入购买时间",
        "buyNo": "请输入采购编号",
        "invoice": "请输入发票编号",
        "purpose": "请输入资产用途",
    });

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

    if (!allParam.warranty) {
        alert('请输入维修天数');
        return;
    } else {
        let pattern = /^(([1-9]\d{0,3})|10000)$/
        if (!pattern.test(allParam.warranty)) {
            alert('请输入1-10000正整数');
            return false;
        }
    }

    if (!allParam.warrantyPeriod) {
        alert('请输入维修周期');
        return;
    } else {
        let pattern = /^(([1-9]\d{0,3})|10000)$/
        if (!pattern.test(allParam.warrantyPeriod)) {
            alert('请输入1-10000正整数');
            return false;
        }
    }

    if (!allParam.usedData) {
        alert('请输入已使用年限');
        return;
    } else {
        let pattern = /^(([1-9]\d{0,3})|10000)$/
        if (!pattern.test(allParam.warranty)) {
            alert('请输入1-10000正整数');
            return false;
        }
    }

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


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

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

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "facilityName": "请输入资产名称",
        "facilityType": "请选择资产类别",
        "company": "请选择使用单位",
        "man": "请填写负责人",
        "register": "请输入资产编号",
    });

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

    ajaxRequest(PROPERTY_UPDATE, "POST", allParam, function(result) {
        if (result.flag) {
            layer.close(layerUpdateIndex);
            layer.msg('修改成功!', { icon: 6 });
            getListDataAjax();
        } else {
            alert(result.msg)
        }
    }, function(errorMsg) {
        alert("数据修改失败!");
    })
})