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

    //定义加载层id
    var loadId;
    //图片服务器地址
    var fastDfsServer = $('#fastDfsServer').val();

    //  页面数据
    var pageData = {

        residentialList : {},
        unitList : {},
        roomList : {},

        residentialNode : $('#residential_id'),
        unitNode : $('#unit_id'),
        roomNode : $('#room_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 '名称首尾不能出现下划线\'_\'';
            }
            if(/^\d+\d+\d$/.test(value)){
                return '名称不能全为数字';
            }
        },
        length : function (value) {
            if (value.length <2 || value.length > 20){
                return  '名称只能输入2-20个字符!'
            }
        },
        cardNum : function (value) {
            if (value != ''){
                if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)){
                    return  '请输入正确的身份证号码!'
                }
            }
        },
        phoneNum : function (value) {
            if(value != ''){
                // if(!/^1[3|4|5|7|8]\d{9}$/.test(value)){
                if(value.length != 11){
                    return '请输入正确的手机号码!';
                }
            }
        },
    });

    //监听提交
    form.on('submit(submit_button)', function(data){
        common.timer($('button[lay-filter="submit_button"]'));
        var type = data.field.type;
        if('0' == type){
            var tel = data.field.tel;
            if(tel == null || tel == '' ){
                layer.msg("添加业主，手机号码必填！");
                return;
            }
            var nationality = data.field.nationality;
            var passportImgUri = data.field.passportImgUri;
            var entryImgUri = data.field.entryImgUri;
            if('3' == nationality && (passportImgUri == null || passportImgUri == ''|| entryImgUri == null || entryImgUri== '' ) ){
                layer.msg("添加海外业主，护照图片及入境图片必填！");
                return;
            }
            //校验长度，类型
            if(data.field.idCard.length > 18) {
                layer.msg("请核实身份证号是否正确，再重新输入");
                return ;
            }
        }
        if (data.field.idCard == '' && data.field.tel == ''){
            layer.msg("请输入手机号或者证件号码的其中一个。");
            return ;
        }
        common.sendAsyncRequest("/estate/user/addUser",'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);
    });

    //  绑定所属机构绑定事件
    form.on('select(room_event)', function(data){
        $('#type_id').next().find('dl dd').eq(0).click();
    });

    //  选定证件类型
    /*form.on('select(nationality_event)', function (data) {
        if (data.value == '0') {
            $('#card_name').text("身份证");
            $('#birth_place').show();
            $('#passport_pic').hide();
            $('#entry_pic').hide();
        } else if (data.value == '1') {
            $('#card_name').text("港澳居民往来内地通行证");
            $('#birth_place').hide();
            $('#passport_pic').hide();
            $('#entry_pic').hide();
        } else if (data.value == '2') {
            $('#card_name').text("台湾居民往来大陆通行证");
            $('#birth_place').hide();
            $('#passport_pic').hide();
            $('#entry_pic').hide();
        } else {
            $('#card_name').text("护照");
            $('#birth_place').hide();
            $('#passport_pic').show();
            $('#entry_pic').show();
        }
    });*/

    //多图片上传
    upload.render({
        elem: '#passport_upload'
        ,url: '/common/file/upload'
        ,exts: 'jpg|png|jpeg'
        ,accept: 'images' //图片
        ,before: function(obj){
            $('#passport_upload').prev('.avatar').remove();
            //开启加载动画
           loadId = layer.msg('图片上传中', {
                icon: 16,
                shade: 0.4,
                time:false //取消自动关闭
            });
        }
        ,done: function(res){  //上传完毕
            //关闭加载动画
            layer.close(loadId);
            if(res.code=="200"){//上传成功
                 $('#passport_upload').before('<div class="avatar" style="display: inline-block;">' +
                     '<input type="hidden" name="passportImgUri" value="'+res.data.fullPath+'" />' +
                     '<img src="'+fastDfsServer+ res.data.fullPath +'" class="layui-upload-img" />' +
                     '</div>');
            }else{
                layer.msg("图片上传失败");
            }
        }
        ,error: function(){
            //关闭加载动画
            layer.close(loadId);
            layer.msg("图片上传失败");
        }
    });

    //多图片上传
    upload.render({
        elem: '#entry_upload'
        ,url: '/common/file/upload'
        ,exts: 'jpg|png|jpeg'
        ,accept: 'images' //图片
        ,before: function(obj){
            $('#entry_upload').prev('.avatar').remove();
            //开启加载动画
            loadId = layer.msg('图片上传中', {
                icon: 16,
                shade: 0.4,
                time:false //取消自动关闭
            });
        }
        ,done: function(res){  //上传完毕
            //关闭加载动画
            layer.close(loadId);
            if(res.code=="200"){//上传成功
                $('#entry_upload').before('<div class="avatar" style="display: inline-block;">' +
                    '<input type="hidden" name="entryImgUri" value="'+res.data.fullPath+'" />' +
                    '<img src="'+fastDfsServer+ res.data.fullPath +'" class="layui-upload-img" />' +
                    '</div>');
            }else{
                layer.msg("图片上传失败");
            }
        }
        ,error: function(){
            //关闭加载动画
            layer.close(loadId);
            layer.msg("图片上传失败");
        }
    });

    //根据树形赋值
    var treeValue = function(){
        switch (pageData.treeFlag) {
            case "2"://小区
                if(null == pageData.selectTreeId || ""== pageData.selectTreeId){
                    pageData.residentialNode.next().find('dl dd').eq(0).click();
                }else{
                    var select = 'dd[lay-value=' +  pageData.selectTreeId + ']';
                    pageData.residentialNode.next().find('dl').find(select).click();
                }
                break;
            case "4"://单元
                pageData.unitList.forEach(function (item) {
                    if (item.id == pageData.selectTreeId){
                        //小区赋值
                        var residentialSelect = 'dd[lay-value=' +  item.residentialId + ']';
                        pageData.residentialNode.next().find('dl').find(residentialSelect).click();
                        //单元赋值
                        var unitSelect = 'dd[lay-value=' +  item.id + ']';
                        pageData.unitNode.next().find('dl').find(unitSelect).click();
                    }
                });
                break;
            case "5"://房间
                pageData.roomList.forEach(function (item) {
                    if (item.id == pageData.selectTreeId){
                        //小区赋值
                        var residentialSelect = 'dd[lay-value=' +  item.residentialId + ']';
                        pageData.residentialNode.next().find('dl').find(residentialSelect).click();
                        //单元赋值
                        var unitSelect = 'dd[lay-value=' +  item.unitId + ']';
                        pageData.unitNode.next().find('dl').find(unitSelect).click();
                        //房间赋值
                        var roomSelect = 'dd[lay-value=' +  item.id + ']';
                        pageData.roomNode.next().find('dl').find(roomSelect).click();
                    }
                });
                break;
        }
    };

    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 (const key in url[i]) {
                    if (key == name) {
                        nameres = url[i][key];
                    }
                }
            }
        } else {
            nameres = url;
        }
        // 返回结果
        return nameres;
    }
    $.ajax({
        type: 'GET',
        url: '/permissions/dict/getByCode/sex',
        success: function (result) {
            sexDic.update({data: result.list})
        },
    });
    var sexDic = xmSelect.render({
        el: '#sex_dic',
        name: 'sex',
        layVerify: 'required',
        radio: true,
        clickClose: true,
        prop: {
            name: 'dictValue',
            value: 'dictKey',
        },
        on: function (data) {},
        model: {
            label: {
                type: 'text',
                text: {
                    left: '',
                    right: '',
                    separator: ', ',
                },
            }
        },
    });
    $.ajax({
        type: 'GET',
        url: '/permissions/dict/getByCode/userType',
        success: function (result) {
            userTypeDic.update({data:result.list})
        },
    });
    var userTypeDic = xmSelect.render({
        el: '#type',
        name: 'type',
        layVerify: 'required',
        radio: true,
        clickClose: true,
        prop: {
            name: 'dictValue',
            value: 'dictKey',
        },
        on: function (data) {
        },
        model: {
            label: {
                type: 'text',
                text: {
                    left: '',
                    right: '',
                    separator: ', ',
                },
            }
        },
    });

    //小区查询下拉列表
    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/getListByLikeName',
                data: {
                    name : val,
                    current : pageIndex,
                },
                success: function (result) {
                    cb(result.list,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([]);
                roomSelect.update({disabled: true }).setValue([]);
            }
            if (!data.isAdd) {
                unitSelect.update({disabled: true }).setValue([]);
                buildingSelect.update({disabled: true }).setValue([]);
                roomSelect.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) {
            $.ajax({
                type: 'GET',
                url: '/estate/building/getListByLikeName',
                data: {
                    name : val,
                    residentialId : residentialSelect.getValue('valueStr'),
                },
                success: function (result) {
                    cb(result.list);
                },
                error: function () {
                    cb([]);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                unitSelect.update({data : initUnitFn(change[0].id),disabled: false }).setValue([]);
                roomSelect.update({disabled:true}).setValue([])
            }
            if (!data.isAdd) {
                unitSelect.update({disabled: true }).setValue([]);
                roomSelect.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,
        filterable: true,
        remoteMethod: function (val, cb, show) {
            $.ajax({
                type: 'GET',
                url: '/estate/unit/getListByLikeName',
                data: {
                    name : val,
                    buildingId : buildingSelect.getValue('valueStr'),
                },
                success: function (result) {
                    cb(result.list);
                },
                error: function () {
                    cb([]);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
                roomSelect.update({data : initRoomFn(change[0].id),disabled: false }).setValue([]);
            }
            if (!data.isAdd) {
                roomSelect.update({disabled:true}).setValue([])
            }
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });

    //房间查询下拉列表
    var roomSelect = xmSelect.render({
        el: '#room_id',
        name: 'roomId',
        layVerify: 'required',
        disabled: true,
        radio: true,
        prop: {
            name: 'name',
            value: 'id',
        },
        clickClose: true,
        filterable: true,
        remoteSearch: true,
        remoteMethod: function (val, cb, show) {
            $.ajax({
                type: 'GET',
                url: '/estate/room/getListByLikeName',
                data: {
                    name : val,
                    unitId : unitSelect.getValue('valueStr'),
                    isSelect : true
                },
                success: function (result) {
                    cb(result.list);
                },
                error: function () {
                    cb([]);
                }
            });
        },
        //监听选择
        on: function (data) {
            var change = data.change;
            if (change.length > 0) {
            }
            if (!data.isAdd) {
            }
        },
        //显示方式
        model: {
            label: {
                type: 'text',
                text: {
                    //左边拼接的字符
                    left: '',
                    //右边拼接的字符
                    right: '',
                    //中间的分隔符
                    separator: ', ',
                },
            }
        },
    });
    function initBuildFn(residentialId) {
        var buildingList;
        common.sendSyncRequest("/estate/building/getListByLikeName", 'get', {residentialId: residentialId,current : 1,isSelect : true}, function (result) {
            buildingList = result.list;
        });
        return buildingList;
    }
    function initUnitFn(buildingId) {
        var unitList;
        common.sendSyncRequest("/estate/unit/getListByLikeName", 'get', {
            buildingId: buildingId,
            isSelect: true
        }, function (result) {
            unitList = result.list;
        });
        return unitList;
    }
    function initRoomFn(unitId) {
        var roomList;
        common.sendSyncRequest("/estate/room/getListByLikeName", 'get', {
            unitId: unitId,
            isSelect: true
        }, function (result) {
            roomList = result.list;
        });
        return roomList;
    }

    //小区和单元赋值
    (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]);
                            roomSelect.update({disabled : false});
                            $.ajax({
                                type: 'GET',
                                url: '/estate/residential/findResidentialById/'+result.data.residentialId,
                                success: function (result1) {
                                    residentialSelect.update({
                                        disabled: true,
                                        data: [result1.data]
                                    }).setValue([result.data.residentialId])
                                }
                            });
                        }
                    });
                    break;
                case '5':
                    $.ajax({
                        type: 'GET',
                        url: '/estate/room/findRoomById/'+pageData.parentId,
                        success: function (result) {
                            roomSelect.update({disabled:true,data:[result.data]}).setValue([pageData.parentId]);
                            $.ajax({
                                type: 'GET',
                                url: '/estate/unit/findUnitById/'+result.data.unitId,
                                success: function (result1) {
                                    unitSelect.update({
                                        disabled: true,
                                        data: [result1.data]
                                    }).setValue([result.data.unitId]);
                                }
                            });
                            $.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;
            }
        }
    })();

});