/*
 * title: org-tree
 * @author 王飞腾
 * date: 2018/12/2
*/
layui.define(['jquery','tree'],function(exports) {
    var $ = layui.jquery;
    //  页面节点
    var $node = {
        //  路径
        pathOrg     :   $('#path-org'),
        pathEstate  :   $('#path-estate'),
        pathAd      :   $('#path-ad'),
        pathAgency  :   $('#path-agency'),
        pathPark  :   $('#path-park'),
        //  下拉树
        treeOrg     :   $('#per-tree-org'),
        treeEstate  :   $('#per-tree-estate'),
        treeAd      :   $('#per-tree-ad'),
        treeAgency  :   $('#per-tree-agency'),
        treePark  :   $('#per-tree-park'),
        searchInput :   $('#search'),
    };

    //  类型转换
    var castDataForma = function(entityList) {
        var list = [];
        if (entityList instanceof Array) {
            entityList.forEach(function (entity) {
                //  递归
                var selectType;//{1：机构，2：小区，，3：社区机构，4：单元，5：房间}
                if (!entity.flag){
                    if (Object.keys(entity).join().indexOf('isAssign') != -1 && Object.keys(entity).join().indexOf('unitNumber') != -1){
                        selectType = 2;
                    }
                    if (Object.keys(entity).join().indexOf('isAssign') == -1 && Object.keys(entity).join().indexOf('unitNumber') != -1){
                        selectType = 4;
                    }
                    if (Object.keys(entity).join().indexOf('houseNumber') != -1){
                        selectType = 5;
                    }
                }else{
                    selectType = entity.flag;
                }
                var title = entity.name;
                switch (entity['flag']) {
                    //  机构
                    case 1:
                        title = '<i class="layui-icon layui-icon-group"></i>&nbsp;' + title;
                        break;
                    //  小区
                    case 2:
                        title = '<i class="layui-icon layui-icon-home"></i>&nbsp;' + title;
                        break;
                    //  社区机构
                    case 3:
                        title = '<i class="layui-icon layui-icon-group"></i>&nbsp;' + title;
                        break;
                    default: break;
                }
                var subList = castDataForma(entity.subList);
                var item = {
                    id: entity.id,
                    name: title,
                    spread: true,
                    // flag: selectType,
                    flag: entity.flag,
                    type : entity.orgType,
                    children: subList
                };
                //  添加元素
                list.push(item);
            });
        }
        return list;
    };

    //  查询机构方法
    var getOrgList = function(parent){
        var data = {
            pid         :   parent.id
        };
        var successFn;
        if (parent.name){
            data.excludeOwn = 1;
            successFn = function (result) {
                parent.children = castDataForma(result.list)
            };
        }else {
            data.excludeOwn = 2;
            successFn = function (result) {
                var dataList = castDataForma(result.list);
                parent = dataList[0];
            };
        }
        if(parent.isShowFlag){
            data.isShowFlag = parent.isShowFlag;
        }
        $.ajax({
            url     :   '/permissions/org/getSubListByPid',
            // url     :   '/permissions/org/getOrgTreeByPid',
            data    :   data,
            type    :   'GET',
            async   :   false,
            success :   function (result) {
                successFn(result);
            }
        });
        return parent;
    };

    var unitTreeFn = function (parent) {
        var data = {
            orgPid         :   parent.id
        };
        $.ajax({
            url     :   '/estate/unit/findListByPid',
            data    :   data,
            type    :   'GET',
            async   :   false,
            success :   function (result) {
                result.list.forEach(function(entity){
                    parent.children.push({
                        id      :   entity.id,
                        name    :   entity.name,
                        spread  :   true,
                        flag    :   4,
                        children  : []
                    });
                });
            }
        });
        return parent;
    };

    var roomTreeFn = function (parent) {
        var data = {
            unitId         :   parent.id
        };
        $.ajax({
            url     :   '/estate/room/findListByPid',
            data    :   data,
            type    :   'GET',
            async   :   false,
            success :   function (result) {
                result.list.forEach(function(entity){
                    parent.children.push({
                        id      :   entity.id,
                        name    :   entity.name,
                        spread  :   true,
                        flag    :   5,
                        children  : []
                    });
                });
            }
        });
        return parent;
    };

    //搜索框事件绑定
    $(document).on("keyup", function(value){
        var searchValue = $node.searchInput.val();
        if (document.getElementById('per-tree-org').hidden == false){
            searchValueChange(searchValue, 'per-tree-org');
        }else if(document.getElementById('per-tree-estate').hidden == false){
            searchValueChange(searchValue, 'per-tree-estate');
        }else if(document.getElementById('per-tree-ad').hidden == false){
            searchValueChange(searchValue, 'per-tree-ad');
        }else if(document.getElementById('per-tree-agency').hidden == false){
            searchValueChange(searchValue, 'per-tree-agency');
        }else if(document.getElementById('per-tree-park').hidden == false){
            searchValueChange(searchValue, 'per-tree-park');
        }

    });

    //搜索框值改变事件
    function searchValueChange(value, elementId){
        value = value.trim();
        var itemArr = $("#" + elementId + " .layui-show li");
        if (itemArr && itemArr.length > 0){
            itemArr.each(function(index, item){
                if (!value){
                    if (index < 20){
                        $(item).show();
                    }else{
                        $(item).hide();
                    }
                }else{
                    var obj = $(item).find("cite");
                    if (obj && obj.text() && obj.text().indexOf(value) != -1){
                        $(item).show();
                    }else {
                        $(item).hide();
                    }
                }
            })
        }
    }

    //只显示前20条数据，其他隐藏，搜索的时候，再把匹配上的显示出来
    function initShow(){
        var orgArr = $("#per-tree-org .layui-show li");
        var estArr = $("#per-tree-estate .layui-show li");
        var adArr = $("#per-tree-ad .layui-show li");
        var agencyArr = $("#per-tree-agency .layui-show li");
        var parkArr = $("#per-tree-park .layui-show li");

        if (orgArr && orgArr.length > 0){
            orgArr.each(function(index, item){
                if (index < 20){
                    $(item).show();
                }else{
                    $(item).hide();
                }
                $(item).prop('title', $(item).find('cite').text());
            })
        }
        if (estArr && estArr.length > 0){
            estArr.each(function(index, item){
                if (index < 20){
                    $(item).show();
                }else{
                    $(item).hide();
                }
                $(item).prop('title', $(item).find('cite').text());
            })
        }
        if (adArr && adArr.length > 0){
            adArr.each(function(index, item){
                if (index < 20){
                    $(item).show();
                }else{
                    $(item).hide();
                }
                $(item).prop('title', $(item).find('cite').text());
            })
        }
        if (agencyArr && agencyArr.length > 0){
            agencyArr.each(function(index, item){
                if (index < 20){
                    $(item).show();
                }else{
                    $(item).hide();
                }
                $(item).prop('title', $(item).find('cite').text());
            })
        }
        if (parkArr && parkArr.length > 0){
            parkArr.each(function(index, item){
                if (index < 20){
                    $(item).show();
                }else{
                    $(item).hide();
                }
                $(item).prop('title', $(item).find('cite').text());
            })
        }

    }

    $(document).on('click','#org, #estate, #ad, #agency, #park',function(){
        var tabArr = ['org','estate','ad','agency','park'];
        var tab = this.id;
        //去掉其他tab激活状态
        document.querySelectorAll('.org-tab').forEach(function(item){
            item.className = item.className.replace('org-active','').trim();
        });
        //给自己添加激活状态
        this.className += ' org-active';
        //显示对应的树形
        tabArr.forEach(function(item){
            document.getElementById('per-tree-' + item).hidden = item != tab;
            document.getElementById('path-' + item).hidden = item != tab;
        })
    });

    //  暴露接口
    var orgTree = function(options){
        //  加载树
        var loadTreeList = function(parent,isInit){
            var aList;
            if (document.getElementById('per-tree-org').hidden == false){
                aList = $node.pathOrg.find('a');
            }
            if(document.getElementById('per-tree-estate').hidden == false){
                aList = $node.pathEstate.find('a');
            }
            if(document.getElementById('per-tree-ad').hidden == false){
                aList = $node.pathAd.find('a');
            }
            if(document.getElementById('per-tree-agency').hidden == false){
                aList = $node.pathAgency.find('a');
            }
            if(document.getElementById('per-tree-park').hidden == false){
                aList = $node.pathPark.find('a');
            }
            //  获取最后一个a标签
            var lastA = aList.eq(aList.length - 1);
            if (lastA){
                if (parseInt(lastA.attr('data')) === parent.id){
                    return;
                }
            }
            //截至级别
            if(options.isShowFlag){
                parent.isShowFlag = options.isShowFlag;
            }
            //  根据数据的类型调用不同的方法
            var result = [];
            //1 机构 2 小区 3社区机构  4 单元 5 房间
            if(parent.flag){
                if(parent.flag === 1){ //父节点为机构，下级可能为小区或者机构
                    result = getOrgList(parent,options.common);
                }else if(parent.flag === 2){ //父节点为小区，下级可能为社区机构或者单元
                    if(parent.isShowFlag !== 3){
                        parent = getOrgList(parent,options.common);
                        if(parent.isShowFlag !== 4) {
                            result = unitTreeFn(parent);
                        }else{
                            result = getOrgList(parent,options.common);
                        }
                    }
                }else if(parent.flag === 3){ //父节点为社区机构，下级只能为单元
                    if(parent.isShowFlag !== 4){
                        parent = getOrgList(parent,options.common);
                        result = unitTreeFn(parent);
                    }
                }else if(parent.flag === 4){//父节点为单元，下级只能为房间
                    if(parent.isShowFlag !== 5){
                        parent = unitTreeFn(parent);
                        result = roomTreeFn(parent);
                    }
                }else{//父节点为房间，下级只能为住户
                    //暂时不需要
                }
            }else {
                //  查询机构
                result = getOrgList(parent,options.common);
            }

            //  判断是否有子节点
            if (result.length <= 0 || (result.children.length <= 0 && !isInit)){
                return;
            }

            var resultOrg = [], resultEstate = [], resultAd = [], resultAgency = [], resultPark = [];
            $.extend(resultOrg, result), $.extend(resultEstate, result), $.extend(resultAd, result), $.extend(resultAgency, result), $.extend(resultPark, result);
            resultOrg.children = [], resultEstate.children = [], resultAd.children = [], resultAgency.children = [], resultPark.children = [];
            result.children.forEach(function(item){
                if (parent.id == 1){//机构
                    if (item.type == 3){//物业
                        resultEstate.children.push(item);
                    }else if (item.type == 2){//广告商
                        resultAd.children.push(item);
                    }else if (item.type == 4){//社区
                        resultAgency.children.push(item);
                    }else if (item.type == 5){//园区
                        resultPark.children.push(item);
                    }else{
                        resultOrg.children.push(item);
                    }
                }else{
                    if (document.getElementById('per-tree-org').hidden == false){
                        resultOrg.children.push(item);
                    }
                    if (document.getElementById('per-tree-estate').hidden == false){
                        resultEstate.children.push(item);
                    }
                    if (document.getElementById('per-tree-ad').hidden == false){
                        resultAd.children.push(item);
                    }
                    if (document.getElementById('per-tree-agency').hidden == false){
                        resultAgency.children.push(item);
                    }
                    if (document.getElementById('per-tree-park').hidden == false){
                        resultPark.children.push(item);
                    }
                }

            });


            //  在路径上拼接 ‘/’符号
            if (aList.length > 0){
                if (document.getElementById('per-tree-estate').hidden == false){
                    $node.pathEstate.append('<span lay-separator>/</span>');
                }
                if(document.getElementById('per-tree-org').hidden == false){
                    $node.pathOrg.append('<span lay-separator>/</span>');
                }
                if(document.getElementById('per-tree-ad').hidden == false){
                    $node.pathAd.append('<span lay-separator>/</span>');
                }
                if(document.getElementById('per-tree-agency').hidden == false){
                    $node.pathAgency.append('<span lay-separator>/</span>');
                }
                if(document.getElementById('per-tree-park').hidden == false){
                    $node.pathPark.append('<span lay-separator>/</span>');
                }
            }
            //  添加点击事件
            lastA.attr('href', 'javascript:void(0);');
            lastA.html(lastA.text());
            //  拼接路径
            // $node.path.append('<a data-id="' + result.id + '" data-flag="' + result.flag + '"><cite>' + result.name + '</cite></a>');

            function renderTree(elementId, $path, data){
                //  拼接路径
                $path.append('<a data-id="' + data.id + '" data-flag="' + data.flag + '"><cite>' + data.name + '</cite></a>');

                layui.tree({
                    elem: '#' + elementId
                    , click: function (item) {
                        $node.searchInput.val('');
                        options.treeClickFn(item);
                        clearItemActive();
                        if (item.children.length > 0){
                            return;
                        }
                        loadTreeList(item,false);
                    }
                    , nodes: [data]
                });
                initShow();
                $('#' + elementId + ' .layui-icon.layui-tree-leaf').remove();
                $('#' + elementId + ' .layui-icon.layui-tree-branch').remove();
            }
            //  渲染机构树形
            if (document.getElementById('per-tree-org').hidden == false){
                //  清空下拉树
                $node.treeOrg.html('');
                //渲染树型
                renderTree('per-tree-org', $node.pathOrg, resultOrg);
            }
            //  渲染物业树形
            if (document.getElementById('per-tree-estate').hidden == false || isInit == true){
                //  清空下拉树
                $node.treeEstate.html('');
                //渲染树型
                renderTree('per-tree-estate', $node.pathEstate, resultEstate);
            }
            //  渲染广告商树形
            if (document.getElementById('per-tree-ad').hidden == false || isInit == true){
                //  清空下拉树
                $node.treeAd.html('');
                //渲染树型
                renderTree('per-tree-ad', $node.pathAd, resultAd);
            }
            //  渲染社区树形
            if (document.getElementById('per-tree-agency').hidden == false || isInit == true){
                //  清空下拉树
                $node.treeAgency.html('');
                //渲染树型
                renderTree('per-tree-agency', $node.pathAgency, resultAgency);
            }
            //  渲染园区树形
            if (document.getElementById('per-tree-park').hidden == false || isInit == true){
                //  清空下拉树
                $node.treePark.html('');
                //渲染树型
                renderTree('per-tree-park', $node.pathPark, resultPark);
            }
        };

        //  路径点击处理事件
        function pathClickFn($this) {
            if ($this.attr('href')) {
                $this.nextAll().each(function () {
                    $(this).remove();
                });
                var item = {
                    id: parseInt($this.attr('data-id')),
                    flag: parseInt($this.attr('data-flag')),
                    name: $this.text(),
                    spread: true
                };
                $this.prev().remove();
                $this.remove();
                loadTreeList(item, false);
                options.pathClickFn(item);
            }
            $node.searchInput.val('');
        }
        //清除其他树的选中状态
        function clearItemActive(){
            if (document.getElementById('per-tree-org').hidden == true){
                $('#per-tree-org .citecolor').removeClass('citecolor');
            }
            if (document.getElementById('per-tree-estate').hidden == true){
                $('#per-tree-estate .citecolor').removeClass('citecolor');
            }
            if (document.getElementById('per-tree-ad').hidden == true){
                $('#per-tree-ad .citecolor').removeClass('citecolor');
            }
            if (document.getElementById('per-tree-agency').hidden == true){
                $('#per-tree-agency .citecolor').removeClass('citecolor');
            }
             if (document.getElementById('per-tree-park').hidden == true){
                $('#per-tree-park .citecolor').removeClass('citecolor');
            }
        }

        //  路径点击事件绑定
        $(document).on('click','#path-org a,#path-estate a,#path-ad a,#path-agency a,#path-park a',function () {
            pathClickFn($(this));
        });

        //  初始化
        if ((!!document.getElementById('org_id') && document.getElementById('org_id').value == '1') ||
            (!!document.getElementById('user_org_id') && document.getElementById('user_org_id').value == '1')){
            document.getElementById('tab').hidden = false;
        }
        if (!!document.getElementById('showAd') && document.getElementById('showAd').value == 'true'){
            document.getElementById('ad').hidden = false;
            document.getElementsByClassName('ad')[0].hidden = false;
        }

        loadTreeList({
            id      :   options.orgId,
            spread  :   true
        },true);
    };

    // $(document).on('mouseenter','#tab,#search,#path-org,#path-estate,#path-ad#per-tree-org,#per-tree-estate,#per-tree-ad',function(){
    //     // $('#leftDiv').hide(500);
    //     $('.per-table').animate({marginLeft: '160px'});
    // })
    // $(document).on('mouseenter','.layui-form',function(){
    //     // $('#leftDiv').show(500);
    //     $('.per-table').animate({marginLeft: '0px'});
    // })
    var flexibleStatus = 1;
    $(document).on('click', '.tree-flexible', function(){
        if (flexibleStatus == 1){
            $('.per-table').animate({marginLeft: '0px'});
            $('#leftDiv').hide(500);
            $('#flexible1').show();
            flexibleStatus = 0;
        }else{
            $('.per-table').animate({marginLeft: '160px'});
            $('#leftDiv').show(500);
            $('#flexible1').hide();
            flexibleStatus = 1;
        }
    })
    exports('orgTree', orgTree);
});

