/*
 * title: unit-manage
 *
*/
layui.extend({
    common    :   'js/common',
}).use(['tree', 'jquery','layer','common','form','element'], function () {

    var tree = layui.tree;
    //  弹窗插件
    var layer = layui.layer;
    //  Jquery插件
    var $ = layui.jquery;
    //  引入公共模块
    var common = layui.common;
    //  引入表单
    var form = layui.form;

    // 页面数据
    var residentialId = $('#residentialId').val();
    var residentialName = $('#residentialName').val();

    var data = getBuildingList({
        id      :   residentialId,
        title   :   residentialName,
        spread  :   true,
        level   :   1,
        type    :   1,
        edit    :   []
    });

    //开启节点操作图标
    var mytree = tree.render({
        elem: '#tree',
        showLine: true, //是否开启连接线。默认 true，若设为 false，则节点左侧出现三角图标。
        accordion: false, //是否开启手风琴模式，默认 false
        onlyIconControl: false, //是否仅允许节点左侧图标控制展开收缩。默认 false
        onlyIconControl: true,
        isJump: false, //是否允许点击节点时弹出新窗口跳转。默认 false
        limitNodeAddLevel: [5, 6],
        // limitNodeUpdateLevel: [1],
        limitNodeDelLevel: [1],
        data: [data],
        edit: ['add'], //操作节点的图标
        operate: function(obj){
            var type = obj.type; //得到操作类型：add、edit、del
            var data = obj.data; //得到当前节点的数据
            var elem = obj.elem; //得到当前节点元素

            //Ajax 操作
            var id = data.id; //得到节点索引
            if(type === 'add'){ //增加节点
                //返回 key 值
                operateAdd(obj);
                return false;
            } else if(type === 'update'){ //修改节点
                operateUpdate(obj);
                // console.log(elem.find('.layui-tree-txt').html()); //得到修改后的内容
                // var textValue = elem.find('.layui-tree-txt').html();
            } else if(type === 'del'){ //删除节点
                operateDel(obj);
            };

        },
        onspread: function (obj) {
            treeOnspread(obj);
        }
        ,click: function(obj){
            // layer.msg(JSON.stringify(obj.data));
            treeClickFn(obj);
        }
    });

    // $('#tree .layui-tree-entry:first').click();
    // 根节点模拟点击，加载右列表
    $('#tree .layui-tree-entry:first .layui-tree-main .layui-tree-txt').click();

    // 新增操作
    function operateAdd(obj) {
        var data = obj.data;
        var type = data.type;
        var layerIndex;

        layer.prompt({
            formType: 0, //文本框
            title: getLabelWithType(type)
        }, function(value, index, elem){
            // layer.close(index);
            layerIndex = index;

            // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
            switch (type) {
                case 1:
                    // 小区->楼栋新增
                    buidingAdd(value, data, callbackFn);
                    break;
                case 2:
                    // 楼栋->单元新增
                    unitAdd(value, data, callbackFn);
                    break;
                case 3:
                    // 单元->楼层新增
                    floorAdd(value, data, callbackFn);
                    break;
                case 4:
                    // 楼层->房间新增
                    roomAdd(value, data, callbackFn);
                    break;
                case 5:
                    // 房间->住户新增
                    break;
            }
        });

        // 添加回调
        function callbackFn(result) {
            obj.state = 'open';
            if(result.code == 200){
                layer.msg("添加成功",{
                    time: 500
                    ,shade : [0.1 , '#000' , true]
                },function () {
                    //关闭弹窗层
                    layer.close(layerIndex);
                    // 树刷新
                    type == 1 ? document.location.reload() : treeOnspread(obj, true);
                });
            }else {//添加失败
                layer.msg("添加失败");
            }
        }
    }


    // 楼栋添加
    function buidingAdd(name, data, callbackFn){
        var params = {
            name: name,
            residentialId: data.id
        };
        common.sendAsyncRequest("/estate/building/addBuilding",'POST', params, callbackFn);
    }

    // 单元添加
    function unitAdd(name, data, callbackFn){
        var params = {
            name: name,
            buildingId: data.id
        };
        common.sendAsyncRequest("/estate/unit/addUnit",'POST', params, callbackFn);
    }

    // 楼层添加
    function floorAdd(name, data, callbackFn){
        var params = {
            name: name,
            unitId: data.id
        };
        common.sendAsyncRequest("/estate/floor/addFloor",'POST', params, callbackFn);
    }

    // 房屋添加
    function roomAdd(name, data, callbackFn){
        var params = {
            name: name,
            floorId: data.id
        };
        common.sendAsyncRequest("/estate/room/addRoom",'POST', params, callbackFn);
    }

    // 批量弹窗
    form.on('submit(add_batch)', function(data){
        // debugger
        // common.sendAsyncRequest("/estate/residential/updateResidential",'POST',data.field,callbackFn);


        // common.openDefaultIframe({
        //     title: residentialName + '-批量添加',
        //     content:  '/estate/building/addBatchView/' + residentialId
        // });

        layer.open({
            //  0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
            type    :   2,
            //  宽高
            area    :   ['60%','60%'],
            //  弹窗标题
            title   :   residentialName + '-批量添加',
            //  打开内容
            content :   '/estate/building/addBatchView/' + residentialId,
        });


    });


    // 根据类型，获取添加文本提示
    function getLabelWithType(type) {
        // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
        switch (type) {
            case 1:
                // 小区->楼栋新增
                return '请输入楼栋名称';
                break;
            case 2:
                // 楼栋->单元新增
                return '请输入单元名称';
                break;
            case 3:
                // 单元->楼层新增
                return '请输入楼层名称';
                break;
            case 4:
                // 楼层->房间新增
                return '请输入房屋名称';
                break;
            case 5:
                // 房间->住户新增
                return '请输入住户名称';
                break;
        }
    }



    //更新操作
    function operateUpdate(obj) {
        var data = obj.data;
        var type = data.type;
        var layerIndex;

        // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
        switch (type) {
            case 1:
                // 小区更新
                residentialUpdate( data, callbackFn);
                break;
            case 2:
                // 楼栋更新
                buidingUpdate(data, callbackFn);
                break;
            case 3:
                // 单元更新
                unitUpdate(data, callbackFn);
                break;
            case 4:
                // 楼层更新
                floorUpdate(data, callbackFn);
                break;
            case 5:
                // 房间更新
                roomUpdate(data, callbackFn);
                break;
            case 5:
                // 住户更新
                userUpdate(data, callbackFn);
                break;
        }

        // 添加回调
        function callbackFn(result) {
            obj.state = 'open';
            if(result.code == 200){
                layer.msg("更新成功",{
                    time: 500
                    ,shade : [0.1 , '#000' , true]
                },function () {
                    //关闭弹窗层
                    layer.close(layerIndex);
                    // 树刷新
                    // type == 1 ? document.location.reload() : treeOnspread(obj, true);
                });
            }else {//添加失败
                layer.msg("添加失败");
            }
        }
    }

    // 小区更新
    function residentialUpdate(data, callbackFn) {
        var params = {
            id  : data.id,
            name: data.title
        }
        common.sendAsyncRequest("/estate/residential/updateResidentialName",'POST', params, callbackFn);
    }
    // 楼栋更新
    function buidingUpdate(data, callbackFn) {
    }
    // 单元更新
    function unitUpdate(data, callbackFn) {
    }
    // 楼层更新
    function floorUpdate(data, callbackFn) {
    }
    // 房屋更新
    function roomUpdate(data, callbackFn) {
    }


    // 删除操作
    function operateDel(obj) {
    }

    //树点击事件
    function treeClickFn(obj){
        var data = obj.data;
        // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
        var type = data.type;
        var url = '';
        switch (type) {
            case 1:
                //小区->楼栋列表
                url = '/estate/building/index' + '/' + data.id;
                break;
            case 2:
                //楼栋->单元列表
                url = '/estate/unit/index' + '/' + data.id;
                break;
            case 3:
                //单元->楼层
                url = '/estate/floor/index' + '/' + data.id;
                break;
            case 4:
                //楼层->房间
                url = '/estate/room/index' + '/' + data.id;
                break;
            case 5:
                //房间->住户
                url = '/estate/user/index' + '/' + data.id;
                break;
            default:
                break;
        }
        !!url && $('#rightFrame').attr('src', url);
    }

    function treeOnspread(obj, reload){
        var childrenData = [];
        var parentData = obj.data;
        if (obj.state == 'open'){
            if ((parentData.children.length > 0 && Object.keys(parentData.children[0]).length > 0) && !reload){
                parentData.spread = true;
            }else{
                // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
                switch (parentData.type) {
                    case 1:
                        break;
                    case 2:
                        childrenData = getUnitList(parentData);
                        break;
                    case 3:
                        childrenData = getFloorList(parentData);
                        break;
                    case 4:
                        childrenData = getRoomList(parentData);
                        break;
                    case 5:
                        childrenData = getUserList(parentData);
                        break;
                    default:
                        break;

                }
                childrenData.spread = true;
                mytree.reload(childrenData);
            }
        }else{
            parentData.spread = false;
        }
    }

    //  查询机构方法
    function getBuildingList(parent){
        var data = {
            residentialId         :   parent.id
        };
        var level = parent.level ? parent.level + 1 : 1;
        var successFn;
        var type = 2; // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
        successFn = function (result) {
            var dataList = castDataForma(result.list, type, level);
            parent.children = dataList;
        };

        $.ajax({
            url     :   '/estate/residential/getSourceByPid',
            // url     :   '/permissions/org/getOrgTreeByPid',
            data    :   data,
            type    :   'GET',
            async   :   false,
            success :   function (result) {
                successFn(result);
            }
        });
        parent.spread = true;
        return parent;
    };

    function getUnitList(parent) {
        var data = {
            buildingId     :   parent.id
        };
        var level = parent.level ? parent.level + 1 : 1;
        var successFn;
        var type = 3; // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
        successFn = function (result) {
            var dataList = castDataForma(result.list, type, level);
            parent.children = dataList;
        };

        $.ajax({
            url     :   '/estate/residential/getUnitsByPid',
            data    :   data,
            type    :   'GET',
            async   :   false,
            success :   function (result) {
                successFn(result);
            }
        });
        parent.spread = true;
        return parent;
    }

    function getFloorList(parent) {
        // /getFloorsByPid
        var data = {
            unitId     :   parent.id
        };
        var level = parent.level ? parent.level + 1 : 1;
        var successFn;
        var type = 4; // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
        successFn = function (result) {
            var dataList = castDataForma(result.list, type, level);
            parent.children = dataList;
        };

        $.ajax({
            url     :   '/estate/residential/getFloorsByPid',
            data    :   data,
            type    :   'GET',
            async   :   false,
            success :   function (result) {
                successFn(result);
            }
        });
        parent.spread = true;
        return parent;
    }

    function getRoomList(parent) {
        // /getFloorsByPid
        var data = {
            floorId     :   parent.id
        };
        var successFn;
        var level = parent.level ? parent.level + 1 : 1;
        var type = 5; // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
        successFn = function (result) {
            var dataList = castDataForma(result.data, type, level);
            parent.children = dataList;
        };

        $.ajax({
            url     :   '/estate/residential/getRoomsByPid',
            data    :   data,
            type    :   'GET',
            async   :   false,
            success :   function (result) {
                successFn(result);
            }
        });
        parent.spread = true;
        return parent;
    }

    function getUserList(parent) {
        // /getFloorsByPid
        var data = {
            roomId     :   parent.id
        };
        var successFn;
        var level = parent.level ? parent.level + 1 : 1;
        var type = 6; // {1: 小区， 2：楼栋，3：单元，4：楼层，5：房间}
        successFn = function (result) {
            var dataList = castDataForma(result.data, type, level);
            parent.children = dataList;
        };

        $.ajax({
            url     :   '/estate/residential/getUsersByPid',
            data    :   data,
            type    :   'GET',
            async   :   false,
            success :   function (result) {
                successFn(result);
            }
        });
        parent.spread = true;
        return parent;
    }

    //  类型转换
    function castDataForma(entityList, type, level) {
        var list;
        var children = [{}];
        if (type == 6){
            children = [];
        }
        entityList.forEach(item => {
            item.title = item.name;
            item.children = children;
            item.type = type;
            item.level = level;
        })
        return entityList;
    };

});