layui.extend({
    common    :   'js/common'
}).use(['table', 'jquery','layer','common','form',], function () {
    //  弹窗插件
    var layer = layui.layer;
    //  Jquery插件
    var $ = layui.jquery;
    //  引入公共模块
    var common = layui.common;
    //  引入表格
    var table = layui.table;
    //引入表单
    var form = layui.form;

    var pageData = {
        residentialId : $('#residential_id').val(),
        openType : '',
        faceChargeProjectList : [],
    };

    var reloadTable = function(obj){
        //重新加载表格
        layuiTable.reload({
            where:{
                //排序
                sortField   :   obj?obj.field:'',
                sortOrder   :   obj?obj.type:'',
            }
            //重新从第1页开始
            ,page: {
                curr: 1
            },
            initSort:obj
        });
    };

    var layuiTable = common.layuiTable.render(table,{
        elem: '#table-id'
        ,url: '/estate/faceChargeProject/showFaceChargeProjectList?residentialId=' + pageData.residentialId
        ,cellMinWidth: 80//全局定义常规单元格的最小宽度，
        , cols: [[
            { field: 'name', title: '套餐名称',align: 'center'}
            ,{ field: 'type', title: '套餐类型',templet: '#type',align: 'center' }
            ,{ field: 'typeItem', title: '收费类型',templet: '#typeItem',align: 'center' }
            ,{ field: 'amount', title: '金额(元)',align: 'center' }
            ,{ field: 'days', title: '天数',align: 'center' }
            , {field: 'discount', align: 'center', title: '折扣(%)', templet: function (d) {
                if (d.discount == 100) {
                    return '<span>无</span>'
                }else {
                    return d.discount;
                }
                }}
            , {field: 'putStatus', title: '上架状态', templet: '#putStatusChange', width: 100, align: 'center'}
            ,{ field: 'endDate',width:300,align: 'center', title: '套餐有效期',sort:true,templet:function(d){
                return layui.util.toDateString(d.beginDate)+" 至 "+layui.util.toDateString(d.endDate);}}
            ,{ title: '操作',width:180,align: 'center', toolbar: '#table-useradmin-webuser' }
        ]]
        //  开启分页功能
        , page : true
        , done : function (result) {
            buttonFn();
        }
    });

    var buttonFn = function (){
        $.ajax({
            url: '/estate/faceChargeProject/selectByResidentialId',
            type: 'GET',
            data : {
                residentialId : pageData.residentialId
            },
            success: function (result) {
                pageData.faceChargeProjectList = result.list;
                var typeFreePut = false;
                var typeTollPut = false;
                for (var i in pageData.faceChargeProjectList){
                    if (typeFreePut && typeTollPut){
                        break;
                    }
                    if (pageData.faceChargeProjectList[i].putStatus == 1){
                        if (pageData.faceChargeProjectList[i].type == 1 && !typeFreePut){
                            $('button[value="1"]').attr('disabled','disabled').addClass('layui-btn-disabled').attr('title','已有上架的免费人脸项目，请直接修改免费人脸项目。');
                            typeFreePut = true;
                            continue;
                        }
                        if (pageData.faceChargeProjectList[i].typeItem == 21 && !typeTollPut){
                            $('button[value="2"]').attr('disabled','disabled').addClass('layui-btn-disabled').attr('title','已有上架的收费类型为【押金】的人脸项目，请直接修改收费人脸项目。');
                            typeTollPut = true;
                        }
                    }
                }
                if (!typeFreePut){
                    $('button[value="1"]').removeAttr('disabled','disabled').removeClass('layui-btn-disabled').removeAttr('title','已有上架的免费人脸项目，请直接修改免费人脸项目。');
                }
                if (!typeTollPut){
                    $('button[value="2"]').removeAttr('disabled','disabled').removeClass('layui-btn-disabled').removeAttr('title','已有上架的收费类型为【押金】的人脸项目，请直接修改收费人脸项目。');
                }
            },
        });
    };

    //工具条事件 lay-filter="table-even"
    table.on('tool(table-even)', function(obj){
        var data = obj.data;
        switch(obj.event){
            case 'edit':
                common.openMaxIframe({
                    title   :   '修改套餐信息',
                    content :   '/estate/faceChargeProject/edit/'+data.id
                });
                break;
            case 'delete':
                data.status = -1;
                layer.confirm("是否确认删除？",{icon: 7, title:'提示'},function(){
                    common.sendAsyncRequest("/estate/faceChargeProject/deleteFaceChargeProject",'POST',data,function(result){
                        if(result.code=='200'){
                            if(result.data) {
                                layer.msg("删除成功", {
                                    time: 500
                                }, function () {
                                    reloadTable();
                                    // 父页面刷新
                                    // location.reload();
                                });
                            }else {//删除失败
                                layer.msg("删除失败");
                            }
                        }else {//删除失败
                            layer.msg("删除失败");
                        }
                    });
                });
                break;
        }
    });

    //监听启用或者禁用
    form.on('switch(putStatusChange)', function (obj) {
        let item = obj.value.split(',');
        let putStatusChange = obj.elem.checked;
        let text = putStatusChange ? '上架' : '下架';
        let data = {
            id              : item[0],
            residentialId   : item[1],
            type            : item[2],
            //如果上架的是套餐，则该小区不能拥有上架的押金
            typeItem        : item[3] == 22 ? 21:'',
            putStatus       : putStatusChange ? 1 : 2
        };

        //是否是上架
        if (putStatusChange){
            let pass = checkPutStatus(data);
            if (!pass){
                reloadTable();
                layer.msg("上架失败，已存在状态为[上架]的同类型套餐");
                return;
            }
        }
        //更新
        $.ajax({
            url: '/estate/faceChargeProject/putStatusChange',
            type: 'POST',
            data : {
                id  :   data.id,
                putStatus : data.putStatus
            },
            success: function (result) {
                layer.msg(text + '成功')
            },
            error: function () {
                layer.msg(text + '失败')
            }
        });
        reloadTable();
    });

    var checkPutStatus = function(data){
        let pass;
        $.ajax({
            url: '/estate/faceChargeProject/checkPutStatus',
            type: 'GET',
            async: false, // 同步
            data: data,
            success: function (result) {
                pass = result.data;
            },
        });
        return pass
    };

    //监听添加套餐按钮
    form.on('submit(add)', function(data){
        pageData.openType = data.elem.value;
        common.openMaxIframe({
            title   :   '添加人脸套餐',
            content :   '/estate/faceChargeProject/add/' + pageData.residentialId + '/' + pageData.openType
        });
    });

    /*//监听添加收费按钮
    form.on('submit(addToll)', function(){
        pageData.openType = 2;
        common.openMaxIframe({
            title   :   '添加收费人脸套餐',
            content :   '/estate/faceChargeProject/add/' + pageData.residentialId + '/' + pageData.openType
        });
    });*/

    //监听批量删除
    form.on('submit(batchdel)', function(){
        if(ids.length == 0 ){
            layer.msg("请选择要删除的数据。");
            return;
        }
        layer.confirm('是否确认删除？',{icon: 7, title:'提示'}, function(index){
            $.ajax({
                url :   '/estate/notice/deleteNoticeList',
                type : 'POST',
                contentType: "application/json;charset=utf-8",
                data :JSON.stringify(ids),
                success :  function(result){
                    if(result.code == '200'){
                        if(result.data){
                            //  刷新表格
                            layuiTable.reload();
                            clearCheckbox();
                            layer.msg("删除成功");
                            layer.close(index);
                        }else{
                            layer.msg("删除失败");
                        }
                    }else{
                        layer.msg(result.msg);
                    }
                }
            });
        });
    });

});