var page = 1;
var totalPages = 0;

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

var aa = ''

//列表渲染
getListDataAjax();
//获取列表ajax请求
function getListDataAjax(queryParam = {}, page = 1) {
    queryParam.page = page;
    queryParam.limit = 8; //每页显示条数
    queryParam.start = (queryParam.page - 1) * queryParam.limit;
    ajaxRequest(PLAN_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.plan_name + "</td>" +
                    "<td>" + item.cycle_name + "</td>" +
                    "<td>" + item.zxsj + "</td>" +
                    "<td>" + item.plan_name + "</td>" +
                    "<td>" + item.name + "</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)
}


// 责任人下拉 start
getStaticAndSelectAjax({ "pd": "no" });

function getStaticAndSelectAjax(queryParam = {}) {

    ajaxRequest(TEAM_PERSON, "POST", queryParam, function(result) {
        queryParam.pd = 'no';
        let data = result.RESULT;

        let items = '';
        data.forEach(function(item, key) {
            items += `<option value="${item.id}">${item.username}</option>`
        })
        $('#person_liable_id').append(items);
        $('#person_liable_id2').append(items);
        $('#person_liable_id3').append(items);
    }, function(errorMsg) {
        alert("请求数据失败!");
    }, 3)
}
// 责任人下拉end

//单位下拉
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);
        $('#getNameList3').append(items);
    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}

//执行团队下拉
getTeamList()
    //执行团队下拉 ajax请求
function getTeamList() {
    ajaxRequest(TEAM_SELECT, "POST", {}, function(result) {
        let data = result.RESULT;
        let items = '';
        data.forEach(function(item, key) {
            items += `<option value="${item.id}">${item.team_name}</option>`
        })
        $('#getTeamList').append(items);
        $('#getTeamList3').append(items);
    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}

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

    param1 = $('#plan_name').val()
    param2 = $('#person_liable_id').val()
})

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

//重置表单
$('.reset').click(resetForm);
//分页刷新按钮
$('.pg-refresh').click(resetForm);

//重置表单
function resetForm() {
    page = 1;

    $("#plan_name").val("");
    $("#person_liable_id").val("");
    getListDataAjax(getSearchParamObj());

    param1 = $('#plan_name').val()
    param5 = $('#person_liable_id').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);
})


/*新增 修改 关闭 弹框*/
var layer = layui.layer;
var layerCreateIndex = '';
var layerUpdateIndex = ''
layui.use('layer', function() {

    // 新增弹框
    $(document).on('click', '.add', function() {
        layerCreateIndex = layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            skin: 'yourclass',
            area: ['800px', '600px'],
            content: $(".addDataOut"),
            success: function() {
                getTeamInnerList();
                $('.clsBtn,.cancel').click(function() {
                    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=plan_name]').val(userInfo.plan_name)
            $('.editDataOut select[name=team_id]').val(userInfo.team_id)
            $('.editDataOut select[name=company_code]').val(userInfo.company_code)
            $('.editDataOut input[name=cycle]').val(userInfo.cycle)
            $('.editDataOut input[name=start_inspect_time]').val(userInfo.start_inspect_time)
            $('.editDataOut input[name=end_inspect_time]').val(userInfo.end_inspect_time)
            $('.editDataOut input[name=start_date]').val(userInfo.start_date)
            $('.editDataOut input[name=end_date]').val(userInfo.end_date)

            layerUpdateIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                skin: 'yourclass',
                area: ['800px', '600px'],
                content: $(".editDataOut"),
                success: function() {
                    getTeamInnerList({ "dwid": dataId });
                    $('.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 #dataList tr').find('.checked').data('id');
            ajaxRequest(PLAN_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, {
            "plan_name": "请输入任务名称",
            "team_id": "请选择执行团队",
            "company_code": "请选择单位",
            "cycle": "请选择周期",
            "start_inspect_time": "请选择维保开始时间",
            "end_inspect_time": "请选择维保结束时间",
            "start_date": "请选择执行开始日期",
            "end_date": "请选择执行结束日期",
        });

        if (res.code == -1) {
            alert(res.msg);
            return;
        }
        //验证组织人员
        if (!$('.pure-table.pure-table-inner tr').has('.checked').length) {
            layer.msg('请选择一条需要修改的信息!', { icon: 5 });
            return
        } else {
            let spot_id = $('.pure-table tr').find('.checked').data('id');
            allParam.spot_id = spot_id;
        }


        //验证通过 请求ajax
        ajaxRequest(PLAN_ADD, "POST", allParam, function(result) {
            layer.close(layerCreateIndex);
            layer.msg('添加成功!', { icon: 6 });
            getListDataAjax();
            $('#addDataForm')[0].reset();
        }, function(errorMsg) {
            alert("异常错误!");
        }, 3)
    })
    /* 修改发送请求 */
$('#updateData').click(function() {

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

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "plan_name": "请输入任务名称",
        "team_id": "请选择执行团队",
        "company_code": "请选择单位",
        "cycle": "请选择周期",
        "start_inspect_time": "请选择维保开始时间",
        "end_inspect_time": "请选择维保结束时间",
        "start_date": "请选择执行开始日期",
        "end_date": "请选择执行结束日期",
    });

    if (res.code == -1) {
        alert(res.msg);
        return;
    }
    //验证组织人员
    if (!$('.pure-table.pure-table-inner tr').has('.checked').length) {
        layer.msg('请选择一条需要修改的信息!', { icon: 5 });
        return
    } else {
        let spot_id = $('.pure-table tr').find('.checked').data('id');
        allParam.spot_id = spot_id;
    }
    let dataId = $('.pure-table tr').find('.checked').data('id');

    allParam.id = dataId;

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


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

function getDataExport(queryParam = {}) {
    // 输出base64编码
    const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
    ajaxRequest(TEAM_EXPORT, "POST", queryParam, function(result) {
        console.log('result.RESULT')
        console.log(result.RESULT)
        let data = result.RESULT;
        let newData = [];
        if (data) {
            data.forEach(function(item, index) {
                newData.push({ xh: item.xh, plan_name: item.plan_name, company_name: item.company_name, name: item.name, phone: item.phone, person_liable_id: item.person_liable_id, add_time: item.add_time })
            });
        }
        let str = '<tr style="text-align:center"><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 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