layui.extend({
    common    :   'js/common',
    xmSelect    :   'layui/dist/xm-select',
}).use(['jquery','layer','common','laydate','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;
    let laydate = layui.laydate;
    laydate.render({
        elem: '#dateSelector' ,
        type: 'month'
    });

    /* -----------表格数据*/
    // let table = layui.table;
    // table.render({
    //     elem: '#itemTable'
    //     ,url: '/bills/manage/list'
    //     ,page: true
    //     ,cols: [[
    //         {field: 'itemName', title: '缴费项'}
    //         ,{field: 'itemFee', title: '缴费金额'}
    //         ,{field: 'itemDesc', title: '备注'}
    //         ,{title: '操作'}
    //     ]]
    //     ,response: {
    //         statusCode: 200
    //     }
    //     ,parseData: (res)=>{
    //         console.log(res);
    //         return {
    //             "code": res.code,
    //             "msg": res.msg,
    //             "count": res.data.total,
    //             "data": res.list
    //         }
    //     }
    // });

    var formdata = {
        orgPosition:'',
        agencyName:'',
        residentialName:'',
        buildingName:'',
        unitName:'',
        floorName: '',
        roomName:'',
    };
    //  页面数据
    var pageData = {
        billsItemList: [],

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

        agencyNode:$('#agency_id'),
        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 '名称首尾不能出现下划线\'_\'';
            }
        },
        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_add)', function(data){
        console.log(data.field,'data.field表单数据');
        console.log(formdata,'formdata表单数据');
        var objs = Object.assign(data.field,formdata);
        console.log(objs,'objs结合对象数据');
        // common.timer($('button[lay-filter="submit_add"]'));
        // common.sendSyncRequest("/bills/manage/add", 'POST', data.field, callbackFn);
        $.ajax({
            url:"/bills/manage/add",
            type:'POST',
            async:false,
            contentType:'application/json;charset=UTF-8',
            data:JSON.stringify(data.field),
            dataType:'text',
            success:function (data) {
                console.log(data,'result.data值');
                if(data!=null){
                    layer.msg('添加成功！',{
                      icon:1,
                      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('添加失败！',{
                        icon:2,
                        time:500,
                        shade : [0.1 , '#000' , true]
                    },function () {
                        //获取当前弹窗出层的名字
                        var index = parent.layer.getFrameIndex(window.name);
                        //关闭弹窗层
                        parent.layer.close(index);
                        // 父页面刷新
                        parent.location.reload();
                    });
                }
            },
            error:function () {
                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 queryBeginDate,queryEndDate;
    // var queryTableFn=function(){
    //     //执行重载
    //     table.reload('billsTable', {
    //         page: {
    //             curr: 1 //重新从第 1 页开始
    //         }
    //     });
    // };

    //社区查询下拉列表
    /*var agencySelect = xmSelect.render({
        el: '#agency_id',
        name: 'agencyId',
        layVerify: 'required',
        radio: true,
        prop: {
            name: 'agencyName',
            value: 'id',
        },
        clickClose: true,
        paging: true,
        pageRemote: true,
        filterable: true,
        remoteMethod: function (val, cb, show,pageIndex) {
            $.ajax({
                type: 'GET',
                url: '/estate/agency/showAgencyList',
                data: {
                    agencyName : val,
                    current : pageIndex,
                },
                success: function (result) {
                    cb(result.list,10);
                },
                error: function () {
                    cb([],0);
                }
            });
        },
        //监听选择
        on: function (data) {
            console.log(data,'社区data');
            var change = data.change;
            if (change.length > 0) {
                formdata.agencyName = change[0].agencyName;
                console.log(formdata.agencyName,'社区名字');
                residentialSelect.update({data:initResidentialFn(change[0].id),disabled: false}).setValue([]);
                buildingSelect.update({disabled: true }).setValue([]);
                unitSelect.update({disabled: true }).setValue([]);
                floorSelect.update({disabled: true }).setValue([]);
                roomSelect.update({disabled: true }).setValue([]);
            }
            if (!data.isAdd) {
                residentialSelect.update({disabled: true }).setValue([]);
                unitSelect.update({disabled: true }).setValue([]);
                buildingSelect.update({disabled: true }).setValue([]);
                floorSelect.update({disabled: true }).setValue([]);
                roomSelect.update({disabled: true }).setValue([]);
            }
        },
        //显示方式
        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) {
                formdata.residentialName = change[0].name;
                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) {
                formdata.buildingName = change[0].name;
                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) {
                formdata.unitName = change[0].name;
                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) {
            console.log(data);
            var change = data.change;
            if (change.length > 0) {
                formdata.roomName = change[0].name;
                //获取房间orgPosition
                formdata.orgPosition = change[0].orgPosition;
            }
            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 '1':
                    $.ajax({
                        type: 'GET',
                        url: '/estate/agency/findAgencyById/'+pageData.parentId,
                        success: function (result) {
                            agencySelect.update({disabled:true,data:[result.data]}).setValue([pageData.parentId]);
                            residentialSelect.update({disabled:false});
                            unitSelect.update({disabled: false });
                        }
                    });
                    break;
                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;
                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;
            }
        }
    })();
});