"use strict";
layui.extend({
    common    :   'js/common'
}).use(['jquery','layer','common','table','laydate','tree','form'],function () {
    var $ = layui.jquery;
    var taskType = $('input[name="taskType"]').val();

    var form = layui.form;

    //日期时间范围
    layui.laydate.render({
        elem: '#date_range'
        ,type: 'month'
        ,format: 'yyyyMM'
        ,max: 0 //最小日期为当天
    });

    var selectedIdSet = new Set();

    //  初始化表单
    var layuiTable = layui.common.layuiTable.render(layui.table,{
        elem: '#data_table'
        ,url: '/ad/device/statistics/pagingQuery?taskType=' + taskType
        ,cols: [[
            { type :'checkbox' }
            ,{ field: 'deviceName', title: '设备名称',align:'center',width:200 }
            ,{ field: 'deviceSerialNumber', title: '序列号',align:'center',width:160 }
            ,{ field: 'deviceInstallPath', title: '安装位置',align:'center',width:100 }
            ,{ field: 'publishCount', title: '发布广告数',align:'center',width:100 }
            ,{ field: 'adCount', title: '当前广告数',align:'center',width:100 }
            ,{ field: 'browseCount', title: '总观看次数',align:'center',width:100 }
            ,{ field: 'lastMonthBrowse', title: '上月观看',align:'center',width:90 }
            ,{ field: 'week1Browse', title: '第一周',align:'center',width:80 }
            ,{ field: 'week2Browse', title: '第二周',align:'center',width:80 }
            ,{ field: 'week3Browse', title: '第三周',align:'center',width:80 }
            ,{ field: 'week4Browse', title: '第四周',align:'center',width:80 }
            ,{ field: 'earlyWarningCount', title: '预警次数',align:'center',width:90 }
            , { title: '操作', align: 'center',toolbar: '#table-operate'}
        ]]
        , done : function(result){
            var list = result.data;
            for (var i = 0; i < list.length; i++) {
                var entity = list[i];
                selectedIdSet.forEach(function (selectedId) {
                    if (entity['deviceId'] === selectedId){
                        $('div[lay-id="data_table"]').find('.layui-table-box table tr[data-index="' + i + '"]').find('td:first .layui-form-checkbox').eq(0).click();
                    }
                });
            }
        }
    });

    layui.table.on('checkbox(data_table_event)',function (obj) {
        if (obj.type === 'all'){
            if (obj.checked){
                //  全选
                var list = layui.table.checkStatus('data_table').data;
                list.forEach(function(entity){
                    selectedIdSet.add(entity['deviceId'])
                });
            }else {
                //  全不选
                layui.table.cache['data_table'].forEach(function(entity){
                    selectedIdSet.delete(entity['deviceId']);
                });
            }
        }else {
            var id = obj.data['deviceId'];
            obj.checked ? selectedIdSet.add(id) : selectedIdSet.delete(id);
        }
    });

    var regionCode = undefined;
    var xqId = undefined;

    //  重新加载表格
    var reloadTable = function() {
        var where = {
            deviceName  :   $('input[name="deviceName"]').val(),
            deviceSerialNumber  :   $('input[name="deviceSerialNumber"]').val(),
            createTime :   $('input[name="createTime"]').val(),
            regionArea : regionCode,
            xqId : xqId
        };
        layuiTable.reload({ where: where ,page: { curr: 1 } });
    };

    //  操作栏事件绑定
    layui.table.on('tool(data_table_event)',function (obj) {
        if (obj.event && obj.event === 'info'){
            var url = taskType === '1' ? '/ad/device/face/list?serialNumber=' : '/ad/device/leisure/list?serialNumber=';
            //  详情页
            layui.common.openDefaultIframe({
                title   :   '详情',
                content :   url + obj.data['deviceSerialNumber']
            });
        }
    });

    //  省市区树
    (function () {
        function selectRegion(pid,flag,$node){
            $.ajax({
                url : '/permissions/region/authorize/getAuthorizeRegion',
                type : 'GET',
                data : { 'groupBy' : flag, 'pid' : pid },
                success : function (result) {
                    if (result.code === '200'){
                        pid === undefined ? void(0): ++flag;
                        var htmlText = '<ul class="layui-show">';
                        result.list.forEach(function (item) {
                            htmlText += '' +
                                '<li data-id="' + item.id + '" data-flag="' + flag + '">' +
                                '   <i class="layui-icon layui-icon-triangle-r layui-tree-spread"></i>' +
                                '   <a href="javascript: void(0);"><cite>' + item.name + '</cite></a>' +
                                '</li>';
                        });
                        htmlText += '</ul>';
                        $node.append(htmlText);
                    }
                }
            });
        }

        //  查询省
        selectRegion(undefined,1,$('#per-tree li[data-id="0"]'));

        //  将树收起
        $(document).on('click','#per-tree .layui-icon-triangle-d',function () {
            $(this).removeClass('layui-icon-triangle-d').addClass('layui-icon-triangle-r');
            $(this).siblings('ul').removeClass('layui-show');
        });

        //  将树展开
        $(document).on('click','#per-tree .layui-icon-triangle-r',function () {
            var $this = $(this);
            $this.removeClass('layui-icon-triangle-r').addClass('layui-icon-triangle-d');
            $this.siblings('ul').addClass('layui-show');
            //  加载子节点
            var $li = $this.closest('li');

            if ($li.find('ul').length > 0){
                return;
            }

            var id = $li.attr('data-id');
            //  当前的数据标识: { 1：省，2：市，3：区，4：小区 }
            var flag = $li.attr('data-flag');
            if (id === '0' || !flag){
                return;
            }
            //  查询省市区
            if (flag === '1' || flag === '2'){
                selectRegion(id,flag,$li);
            } else {
                $.ajax({
                    url :   "/permissions/region/authorize/getAuthorizeOrgList",
                    type : "GET",
                    data : { "region" : id},
                    success : function (result) {
                        if (result.code === '200'){
                            if (result.list.length === 0){
                                $this.remove();
                            }
                            ++flag;
                            var htmlText = '<ul class="layui-show">';
                            result.list.forEach(function (item) {
                                htmlText += '' +
                                    '<li data-id="' + item.id + '" data-flag="' + flag + '">' +
                                    '   <a href="javascript: void(0);"><cite>' + item.name + '</cite></a>' +
                                    '</li>';
                            });
                            htmlText += '</ul>';
                            $li.append(htmlText);
                        }
                    }
                });
            }
        });

        //  选中或不选中
        $(document).on('click','#per-tree li a',function () {
            if ($(this).hasClass('citecolor')){
                $(this).removeClass('citecolor');
                regionCode = undefined;
                xqId = undefined;
            }else {
                $('#per-tree li a').removeClass('citecolor');
                $(this).addClass('citecolor');
                var id = $(this).closest('li').attr('data-id');
                var flag = $(this).closest('li').attr('data-flag');
                if (flag === '4'){
                    xqId = id;
                    regionCode = undefined;
                }else if(flag){
                    xqId = undefined;
                    regionCode = id;
                }else {
                    xqId = undefined;
                    regionCode = undefined;
                }
            }
            reloadTable();
        });
    })();

    //监听查询
    form.on('submit(query)', function(){
        reloadTable();
    });

    //监听重置
    form.on('submit(reset)', function(){
        $('input[name="deviceName"]').val("");
        $('input[name="deviceSerialNumber"]').val("");
        $('input[name="createTime"]').val("");
        regionCode = undefined;
        xqId = undefined;
        // 刷新
        form.render();
        reloadTable();
    });

    //监听查询
    form.on('submit(setWarning)', function(){
        if (selectedIdSet.size === 0){
            layui.layer.alert('请选中设备');
            return;
        }
        layui.layer.open({
            type : 1,
            titile : '预警设置',
            area : ['550px','340px'],
            content : $('#warning_from').html(),
            btn : ['提交','取消'],
            btnAlign : 'c',
            yes : function (index) {
                var data = {
                    monthExpect : $('input[name="monthExpect"]').val(),
                    weekExpect  : $('input[name="weekExpect"]').val(),
                    taskType : taskType,
                    deviceIdList : []
                };
                if (!data.monthExpect && !data.weekExpect){
                    layui.layer.alert('请输入月预警值或月预警值!');
                    return;
                }
                selectedIdSet.forEach(function (item) {
                    data.deviceIdList.push(item);
                });
                //  发送请求
                $.ajax({
                    url : '/ad/face/early_warning/add',
                    type : 'POST',
                    contentType: "application/json;charset=utf-8",
                    data :  JSON.stringify(data),
                    success : function (result) {
                        if (result.code === '200'){
                            reloadTable();
                            layui.layer.close(index);
                        }else {
                            layui.layer.alert(result.msg);
                        }
                    }
                });

            }
        });
    });


});
