layui.extend({
    common    :   'js/common',
    xmSelect    :   'layui/dist/xm-select',
}).use(['jquery','layer','common','form','xmSelect'],function () {
    //  Jquery插件
    var $ = layui.jquery;
    //  弹窗插件
    var layer = layui.layer;
    //  引入表单插件
    var form = layui.form;
    //  引入公共模块
    var common = layui.common;
    //  引入下拉菜单
    var xmSelect = layui.xmSelect;

    //  页面数据
    var pageData = {
        residentialList : {},
        unitList : {},

        residentialNode : $('#residential_id'),
        unitNode : $('#unit_id'),

        selectTreeId : $('#selectTreeId').val(),
        treeFlag : '',

        parentId : $('#parentId').val(),
        flag : $('#flag').val()
    };

    layui.form.verify({
        specialCharacters : function (value) {
            if(!/^[a-zA-Z0-9_\u4e00-\u9fa5\s·]+$/.test(value)){
                return '名称不能有特殊字符';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '名称首尾不能出现下划线\'_\'';
            }
        },
        length : function (value) {
            if (value.length <2 || value.length > 20){
                return  '名称只能输入2-20个字符!'
            }
        },
        serial : function (value) {
            if (value[0] == 0){
                return '请输入不以0开头的数字！'
            }
            if(!/(^$)|^\d+$/.test(value)){
                return '只能填写正整数!'
            }
        }
    });

    //监听提交
    form.on('submit(submit_button)', function(data){
        common.timer($('button[lay-filter="submit_button"]'));
        common.sendAsyncRequest("/estate/room/addRoom",'POST',data.field,callbackFn);
    });

    //回调函数
    function callbackFn(result) {
        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("添加失败");
        }
    }

    //取消按钮
    $('#cancel_btn').on("click",function(){
        //获取当前弹窗出层的名字
        var index = parent.layer.getFrameIndex(window.name);
        //关闭弹窗层
        parent.layer.close(index);
    });

    pageData.treeFlag = getUrlParams('flag');
    //获取请求路径携带的参数
    function getUrlParams(name) { // 不传name返回所有值，否则返回对应值
        var url = window.location.search;
        if (url.indexOf('?') == 1) { return false; }
        url = url.substr(1);
        url = url.split('&');
        var name = name || '';
        var nameres;
        // 获取全部参数及其值
        for(var i=0;i<url.length;i++) {
            var info = url[i].split('=');
            var obj = {};
            obj[info[0]] = decodeURI(info[1]);
            url[i] = obj;
        }
        // 如果传入一个参数名称，就匹配其值
        if (name) {
            for(var i=0;i<url.length;i++) {
                for (var key in url[i]) {
                    if (key == name) {
                        nameres = url[i][key];
                    }
                }
            }
        } else {
            nameres = url;
        }
        // 返回结果
        return nameres;
    }

    //小区查询下拉列表
    var residentialSelect = xmSelect.render({
        el: '#residential_id',
        name: 'residentialId',
        layVerify: 'required',
        radio: true,
        prop: {
            name: 'name',
            value: 'id',
        },
        clickClose: true,
        paging: true,
        pageRemote: true,
        filterable: true,
        remoteMethod: function (val, cb, show,pageIndex) {
            $.ajax({
                type: 'GET',
                url: '/estate/residential/showResidentialList',
                data: {
                    name : val,
                    current : pageIndex,
                },
                success: function (result) {
                    cb(result.data.records,10);
                },
                error: function () {
                    cb([],0);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                buildingSelect.update({data:initBuildFn(change[0].id),disabled: false}).setValue([]);
                unitSelect.update({disabled: true }).setValue([]);
                floorSelect.update({disabled: true }).setValue([]);
            }
            if (!data.isAdd) {
                unitSelect.update({disabled: true }).setValue([]);
                buildingSelect.update({disabled: true }).setValue([]);
                floorSelect.update({disabled: true }).setValue([]);
            }
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });

    //楼栋查询下拉列表
    var buildingSelect = xmSelect.render({
        el: '#building_id',
        name: 'buildingId',
        layVerify: 'required',
        disabled: true,
        tips: '请先选择楼栋',
        radio: true,
        prop: {
            name: 'name',
            value: 'id',
        },
        clickClose: true,
        paging: true,
        pageRemote: true,
        filterable: true,
        remoteMethod: function (val, cb, show,pageIndex) {
            $.ajax({
                type: 'GET',
                url: '/estate/building/showBuildingList',
                data: {
                    name : val,
                    residentialId : residentialSelect.getValue('valueStr'),
                    current : pageIndex,
                },
                success: function (result) {
                    cb(result.data.records);
                },
                error: function () {
                    cb([],0);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                unitSelect.update({data : initUnitFn(change[0].id),disabled: false }).setValue([]);
                floorSelect.update({disabled:true}).setValue([])
            }
            if (!data.isAdd) {
                unitSelect.update({disabled: true }).setValue([]);
                floorSelect.update({disabled:true}).setValue([])

            }
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });

    //单元查询下拉列表
    var unitSelect = xmSelect.render({
        el: '#unit_id',
        name: 'unitId',
        layVerify: 'required',
        disabled: true,
        tips: '请先选择单元',
        radio: true,
        prop: {
            name: 'name',
            value: 'id',
        },
        clickClose: true,
        paging: true,
        pageRemote: true,
        filterable: true,
        remoteMethod: function (val, cb, show,pageIndex) {
            $.ajax({
                type: 'GET',
                url: '/estate/unit/showUnitList',
                data: {
                    name : val,
                    buildingId : buildingSelect.getValue('valueStr'),
                    current : pageIndex,
                },
                success: function (result) {
                    cb(result.data.records,5);
                },
                error: function () {
                    cb([],0);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                floorSelect.update({data : initFloorFn(change[0].id),disabled: false }).setValue([]);
            }
            if (!data.isAdd) {
                floorSelect.update({disabled:true}).setValue([])
            }
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });

    //楼层查询下拉列表
    var floorSelect = xmSelect.render({
        el: '#floor_id',
        name: 'floorId',
        layVerify: 'required',
        disabled: true,
        tips: '请先选择楼层',
        radio: true,
        prop: {
            name: 'name',
            value: 'id',
        },
        clickClose: true,
        paging: true,
        pageRemote: true,
        filterable: true,
        remoteMethod: function (val, cb, show,pageIndex) {
            $.ajax({
                type: 'GET',
                url: '/estate/floor/showFloorList',
                data: {
                    name : val,
                    unitId : unitSelect.getValue('valueStr'),
                    current : pageIndex,
                },
                success: function (result) {
                    cb(result.data.records,5);
                },
                error: function () {
                    cb([],0);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {}
            if (!data.isAdd) {}
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });
    function initUnitFn(buildingId) {
        var unitList;
        common.sendSyncRequest("/estate/unit/showUnitList", 'get', {buildingId: buildingId,current : 1,}, function (result) {
            unitList = result.data.records;
        });
        return unitList;
    }

    function initBuildFn(residentialId) {
        var buildingList;
        common.sendSyncRequest("/estate/building/showBuildingList", 'get', {residentialId: residentialId,current : 1,}, function (result) {
            buildingList = result.data.records;
        });
        return buildingList;
    }

    function initFloorFn(unitId) {
        var floorList;
        common.sendSyncRequest("/estate/floor/showFloorList", 'get', {unitId: unitId,current : 1,}, function (result) {
            floorList = result.data.records;
        });
        return floorList;
    }

    //小区和单元赋值
    (function() {
        if (pageData.parentId != null){
            switch (pageData.flag) {
                case '2':
                    $.ajax({
                        type: 'GET',
                        url: '/estate/residential/findResidentialById/'+pageData.parentId,
                        success: function (result) {
                            residentialSelect.update({disabled:true,data:[result.data]}).setValue([pageData.parentId]);
                            unitSelect.update({disabled: false });
                        }
                    });
                    break;
                case '4':
                    $.ajax({
                        type: 'GET',
                        url: '/estate/unit/findUnitById/'+pageData.parentId,
                        success: function (result) {
                            unitSelect.update({disabled:true,data:[result.data]}).setValue([pageData.parentId]);
                            $.ajax({
                                type: 'GET',
                                url: '/estate/residential/findResidentialById/'+result.data.residentialId,
                                success: function (result2) {
                                    residentialSelect.update({disabled:true,data : [result2.data]}).setValue([result.data.residentialId])
                                }
                            });
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    })();

});