var page = 1;
var totalPages = 0;

var param1 = '';
var param2 = '';
var param3 = '';
var param4 = '';
var param5 = '';

// 数据统计及责任人下拉 start
getStaticAndSelectAjax();

function getStaticAndSelectAjax(queryParam = {}) {

    ajaxRequest(RECORD_STATIC_AND_SELECT, "POST", queryParam, function(result) {
        let data = result.RESULT1;
        $('#xjrysl').html(result.xjrysl)
        $('#jrrw').html(result.jrrw)
        $('#csrw').html(result.csrw)
        $('#jrwcrw').html(result.jrwcrw)

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

//列表渲染
getListDataAjax();

//获取列表 ajax请求
function getListDataAjax(queryParam = {}, page = 1) {
    queryParam.page = page;
    queryParam.limit = 20; //每页显示条数
    queryParam.start = (queryParam.page - 1) * queryParam.limit;
    ajaxRequest(RECORD_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'></td>" +
                    "<td>" + item.xh + "</td>" +
                    "<td>" + item.plan_name + "</td>" +
                    "<td ><a class='view-detail' data-id=" + item.id + ">查看</a></td>" +
                    "<td>" + item.ywcsj + "</td>" +
                    "<td>" + item.zt + "</td>" +
                    "<td>" + item.completion + "</td>" +
                    "<td>" + item.name + "</td>" +
                    "<td>" + item.phone + "</td>" +
                    "</tr>"
            })
            $('#dataList').html(items);
        } else {
            $('#dataList').html('');
        }
        console.log(result)
        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)
}

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

    param1 = $('#data3a').val()
    param2 = $('#data3b').val()
    param3 = $('#zt').val()
    param4 = $('#plan_name').val()
    param5 = $('#person_liable_id').val()
})

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

    queryParam.data3a = data3a;
    queryParam.data3b = data3b;
    queryParam.zt = zt;
    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;

    $("#data3a").val("");
    $("#data3b").val("");
    $("#zt").val("4");
    $("#plan_name").val("");
    $("#person_liable_id").val("");
    getListDataAjax(getSearchParamObj());

    param1 = $('#data3a').val()
    param2 = $('#data3b').val()
    param3 = $('#zt').val()
    param4 = $('#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);
})

// 导出 start
$('.export').click(function() {
    getDataExport({ "data3a": param1, "data3b": param2, "zt": param3, "plan_name": param4, "person_liable_id": param5 })
})

function getDataExport(queryParam = {}) {
    // 输出base64编码
    const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
    ajaxRequest(RECORD_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, ywcsj: item.ywcsj, zt: item.zt, completion: item.completion, name: item.name, phone: item.phone })
            });
        }
        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