var dafautTitle = [] //表格标题
var arr = [] //表格填充数据
var i;
var loadIndex2
var lineArr = [] //checkbox选取的对象集合
var workspace = [] //checkbox选取的厂家对象集合
var lineIndexArr =[] //checkbox选取的监测点母线对象集合
var color = '#006565'
var myInt //定时器
var Obj = {
    page: 1,
    pageSize: 10,
    total: 0,
    beginTime: '',
    endTime: '',
    flag: false,  //用来标记是否响应
    clickOrCheck:true, //true表示点击，false表示选择复选框
    lineNum: 0, //已经导出的条数
    lineAllNum: 0, //总条数
    lineIndex: null //监测点id
}


layui.use(['table', 'element', 'laypage', 'jquery',], function () {
    var table = layui.table,
        laypage = layui.laypage,
        $ = layui.jquery,
        element = layui.element;


  var height = $(window).height()

    let pagesize = Math.floor((height-150)/31)
    Obj.pageSize = pagesize

    //初始化
    tableInit();


    $.ajax({
        type: "POST",
        url: "/pqs9900/theme/getColor",
        async: false,
        dataType: 'json',
        success: function (data) {
            color = data.body
            $('.layui-laypage-abcdfg').children('.layui-laypage-curr').find('.layui-laypage-em').css('background-color', '' + color)
        }
    })

    $('body').on('click', '#queryCsv', function () {
        var start = $("#startTime").val()
        var end = $("#endTime").val()
        if (start != null && end != null && start != '' && end != '') {
            Obj.beginTime = start
            Obj.endTime = end
            Obj.page = 1

            var time_arr = diff(Obj.beginTime, Obj.endTime)
            var ye = time_arr[0]
            var mo = time_arr[1]
            var da = time_arr[2]

            if (ye > 0 || mo > 1 || da > 31) {
                layer.msg('数据量过大，时间范围不可超过一个月!')
                return false;
            }

            if (Obj.lineIndex == 0 || Obj.lineIndex == null || Obj.lineIndex == '') {
                layer.msg('请至少选择一个监测点');
                return;
            }
            getDetail()
        } else {
            layer.msg('请选择时间', {icon: 2})
        }
    })

    //导出csv文件点击事件
    $("#getCsv").on('click', function () {
        Obj.flag = false
        var start = $("#startTime").val()
        var end = $("#endTime").val()
        if (start != null && end != null) {
            Obj.beginTime = start
            Obj.endTime = end

            var time_arr = diff(Obj.beginTime, Obj.endTime)
            var ye = time_arr[0]
            var mo = time_arr[1]
            var da = time_arr[2]

            if (ye > 0 || mo > 1 || da > 31) {
                layer.msg('数据量过大，时间范围不可超过一个月!')
                return false;
            } //判断时间不可大于一个月
            workspace=[]
            lineIndexArr=[]
            lineArr = getTreeCheckBoxData()
            if(lineArr.length!=0){
                lineArr.forEach(function (item) {
                    if(item.level == 3){
                        workspace.push(item)
                    }else {
                        lineIndexArr.push(item)
                    }
                })
            }

            if (lineIndexArr.length == 0) {
                layer.msg('请至少选择一个监测点');
                return;
            }
            if (lineIndexArr.length == 1) {
                //导出单个监测点数据
                processShow() //进度条展示
                request(lineIndexArr);
                getCsvNew() //进度条获取进度
            } else {

                batchExport(lineIndexArr)
            }

            var DISABLED = 'layui-btn-disabled';
            if ($("#getCsv").hasClass(DISABLED)) return;

        } else {
            layer.msg('请选择时间')
            return;
        }
    })

    //初始化表头
    function tableInit() {
        toF(titleList)
        table.render({
            id: 'table_1',
            elem: '#demo',
            height:height-100
            , cellMinWidth: 200
            , size: 'sm'
            , even: true
            , cols: [dafautTitle]
            , data: arr
            ,limit:15
        });
    }


    //批量导出csv文件
    function batchExport(lineIndexArr) {
        Obj.lineNum = 0
        var DISABLED = 'layui-btn-disabled';
        if ($("#getCsv2").hasClass(DISABLED)) return;
       //导出多个监测点数据
        let lineIndexArrId = [] //存节点id
        lineIndexArr.forEach(function (item) {
            lineIndexArrId.push(item.nodeIndex)
        })
        $.ajax({
            method: "get",
            dataType: "json",
            contentType: 'application/json;charset=UTF-8',
            url: '/pqs9900/csv/getCsvBatch?list=' + lineIndexArrId + '&beginTime=' + Obj.beginTime + '&endTime=' + Obj.endTime,
            beforeSend: function () {
                i = ityzl_SHOW_LOAD_LAYER();
            },
            success: function (result) {
                if (result.code == 200) {
                    loadIndex2 = parent.layer.open({
                        type: 1
                        , title: false //不显示标题栏
                        , closeBtn: false
                        , area: '0px'
                        , shade: 0.15
                        , id: 'LAY_layuipro2' //设定一个id，防止重复弹出
                        , btnAlign: 'c'
                        , moveType: 1 //拖拽模式，0或者1
                    });
                    Obj.lineAllNum = lineIndexArr.length
                    processShow() //进度条展示
                    element.progress('demo2', '10%');
                    // moniProcess(lineIndexArr.length)
                    for (var i = 0; i < lineIndexArr.length; i++) {
                        ajaxForDown(lineIndexArr[i])
                    }

                } else {
                    lineIndexArr.forEach(function (item, index) {
                        if (item.nodeIndex.toString() == result.message) {
                            layer.msg(item.name + '_无数据', {icon: 2})
                            return
                        }
                    })

                }
                //***********关闭loading
                ityzl_CLOSE_LOAD_LAYER(i);
            }
        })
    }


    //模拟控制进度条（一个月）
   /* function moniProcess(linNum) {
        cal(2000, linNum)
    }

    //计算
    function cal(n, linNum) {
        var proIndex = 20;
        var proce1 = window.setInterval(function () {
            element.progress('demo2', proIndex + '%');
            if (proIndex < 95) {
                proIndex += 2;
            }
            if (Obj.lineNum == linNum) {
                element.progress('demo2', '100%');
                clearInterval(proce1)
                window.setTimeout(function () {
                    layer.closeAll()
                }, 500)
            }

        }, n)
    }
*/

    //批量导出csv文件
    function ajaxForDown(arr) {
        const req = new XMLHttpRequest();
        let URL = '/pqs9900/csv/getCsvAsSession?lineid=' + filterXSS(arr.nodeIndex) + '&beginTime=' + filterXSS(Obj.beginTime) + '&endTime=' + filterXSS(Obj.endTime)
        req.open('GET', URL, true);
        req.responseType = 'blob';
        req.setRequestHeader('Content-Type', 'application/json');
        req.onload = function () {
            const data = req.response;
            if (this.status === 200) {
                if (data.type == "application/csv") {
                    Obj.lineNum++
                    element.progress('demo2', 100 / Obj.lineAllNum * Obj.lineNum + '%');
                    const blob = new Blob([data]);
                    const blobUrl = window.URL.createObjectURL(blob);
                    download(blobUrl, arr)

                    if (Obj.lineNum == Obj.lineAllNum) {
                        //全部导出时
                        element.progress('demo2', '100%');
                        window.setTimeout(function () {
                            layer.closeAll()
                            parent.layer.close(loadIndex2)
                        }, 500)

                    }
                } else if (data.type == "application/json") {
                    layer.msg('该检测点下无数据', {icon: 2})
                } else {
                    layer.msg('错误', {icon: 2})
                }
            } else {
                layer.msg('未知错误', {icon: 2})
            }
        };
        req.send();
    }

    //导出数据
    function request(arr) {
        var loadIndex = parent.layer.open({
            type: 1
            , title: false //不显示标题栏
            , closeBtn: false
            , area: '0px'
            , shade: 0.15
            , id: 'LAY_layuipro1' //设定一个id，防止重复弹出
            , btnAlign: 'c'
            , moveType: 1 //拖拽模式，0或者1
        });

        const req = new XMLHttpRequest();
        req.open('GET', '/pqs9900/csv/getCsvAsSession?lineid=' + filterXSS(arr[0].nodeIndex) + '&beginTime=' + filterXSS(Obj.beginTime) + '&endTime=' + filterXSS(Obj.endTime), true);
        req.responseType = 'blob';
        req.setRequestHeader('Content-Type', 'application/json');
        req.onload = function () {
            if (this.status === 200) {
                const data = req.response;
                if (data.type == "application/csv") {
                    Obj.flag = true
                    const blob = new Blob([data]);
                    const blobUrl = window.URL.createObjectURL(blob);
                    download(blobUrl, arr[0]);
                    element.progress('demo2', '100%');
                    window.setTimeout(function () {
                        layer.closeAll();
                        parent.layer.close(loadIndex)
                    }, 500)
                } else if (data.type == "application/json") {
                    layer.closeAll();
                    parent.layer.close(loadIndex)
                    layer.msg('该监测点暂无数据', {icon: 2}, 1000)
                } else {
                    layer.msg('未知错误', {icon: 2}, 1000)
                }
                if(myInt!=null){
                    clearInterval(myInt)
                }
                $("#getCsv").removeClass('layui-btn-disabled');
            } else {
                layer.msg('未知错误', {icon: 2}, 1000)
            }
        };
        req.send();
    };

    function download(blobUrl, arr) {
        let work_name = ''
        workspace.forEach(function (item) {
            if(item.id == arr.pId){
                work_name = item.name
            }
        })
        const a = document.createElement('a');
        a.style.display = 'none';
        a.download = Obj.beginTime + '-' + Obj.endTime +' '+work_name+'_'+arr.anotherName + '监测数据.csv';
        a.href = blobUrl;
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(a.href); // 释放URL 对象
        document.body.removeChild(a);
    }


    //获取后台返回的进度条信息
    function getCsvNew() {
        $("#getCsv").addClass('layui-btn-disabled');

        /*** 进度条的显示  */
        window.setTimeout(function () {
             myInt = window.setInterval(function () {
                $.ajax({
                    method: "get",
                    url: "/pqs9900/csv/flushProgress2",
                    success: function (data) {
                        if (data.code == 200) {
                            let n = data.body.percent
                            if(isNaN(n)){
                                clearInterval(myInt)
                                layer.msg("出错了")
                                return
                            }
                            if (n < 0) {
                                clearInterval(myInt)
                                return;
                            }
                            element.progress('demo2', n + '%');
                            //当为100时终止
                            if (n == 100 || Obj.flag == true) {
                                element.progress('demo2', '100%');
                                clearInterval(myInt)
                                $("#getCsv").removeClass('layui-btn-disabled');
                                window.setTimeout(function () {
                                    layer.closeAll();
                                }, 500)
                            }
                        } else {
                            clearInterval(myInt)
                            layer.msg("出错了")
                            return
                        }

                    },
                    error: function () {
                        clearInterval(myInt)
                        return
                    }

                });
            }, 1500);
        }, 1500);

    }


    //第一个实例
    function initPage() {
        //总页数大于页码总数
        laypage.render({
            elem: 'demo1'
            , theme: 'abcdfg'
            , layout: ['prev', 'page', 'next', 'skip', 'count']
            , count: Obj.total //数据总数
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    Obj.page = obj.curr;
                    getDetail();
                    $('.layui-laypage-abcdfg').children('.layui-laypage-curr').find('.layui-laypage-em').css('background-color', '' + color)
                }
            }
        })
    }

    //初始化页面
    function getDetail() {
    	Obj.beginTime = filterXSS(Obj.beginTime);
    	Obj.endTime = filterXSS(Obj.endTime);
        $.ajax({
            method: "get",
            dataType: "json",
            contentType: 'application/json;charset=UTF-8',
            url: '/pqs9900/csv/getAllInfo?lineid=' + Obj.lineIndex + '&page=' + Obj.page + '&pageSize=' + Obj.pageSize + '&beginTime=' + Obj.beginTime + '&endTime=' + Obj.endTime,
            beforeSend: function () {
                i = ityzl_SHOW_LOAD_LAYER();
            },
            success: function (result) {
                Obj.total = result.body.pageInfo.total
                arr = result.body.pageInfo.list;
                var k =0
                for(var l in arr[0]){
                    k++
                }
                if (result.code == 200) {
                    if (arr.length != 0) {
                        arr.map(function (item) {

                            var date = item.TIMEID
                            date = new Date(date);
                            var year = date.getFullYear() + '-';
                            var month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                            var day = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
                            var hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
                            var min = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
                            var secon = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());

                            item.TIMEID = year+month+day+' '+hour+min+secon
                            return item
                        })
                    } else {
                        table.reload('table_1', {data: arr});
                        layer.msg('数据为空', {icon: 2})
                    }
                    table.reload('table_1', {data: arr});

                    if (Obj.page == 1) {
                        initPage();
                        $('.layui-laypage-abcdfg').children('.layui-laypage-curr').find('.layui-laypage-em').css('background-color', '' + color)
                    }
                    //***********关闭loading
                    ityzl_CLOSE_LOAD_LAYER(i);
                } else {


                }
            },
            error: function () {
                layer.closeAll()
                layer.msg('未知错误')
            }
        })


    }

    //转换table标题
    function toF(list) {
        dafautTitle = []
        if (list != null) {
            for (var i = 0; i < list.length; i++) {
                let aa = {}
                aa.field = list[i]
                aa.title = list[i]
                aa.align = 'center'
                dafautTitle.push(aa)
            }

        }
    }

    //进度条控制
    function processShow() {
        element.progress('demo2', 0); //进度条初始化
        layer.open({
            type: 1
            ,
            title: false //不显示标题栏
            ,
            closeBtn: false
            ,
            area: '300px;'
            ,
            shade: 0
            ,
            id: 'LAY_layuipro' //设定一个id，防止重复弹出
            ,
            btnAlign: 'c' //按钮居中
            ,
            moveType: 1 //拖拽模式，0或者1
            ,
            content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' +
                '<div class="layui-progress" id="progress" lay-filter="demo2">' +
                '<div class="layui-progress-bar " ></div>' +
                '</div>' +
                '<br>数据正在导出.....<br><br></div>'

        });
    }


    //批量进度条
    //进度条控制
    /*function BatchprocessShow(){
        layer.open({
            type: 1
            ,title: false //不显示标题栏
            ,closeBtn: false
            ,area: '300px;'
            ,shade: 0
            ,id: 'LAY_layuipro1' //设定一个id，防止重复弹出
            ,btnAlign: 'c'
            ,moveType: 1 //拖拽模式，0或者1
            ,content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' +
                '<div class="layui-progress" id="progress" lay-filter="demo2">' +
                '<div class="layui-progress-bar " ></div>' +
                '</div>' +
                '<br>数据正在导出.....<br><br></div>'

        });
    }*/


    //获取设备书选择的监测点id对象
    function getTreeCheckBoxData() {
        return parent.getTreeSelected(1);
    }


    var mons = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    function isLeapYear(year) {
        var r = year / 100
        if (r === parseInt(r)) {
            r = year / 400
            return r === parseInt(r)
        }
        r = year / 4
        if (r === parseInt(r)) {
            return true
        }
        return false
    }

    function getDaysOfMonth(month, year) {
        if (month === 2 && isLeapYear(year)) {
            return 29
        }
        return mons[month]
    }

    function getMonthsOfYear(year) {
        if (isLeapYear(year)) {
            return 366
        }
        return 365
    }

    function diff(s1, s2) {
        var arr1 = s1.split('-').map(Number)
        var arr2 = s2.split('-').map(Number)
        var [year, month, day] = arr2.map((n, i) => n - arr1[i])
        if (day < 0) {
            day += getDaysOfMonth(arr2[1], arr2[0])
            month--
        }
        if (month < 0) {
            month += getMonthsOfYear(arr2[0])
            year--
        }
        return [year, month, day]
    }


});


//子页面调用父页面
function initDetail(index) {
    Obj.clickOrCheck = true
    Obj.lineIndex = index
    Obj.page = 1
    $('#queryCsv').trigger('click')
}

var path = window.location.href;// 获取界面路径

var titleList = ["TIMEID","电压总谐波畸变率A相最大值","电压总谐波畸变率B相最大值","电压总谐波畸变率C相最大值",
    "电压总谐波畸变率A相95值","电压总谐波畸变率B相95值","电压总谐波畸变率C相95值","电压有效值A相平均值","电压有效值B相平均值","电压有效值C相平均值",
    "电压有效值A相最大值","电压有效值B相最大值","电压有效值C相最大值","电流有效值A相平均值","电流有效值B相平均值","电流有效值C相平均值",
    "电流有效值A相最大值","电流有效值B相最大值","电流有效值C相最大值","电压偏差A相平均值","电压偏差B相平均值",
    "电压偏差C相平均值","电压偏差A相最大值",
    "电压偏差B相最大值","电压偏差C相最大值","电压偏差A相95值","电压偏差B相95值","电压偏差C相95值","有功功率平均值","有功功率最小值","有功功率最大值",
    "无功功率平均值","无功功率最小值","无功功率最大值","视在功率平均值","视在功率最小值","视在功率最大值",
    "谐波电压含有率3次A相平均值","谐波电压含有率3次B相平均值","谐波电压含有率3次C相平均值","谐波电压含有率3次A相最大值",
    "谐波电压含有率3次B相最大值","谐波电压含有率3次C相最大值","谐波电压含有率3次A相95值","谐波电压含有率3次B相95值",
    "谐波电压含有率3次C相95值","谐波电压含有率5次A相平均值","谐波电压含有率5次B相平均值","谐波电压含有率5次C相平均值",
    "谐波电压含有率5次A相最大值","谐波电压含有率5次B相最大值","谐波电压含有率5次C相最大值","谐波电压含有率5次A相95值",
    "谐波电压含有率5次B相95值","谐波电压含有率5次C相95值","谐波电压含有率7次A相平均值","谐波电压含有率7次B相平均值",
    "谐波电压含有率7次C相平均值","谐波电压含有率7次A相最大值","谐波电压含有率7次B相最大值","谐波电压含有率7次C相最大值",
    "谐波电压含有率7次A相95值","谐波电压含有率7次B相95值","谐波电压含有率7次C相95值","谐波电压含有率9次A相平均值",
    "谐波电压含有率9次B相平均值","谐波电压含有率9次C相平均值","谐波电压含有率9次A相最大值","谐波电压含有率9次B相最大值",
    "谐波电压含有率9次C相最大值","谐波电压含有率9次A相95值","谐波电压含有率9次B相95值","谐波电压含有率9次C相95值",
    "谐波电压含有率11次A相平均值","谐波电压含有率11次B相平均值","谐波电压含有率11次C相平均值","谐波电压含有率11次A相最大值",
    "谐波电压含有率11次B相最大值","谐波电压含有率11次C相最大值","谐波电压含有率11次A相95值","谐波电压含有率11次B相95值",
    "谐波电压含有率11次C相95值","谐波电压含有率13次A相平均值","谐波电压含有率13次B相平均值","谐波电压含有率13次C相平均值",
    "谐波电压含有率13次A相最大值","谐波电压含有率13次B相最大值","谐波电压含有率13次C相最大值","谐波电压含有率13次A相95值",
    "谐波电压含有率13次B相95值","谐波电压含有率13次C相95值","谐波电压含有率15次A相平均值","谐波电压含有率15次B相平均值",
    "谐波电压含有率15次C相平均值","谐波电压含有率15次A相最大值","谐波电压含有率15次B相最大值","谐波电压含有率15次C相最大值",
    "谐波电压含有率15次A相95值","谐波电压含有率15次B相95值","谐波电压含有率15次C相95值","谐波电压含有率25次A相平均值",
    "谐波电压含有率25次B相平均值","谐波电压含有率25次C相平均值","谐波电压含有率25次A相最大值","谐波电压含有率25次B相最大值",
    "谐波电压含有率25次C相最大值","谐波电压含有率25次A相95值","谐波电压含有率25次B相95值","谐波电压含有率25次C相95值",
    "谐波电流幅值3次A相平均值","谐波电流幅值3次B相平均值","谐波电流幅值3次C相平均值","谐波电流幅值3次A相最大值","谐波电流幅值3次B相最大值",
    "谐波电流幅值3次C相最大值","谐波电流幅值3次A相95值","谐波电流幅值3次B相95值","谐波电流幅值3次C相95值","谐波电流幅值5次A相平均值",
    "谐波电流幅值5次B相平均值","谐波电流幅值5次C相平均值","谐波电流幅值5次A相最大值","谐波电流幅值5次B相最大值","谐波电流幅值5次C相最大值",
    "谐波电流幅值5次A相95值","谐波电流幅值5次B相95值","谐波电流幅值5次C相95值","谐波电流幅值7次A相平均值","谐波电流幅值7次B相平均值",
    "谐波电流幅值7次C相平均值","谐波电流幅值7次A相最大值","谐波电流幅值7次B相最大值","谐波电流幅值7次C相最大值","谐波电流幅值7次A相95值",
    "谐波电流幅值7次B相95值","谐波电流幅值7次C相95值","谐波电流幅值9次A相平均值","谐波电流幅值9次B相平均值","谐波电流幅值9次C相平均值",
    "谐波电流幅值9次A相最大值","谐波电流幅值9次B相最大值","谐波电流幅值9次C相最大值","谐波电流幅值9次A相95值","谐波电流幅值9次B相95值",
    "谐波电流幅值9次C相95值","谐波电流幅值11次A相平均值","谐波电流幅值11次B相平均值","谐波电流幅值11次C相平均值","谐波电流幅值11次A相最大值",
    "谐波电流幅值11次B相最大值","谐波电流幅值11次C相最大值","谐波电流幅值11次A相95值","谐波电流幅值11次B相95值","谐波电流幅值11次C相95值",
    "谐波电流幅值13次A相平均值","谐波电流幅值13次B相平均值","谐波电流幅值13次C相平均值","谐波电流幅值13次A相最大值","谐波电流幅值13次B相最大值",
    "谐波电流幅值13次C相最大值","谐波电流幅值13次A相95值","谐波电流幅值13次B相95值","谐波电流幅值13次C相95值","谐波电流幅值15次A相平均值",
    "谐波电流幅值15次B相平均值","谐波电流幅值15次C相平均值","谐波电流幅值15次A相最大值","谐波电流幅值15次B相最大值","谐波电流幅值15次C相最大值",
    "谐波电流幅值15次A相95值","谐波电流幅值15次B相95值","谐波电流幅值15次C相95值","谐波电流幅值25次A相平均值","谐波电流幅值25次B相平均值",
    "谐波电流幅值25次C相平均值","谐波电流幅值25次A相最大值","谐波电流幅值25次B相最大值","谐波电流幅值25次C相最大值","谐波电流幅值25次A相95值",
    "谐波电流幅值25次B相95值","谐波电流幅值25次C相95值","电压负序不平衡度平均值","电压负序不平衡度最大值","电压负序不平衡度95值","频率平均值",
    "频率最大值","频率95值","A相短闪平均值","B相短闪平均值","C相短闪平均值"]
