/*
 *title:notice-push-add
 *@auther  liaoxin
 *date:2018/12/6
*/
layui.extend({
    common    :   'js/common',
    pushType: 'layui/lay/mymodules/push-type'
}).use([ 'jquery','layer','common','form','laydate','element','table','pushType'], function () {
    //  Jquery插件
    var $ = layui.jquery;
    //  引入公共模块
    var common = layui.common;
    //引入表单
    var form = layui.form;
    //上传文件
    var upload= layui.upload;
    //时间模块
    var layDate=layui.laydate;
    //element模块
    var element = layui.element;
    //  初始化发布类型
    layui.pushType.init({ height  :   'full-235'});
    //选中的发布公告集合
    var pbMap = new Map();

    var  startDate,endDate1;
    //监听提交
    form.on('submit(entity_submit_event)', function(data){
        common.timer($('button[lay-filter="entity_submit_event"]'));
        var pushTargetValue="";
        var $pushTarget=$("input[name='pushTarget']:checked");
        $pushTarget.each(function (i) {
            var value=$(this).val();
            if(i==0){
                pushTargetValue+=value;
            }else{
                pushTargetValue+=","+value;
            }

        });
        //选中的数据
        var obj =layui.pushType.getSelectedData();
        //1-按小区 2-按单元 3-按设备 4-按区域
        var pushType = obj.type;
        data.field.pushType = pushType;
        var fkIds = obj.list;
        if(fkIds.length<=0){
            var targetName="小区";
            if(pushType==1){
                targetName="小区";
            }else if(pushType==2){
                targetName="单元";
            }else if(pushType==3){
                targetName="设备";
            }else if(pushType==4){
                targetName="区域";
            }
            layer.msg("请选择要发布的"+targetName);
            return;
        }
        var body = data.field;
        if (pbMap.size === 0){
            layer.alert("请先关联策略");
            return;
        }
        if (pbMap.size > 1){
            layer.alert("请关联一条策略");
            return;
        }
        pbMap.forEach(function (data) {
            body.noticeId=data.id;
        });
        body.fkIds = fkIds.toString();
        body.pushTarget=pushTargetValue;
       //传递时间参数值
        body.startDate=startDate;
        body.endDate=endDate1;
        common.sendAsyncRequest("/estate/noticePush/addNoticePush",'POST',body,callbackFn);
    });
    //回调函数
    function callbackFn(result) {
        if(result.code=='200'){
            if(result.data){
                layer.msg("添加成功",{
                    time: 500,
                    shade : [0.1 , '#000' , true]
                },function () {
                    //获取当前弹窗出层的名字
                    var index = parent.layer.getFrameIndex(window.name);
                    //关闭弹窗层
                    parent.layer.close(index);
                    // 父页面刷新
                    parent.location.reload();
                });
            }else{
                layer.msg("添加失败");
            }

        }else {//添加失败
            layer.msg("操作失败");
        }
    }
    //取消按钮
    $('#cancel_btn').on("click",function(){
        //获取当前弹窗出层的名字
        var index = parent.layer.getFrameIndex(window.name);
        //关闭弹窗层
        parent.layer.close(index);
    });
    //日期时间范围选择
    layDate.render({
        elem: '#laydate-range-datetime'
        ,type: 'date'
        ,range:true //或 range: '~' 来自定义分割字符
        ,done: function(value, date, endDate){
            //date得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            if(value){
                var dates=value.split(" - ");
                startDate=dates[0] + ' 00:00:00';
                endDate1=dates[1] + ' 23:59:59';
            }else{
                startDate="";
                endDate1="";
            }
        }
    });
    //自定义验证规则
    form.verify({
        checkboxMustBe:function(value) {
        if (!$("input[name='pushTarget']").is(":checked")) {
            return "请选择发布渠道";
        }
    }
    });


    var layuiTable;
    var relation_np_window;
    $('#relation_np_btn').on('click',function () {
        relation_np_window=layer.open({
            title   :   '关联公告',
            type    :   1,
            maxmin  :   false,
            area    :   ['1000px', '550px'],
            content :   $('#np_content_table').html()
        });
        layuiTable = layui.common.layuiTable.render(layui.table,{
            elem: '#np_entity_table'
            ,url: '/estate/notice/showServerUserList'
            ,toolbar: '#table-head-id'
            , cols: [[
                { type: 'radio' }
                ,{ field: 'title', title: '公告标题', width:150}
                ,{ field: 'code', title: '公告编号' }
                ,{ field: 'content', title: '公告内容' }
                ,{ field: 'createAccountName', title: '创建人' }
                ,{ field: 'createDate', title: '创建时间' }
            ]]
            ,done : function(result){
                var list = result.data;
                for (var i = 0; i < list.length; i++){
                    var entity = list[i];
                    var data = pbMap.get(entity.id);
                    if (data){
                        $('div[lay-id="np_entity_table"] .layui-table-box table tr[data-index="' + i + '"]').find('td:first .layui-form-radio').click();
                    }
                }
            }
            , height: '350'
        });

    });

    //  查询策略
    $(document).on('click','#select_btn',function () {
        layuiTable.reload({
            //  设定异步数据接口的额外参数
            where: {
                title    :   $('#np_title').val()
            }
            //  重新从第1页开始
            ,page: {
                curr: 1
            }
        })
    });

    //单选框事件
    layui.table.on('radio(np_entity_event)',function (obj) {
        //清空
        pbMap.clear();
        var id = obj.data.id;
        pbMap.set(id,obj.data);
        $('.select_count').html(pbMap.size);
    });

    //头工具栏事件 lay-filter="ts_entity_event"
    layui.table.on('toolbar(np_entity_event)', function(obj){
        var data = obj.data;
        //确认选择
        if(obj.event === 'confirm'){
            //获取当前弹窗出层的名字
            //关闭弹窗层
            layer.close(relation_np_window);
        } else if(obj.event === 'clear'){ //清空选择
            $('#np_entity_table').next().find('input:radio[lay-type=layTableRadio]').prop('checked', false);
            layui.form.render('radio');
            //清空
            pbMap.clear();
            $('.select_count').html(pbMap.size);
        }
    });
});