var tiledMapUnit = require('TiledMapUnit');
var reGameStates = require('GameStates');
//商品信息
var highwayInfo = cc.Class({
    name: "hightwayInfo",
    properties: {
        //公路id
        highwayInfoId: {
            default: -1,
            type: cc.Integer,
            tooltip: '公路的id.',
        },

        //公路方向类型
        highwayInfoType: {
            default: reGameStates.HighwayType.none,
            type: cc.Enum(reGameStates.HighwayType),
        },

        //公路约定的index值
        highwayInfoIndex: {
            default: -1,
            type: cc.Integer,
            tooltip: '公路约定的Index值.',
        },


    }
});
var GameManager = cc.Class({
    extends: cc.Component,
    properties: {
        //记录全部道路的样式和Index值
        AllHighwayStylesAndIndex: {
            default: [],
            type: [highwayInfo],
            visible: false,
            serializable: false,
        },
        //记录建筑的类和信息
        buildingsTiledMapUnit: [tiledMapUnit],
        //id是对应物体的index
        //约定占位信息Index=WIDHT*tielY+tileX，WIDTH是最大tileX坐标。
        OccupyArray: [],
        // OccupyArrayV2: [],
        //维护节点的渲染顺序
        sliblingIndexArray: [],
        //工人住房的数组信息
        //每个工人都会分配一个房子，房子用id来区分
        //x值为buildId,y为Index
        housingArray: [],
        //工作的建筑数组信息
        //农田
        FarmlandBuildingArray: [],
        //木材厂
        TimberYardBuildingArray: [],
        //矿厂
        MiningPitBuildingArray: [],
        //游客的话，对应可销售的数组
        //工人的话，对应可收集数组
        MaterialsArray: [],
        //工厂
        FactoryArray: [],
        //需要生产的物品，
        //那个商店需要的商品
        productCommodityArray: [],
        //存储空闲工人的数组
        //Node类型
        WorkerArray: [cc.Node],
        //int类型,保存工人初始化位置
        WorkerInitInfoArray: [cc.Integer],


        //可销售的商店
        shopBuildingSalesArray: [],

        tiledMap: {
            default: null,
            type: cc.Node,
        },

        //最大的tilex坐标
        // WIDHT: 50,
        labelPrefabs: {
            default: null,
            type: cc.Prefab,
        },
        SpawnPoint: {
            default: null,
            type: cc.Node,
        },

        //提示牌：暂停营业
        buildingTipViewPrefabs: {
            default: null,
            type: cc.Prefab,
        },

        //ui的节点
        ManageUINode: cc.Node,
        //获取管理UI脚本
        _ManageUIScript: null,
        //主摄像机
        MainCamera: cc.Camera,
        //当前的canvas
        Canvas: cc.Node,
        //记录当前编辑的建筑
        currentEditorBuilding: {
            default: null,
            type: cc.Node,
            visible: false,
        },
        //是否是编辑状态
        _ifEditingStatus: { default: false, visible: false },
        //当前编辑的建筑的提示区域
        currentEditorBuildingTipPrefab: {
            default: null,
            type: cc.Prefab,
        },
        //当前提示区域的数组
        EditorBuildingTipArray: {
            default: [],
            type: cc.Node,
            visible: false,
        },
        //当前编辑房屋影响的房子节点
        EditorBuildingEffectNodeArray: {
            default: [],
            type: cc.Node,
            visible: false,
        },
        FoodTradeState: cc.Node,
        WoodTradeState: cc.Node,
        MineralTradeState: cc.Node,

        AllowPrefabs: {
            default: null,
            type: cc.SpriteFrame,
        },
        NoAllowPrefabs: {
            default: null,
            type: cc.SpriteFrame,
        },

        //影响提示的预制
        EffectUpAndDown: cc.Prefab,
        //显示的库存总量，人才界面
        cropContentNum: { default: 0, type: cc.Integer, visible: false },
        woodContentNum: { default: 0, type: cc.Integer, visible: false },
        mineContentNum: { default: 0, type: cc.Integer, visible: false },
    },
    //Enum
    statics: {
    },
    onLoad() {
        GlobalD.GameManager = GameManager;
        GlobalD.game = this;

        if (this.ManageUINode)
            this._ManageUIScript = this.ManageUINode.getComponent('ManageUI');

        //如果有提示框
        if (this.currentEditorBuildingTipPrefab) {
            this.HighTipPool = new cc.NodePool();
            let initCount = 10;
            for (let i = 0; i < initCount; ++i) {
                let highTipTemp = cc.instantiate(this.currentEditorBuildingTipPrefab); // 创建节点
                highTipTemp.active = false;
                this.HighTipPool.put(highTipTemp); // 通过 putInPool 接口放入对象池
            }
        }


    },
    //如果进入编辑状态，游戏暂停
    //可以编辑，清除建筑，道路等. 
    //todo...
    onEnterEditingStatus() {
        this._ifEditingStatus = true;
    },
    //添加场景物体基本信息数组// //添加占位信息
    addBuildTiled(_buildId, _startTiledPos, _occupyingArea, isOccupy = true) {
        let areaX = _occupyingArea.x;
        let areaY = _occupyingArea.y;
        for (let i = 0; i < areaX; i++) {
            for (let j = 0; j < areaY; j++) {
                // let index = this.WIDHT * (_startTiledPos.y - j) + (_startTiledPos.x - i);
                let index = GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x - i, _startTiledPos.y - j));
                let occupyTemp = cc.v2(_buildId, index);
                this.OccupyArray.push(occupyTemp);

                // let tempV2 = cc.v2(_startTiledPos.x - i, _startTiledPos.y - j);
                // // this.OccupyArrayV2.push(tempV2);

                // var pos = GlobalD.TiledMap._locationFromtilePos(tempV2);
                // return;
                // var label = cc.instantiate(this.labelPrefabs);
                // label.parent = this.SpawnPoint;
                // label.setPosition(pos);
                // label.getComponent(cc.Label).string = "(" + tempV2.x + ',' + tempV2.y + ')';
                // label.getComponent('LabelInfo').BuildId = _buildId;
            }
        }
    },


    //更新占位信息
    //移动后更新原来的占位信息。
    updateBuildOccupy(isMove, _buildId, _startTiledPos, _occupyingArea) {
        if (isMove) {//如果移动的话，重新设置信息

            //临时清空label 节点 。todo...
            // this.clearChildren(_buildId);

            //需要更新的下标
            let updateIndex = 0;
            //需要更新的数组
            let updateArray = [];
            let areaX = _occupyingArea.x;
            let areaY = _occupyingArea.y;
            for (let i = 0; i < areaX; i++) {
                for (let j = 0; j < areaY; j++) {
                    // let index = this.WIDHT * (_startTiledPos.y - j) + (_startTiledPos.x - i);
                    let index = GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x - i, _startTiledPos.y - j));
                    let occupyTemp = cc.v2(_buildId, index);
                    updateArray.push(occupyTemp);

                    // let tempV2 = cc.v2(_startTiledPos.x - i, _startTiledPos.y - j);
                    // var pos = GlobalD.TiledMap._locationFromtilePos(tempV2);
                    // var label = cc.instantiate(this.labelPrefabs);
                    // label.parent = this.SpawnPoint;
                    // label.setPosition(pos);
                    // label.getComponent(cc.Label).string = "(" + tempV2.x + ',' + tempV2.y + ')';
                    // label.getComponent('LabelInfo').BuildId = _buildId;
                }
            }
            let length = this.OccupyArray.length;
            if (length > 0) {
                for (let i = 0; i < length; i++) {
                    if (this.OccupyArray[i].x == _buildId) {
                        this.OccupyArray[i].y = updateArray[updateIndex].y;
                        updateIndex++;
                        //如果需要更新的下标遍历完全后，直接退出
                        if (updateIndex >= updateArray.length) {
                            // cc.log('OccupyArray 更新完毕！');
                            break;
                        }
                    }
                }
            }
        } else {//没有移动的话，回到原来的位置
            //todo..
        }
    },

    //添加建筑的提示牌
    onAddBuildingTipView(_targetBuilding) {
        if (this.buildingTipViewPrefabs) {
            if (_targetBuilding.node.getChildByName('BuildingTipView')) return;

            var _buildTipView = cc.instantiate(this.buildingTipViewPrefabs);
            _buildTipView.parent = _targetBuilding.node;
            _buildTipView.setPosition(cc.v2(0, 50));

        } else {
            cc.warn('请在ManageGame 的面板添加BuildingTipView预制！');
        }

    },
    //移除建筑的提示牌
    onRemoveBuildingTipView(_targetBuilding) {
        if (_targetBuilding.node.getChildByName('BuildingTipView'))
            _targetBuilding.node.getChildByName('BuildingTipView').destroy();
    },

    //根据index 获取公路节点
    onGetHighwayFromIndex(targetIndex) {
        let roadIndexArray = GlobalD.game.AllHighwayStylesAndIndex;
        let length = roadIndexArray.length;
        for (let i = 0; i < length; i++) {
            if (targetIndex === roadIndexArray[i].highwayInfoIndex) {
                return true;
            }
        }
        return false;

    },

    //根据建筑id 获取对应的buildingsInfo
    onGetBuildingsTiledMapUnitFromBuildID(targetBuildID) {
        let length = this.buildingsTiledMapUnit.length;
        for (let i = 0; i < length; i++) {
            // cc.log(targetBuildID, this.buildingsTiledMapUnit[i].getBuildingID);
            if (targetBuildID === this.buildingsTiledMapUnit[i].getBuildingID) {
                return this.buildingsTiledMapUnit[i].getBuildingsInfo;
            }
        }
        return false;
    },

    //根据index 获取对应的buildingsInfo
    onGetBuildingsTiledMapUnitFromIndex(targetIndex) {
        let length = this.buildingsTiledMapUnit.length;
        for (let i = 0; i < length; i++) {
            if (this.buildingsTiledMapUnit[i].onIndexExistInThis(targetIndex)) {
                if (this.buildingsTiledMapUnit[i].getBuildingsInfo)
                    return this.buildingsTiledMapUnit[i].getBuildingsInfo;
                else
                    return false;
            }
        }
        return false;
    },
    //    Muinus(buildingName) {
    /**
     * 建筑物减1操作
     * @param {建筑名称} buildingName 
     */    
    MuinusBuilding(buildingName) {
        let ManageBuildings = this.ManageUINode.getComponent('ManageBuildings');
        if (!ManageBuildings) return;

        let BuildingNumArray = GlobalD.GameData.BuildingNumArray;

        for (let i = 0; i < ManageBuildings.BuildingArray.length; i++) {
            // cc.log('Name='+ManageBuildings.BuildingArray[i].getChildByName('Name').getComponent(cc.Label).string,buildingName);
            if (ManageBuildings.BuildingArray[i].getChildByName('Name').getComponent(cc.Label).string == buildingName) {
                if (BuildingNumArray[i] == 0) return;
                BuildingNumArray[i] = Number(BuildingNumArray[i]) - 1;

                ManageBuildings.BuildingArray[i].getChildByName('Name').getChildByName('Num').getComponent(cc.Label).string = BuildingNumArray[i].toString();
                GlobalD.GameData.SetBuildingNumArray(BuildingNumArray);
                GlobalD.GameData.PlusGolden(-GlobalD.GameData.AddBuildingCost);
                // cc.log('222222222222='+ BuildingNumArray[i]);
                return;
            }
        }
    },

    //钻石：购买后增加对应可建造的数据
    //todo 现在修改为不给购买了。给默认值
    AddBuildingNum(_buttonNodeName) {
        let ManageBuildings = this.ManageUINode.getComponent('ManageBuildings');
        if (!ManageBuildings) return;
        let BuildingNumArray = GlobalD.GameData.BuildingNumArray;
        for (let i = 0; i < ManageBuildings.BuildingArray.length; i++) {
            if (ManageBuildings.BuildingArray[i].name == _buttonNodeName) {
                BuildingNumArray[i] = Number(BuildingNumArray[i]) + 1;
                ManageBuildings.BuildingArray[i].getChildByName('Name').getChildByName('Num').getComponent(cc.Label).string = BuildingNumArray[i].toString();
                GlobalD.GameData.SetBuildingNumArray(BuildingNumArray);
                let _contentButton = ManageBuildings.BuildingArray[i].getComponent('Content_Button');
                //设置新的钻石价格
                let _DiamondNumArray = GlobalD.GameData.GetDiamondNumArray();
                // _DiamondNumArray[i] = Number(_DiamondNumArray[i]) * 1.5 + '';
                _DiamondNumArray[i] = Number(_DiamondNumArray[i]) + '';
                //更新对应的ui
                _contentButton.DiamondPrice = _DiamondNumArray[i];   //钻石费用
                GlobalD.GameData.SetDiamondNumArray(_DiamondNumArray);
                return;
            }
        }
    },
    //用类型添加场景物件
    addBuilding(item) {
        // cc.log('buildInfo=='+ item.buildInfo.buildingName);
        // this.MuinusBuilding(item.buildInfo.buildingName);
        //添加深度检测的占位信息
        //  _startTiledPos, _occupyingArea
        //四周围 有通路的点都可以作为目标点
        //清空数组
        item.buildInfo._gotoPosistion = [];
        let _indexArray = [];
        let areaX = item.buildInfo.occupyArea.x;
        let areaY = item.buildInfo.occupyArea.y;
        for (let i = 0; i < areaX; i++) {
            for (let j = 0; j < areaY; j++) {

                let targetPosition = cc.v2(item.buildInfo.startTilePos.x - i, item.buildInfo.startTilePos.y - j);
                item.buildInfo._gotoPosistion.push(targetPosition);
                let buildIndex = GlobalD.TiledMap.getIndex(targetPosition);

                //
                this.sliblingIndexArray.push(cc.v2(item.node.getSiblingIndex(), buildIndex));
                //添加约定的数组
                _indexArray.push(buildIndex);
            }
        }
        //设置Index
        let _ZIndex = this.onUpdateVertexZFromZIndex(item.node, item.buildInfo.startTilePos);//GlobalD.TiledMap.getIndex(item.buildInfo.startTilePos);
        // cc.log(item.node.name,' == ',_ZIndex);


        //记录节点信息
        let tiledTemp = new tiledMapUnit();
        tiledTemp.onSetBuildingID(item.buildInfo.id);
        tiledTemp.onSetSiblingIndex(item.node.getSiblingIndex());
        tiledTemp.onSetZIndex(_ZIndex);
        tiledTemp.onSetStartTiledPos(item.buildInfo.startTilePos);
        tiledTemp.onSetOccupyingArea(areaX, areaY)
        tiledTemp.onSetIndexArray(_indexArray);
        tiledTemp.onSetBuildingsInfo(item);
        this.buildingsTiledMapUnit.push(tiledTemp);


        switch (item.buildInfo.buildType) {
            //如果移动或者创建的是住房
            case reGameStates.BuildType.Housing:
                this.housingArray.push(item);
                break;
            //如果是农田，采木场，矿坑,加工厂。
            case reGameStates.BuildType.Farmland:
                this.FarmlandBuildingArray.push(item);
                this.onSetMaterialsArray(item);
                break;
            case reGameStates.BuildType.TimberYard:
                this.TimberYardBuildingArray.push(item);
                this.onSetMaterialsArray(item);
                break;
            case reGameStates.BuildType.MiningPit:
                // cc.log('工作的建筑信息：', item.buildInfo);
                this.MiningPitBuildingArray.push(item);
                this.onSetMaterialsArray(item);
                break;
            case reGameStates.BuildType.Factory:
                this.FactoryArray.push(item);
                break;
            case reGameStates.BuildType.Shop:
                this.shopBuildingSalesArray.push(item);
                break;
        }


        if (item.buildInfo.isItActive) {
            let BuildingsItem = {
                "buildingNodeName": item.node.name,
                "buildingId": item.buildInfo.id,
                "startTilePos": item.buildInfo.startTilePos,
                "isDefault": item.InitPos,//如果有初始化，说明在地图上
                "isItSaleable": item.buildInfo.isItSaleable ? 1 : 0,//建筑当前的销售状态
                "isItStopOperation": item.buildInfo.isItStopOperation ? 1 : 0,//建筑当前的运营状态
                "consumeStrengthAddValue": item.buildInfo.consumeStrengthAddValue,//建筑体力值变化的加成
                "goodsPriceAddValue": item.buildInfo.goodsPriceAddValue,//商品销售的加成值
            };

            //默认建筑初始化时候，如果存在数据中，就只更新数据
            let isUpdateData = false;
            //更新建筑物存储信息
            let gameDataBuildings = GlobalD.GameData.GameData_buildings;

            for (let i = 0; i < gameDataBuildings.length; i++) {
                if (item.buildInfo.id == gameDataBuildings[i].buildingId) {
                    gameDataBuildings.splice(i, 1, BuildingsItem);
                    // cc.log('item.buildInfo.id11', item.buildInfo.id);
                    isUpdateData = true;
                    break;
                }
            }
            if (isUpdateData) return;
            // cc.log('item.buildInfo.id22', item.buildInfo.id);
            if (!item.InitPosFromStore)
                //添加建筑物存储信息
                GlobalD.GameData.GameData_buildings.push(BuildingsItem);
        }
    },
    PlusBuilding(buildingName) {
        cc.log('buildingName='+buildingName)
        let ManageBuildings = this.ManageUINode.getComponent('ManageBuildings');
        if (!ManageBuildings) return;

        let BuildingNumArray = GlobalD.GameData.BuildingNumArray;

        for (let i = 0; i < ManageBuildings.BuildingArray.length; i++) {
            // cc.log('Name='+ManageBuildings.BuildingArray[i].getChildByName('Name').getComponent(cc.Label).string);
            if (ManageBuildings.BuildingArray[i].getChildByName('Name').getComponent(cc.Label).string == buildingName) {
                BuildingNumArray[i] = Number(BuildingNumArray[i]) + 1;

                ManageBuildings.BuildingArray[i].getChildByName('Name').getChildByName('Num').getComponent(cc.Label).string = BuildingNumArray[i].toString();
                GlobalD.GameData.SetBuildingNumArray(BuildingNumArray);
                GlobalD.GameData.PlusGolden(-GlobalD.GameData.RemoveBuildingCost);
                // cc.log('222222222222='+ BuildingNumArray[i]);
                return;
            }
        }
    },
    //移除建筑物
    removeBuilding(item) {
        // cc.log('removeBuilding',item.buildInfo.id,this.buildingsTiledMapUnit);
        let buildInfo = item.buildInfo;
        this.PlusBuilding(item.buildInfo.buildingName);
        //首先移除占位信息
        //临时清空label 节点 。todo...
        this.clearChildren(buildInfo.id);
        let removeIndex = 0;
        let removeArray = [];
        let areaX = buildInfo.occupyArea.x;
        let areaY = buildInfo.occupyArea.y;
        for (let i = 0; i < areaX; i++) {
            for (let j = 0; j < areaY; j++) {
                let buildIndex = GlobalD.TiledMap.getIndex(cc.v2(buildInfo.startTilePos.x - i, buildInfo.startTilePos.y - j));
                let occupyTemp = cc.v2(buildInfo.id, buildIndex);
                removeArray.push(occupyTemp);
            }
        }
        let length = this.OccupyArray.length;
        for (let i = length - 1; i >= 0; i--) {
            if (this.OccupyArray[i].x === buildInfo.id) {
                this.OccupyArray.splice(i, 1);
                removeIndex++;
                //如果需要更新的下标遍历完全后，直接退出
                if (removeIndex >= removeArray.length) {
                    // cc.log('OccupyArray 更新完毕！');
                    break;
                }
            }
        }
        //清空buildingsTiledMapUnit节点信息
        let _buildingsTiledMapLength = this.buildingsTiledMapUnit.length;
        for (let i = _buildingsTiledMapLength - 1; i >= 0; i--) {
            // cc.log(this.buildingsTiledMapUnit[i]);
            if (buildInfo.id === this.buildingsTiledMapUnit[i].getBuildingID) {
                //移除buildingsTiledMapUnit节点信息
                this.buildingsTiledMapUnit.splice(i, 1);
            }

        }

        //拆除房子后
        if (item.buildInfo.occupantPlayerInfo) {
            item.buildInfo.occupantPlayerInfo.onHideChildrenNode(true);
        }


        //区分类别后移除
        switch (item.buildInfo.buildType) {
            //如果移动或者创建的是住房
            case reGameStates.BuildType.Housing:
                // cc.log('移除房子：');
                for (let i = 0; i < this.housingArray.length; i++) {
                    if (item.buildInfo.id == this.housingArray[i].buildInfo.id) {
                        this.housingArray.splice(i, 1);
                    }
                }
                break;
            //如果是农田，采木场，矿坑,加工厂。
            case reGameStates.BuildType.Farmland:
                // cc.log('移除农田工作的建筑信息：');
                for (let i = 0; i < this.FarmlandBuildingArray.length; i++) {
                    if (item.buildInfo.id == this.FarmlandBuildingArray[i].buildInfo.id) {
                        this.FarmlandBuildingArray.splice(i, 1);
                    }
                }
                this.onUpdateMaterialsArray(item, true);
                break;
            case reGameStates.BuildType.TimberYard:
                // cc.log('移除木材厂工作的建筑信息：', item.buildInfo);
                for (let i = 0; i < this.TimberYardBuildingArray.length; i++) {
                    if (item.buildInfo.id == this.TimberYardBuildingArray[i].buildInfo.id) {
                        this.TimberYardBuildingArray.splice(i, 1);
                    }
                }
                this.onUpdateMaterialsArray(item, true);
                break;
            case reGameStates.BuildType.MiningPit:
                // cc.log('移除矿产工作的建筑信息：');
                for (let i = 0; i < this.MiningPitBuildingArray.length; i++) {
                    if (item.buildInfo.id == this.MiningPitBuildingArray[i].buildInfo.id) {
                        this.MiningPitBuildingArray.splice(i, 1);
                    }
                }
                this.onUpdateMaterialsArray(item, true);
                break;
            case reGameStates.BuildType.Factory:
                // cc.log('移除工厂');
                for (let i = 0; i < this.FactoryArray.length; i++) {
                    if (item.buildInfo.id == this.FactoryArray[i].buildInfo.id) {
                        this.FactoryArray.splice(i, 1);
                    }
                }
                break;
            case reGameStates.BuildType.Shop:
                // cc.log('移除商店');
                for (let i = 0; i < this.shopBuildingSalesArray.length; i++) {
                    if (item.buildInfo.id == this.shopBuildingSalesArray[i].buildInfo.id) {
                        this.shopBuildingSalesArray.splice(i, 1);
                    }
                }
                break;
        }



        //移除建筑物存储信息
        let gameDataBuildings = GlobalD.GameData.GameData_buildings;
        for (let i = 0; i < gameDataBuildings.length; i++) {
            if (item.buildInfo.id == gameDataBuildings[i].buildingId) {
                gameDataBuildings.splice(i, 1);
            }
        }
    },
    //更新建筑信息
    updateBuilding(item) {
        let _indexArray = [];
        //记录目标点
        //清空数组
        item.buildInfo._gotoPosistion = [];
        let areaX = item.buildInfo.occupyArea.x;
        let areaY = item.buildInfo.occupyArea.y;
        for (let i = 0; i < areaX; i++) {
            for (let j = 0; j < areaY; j++) {
                let targetPosition = cc.v2(item.buildInfo.startTilePos.x - i, item.buildInfo.startTilePos.y - j);
                item.buildInfo._gotoPosistion.push(targetPosition);

                let buildIndex = GlobalD.TiledMap.getIndex(targetPosition);
                //添加约定的数组
                _indexArray.push(buildIndex);
            }
        }
        // let buildIndex = GlobalD.TiledMap.getIndex(item.buildInfo.startTilePos);
        // item.node.setSiblingIndex(buildIndex);
        //更新Index
        let _ZIndex = this.onUpdateVertexZFromZIndex(item.node, item.buildInfo.startTilePos);

        let _buildingsTiledMapLength = this.buildingsTiledMapUnit.length;
        for (let i = 0; i < _buildingsTiledMapLength; i++) {
            if (item.buildInfo.id === this.buildingsTiledMapUnit[i].getBuildingID) {
                //更新buildingsTiledMapUnit节点信息
                this.buildingsTiledMapUnit[i].onSetSiblingIndex(item.node.getSiblingIndex());
                //cc.log('this.buildingsTiledMapUnit[i]',_ZIndex,item.node.getSiblingIndex());

                this.buildingsTiledMapUnit[i].onSetZIndex(_ZIndex);
                this.buildingsTiledMapUnit[i].onSetStartTiledPos(item.buildInfo.startTilePos);
                this.buildingsTiledMapUnit[i].onSetOccupyingArea(areaX, areaY)
                this.buildingsTiledMapUnit[i].onSetIndexArray(_indexArray);
                this.buildingsTiledMapUnit[i].onSetBuildingsInfo(item);

                break;
            }
        }



        switch (item.buildInfo.buildType) {
            //如果移动或者创建的是住房
            case reGameStates.BuildType.Housing:
                // cc.log(item.buildInfo);
                for (let i = 0; i < this.housingArray.length; i++) {
                    if (item.buildInfo.id == this.housingArray[i].buildInfo.id) {
                        this.housingArray.splice(i, 1, item);
                    }
                }
                break;
            //如果是农田，采木场，矿坑,加工厂。
            case reGameStates.BuildType.Farmland:
                // cc.log('农田工作的建筑信息：', item.buildInfo);
                for (let i = 0; i < this.FarmlandBuildingArray.length; i++) {
                    if (item.buildInfo.id == this.FarmlandBuildingArray[i].buildInfo.id) {
                        this.FarmlandBuildingArray.splice(i, 1, item);
                    }
                }
                this.onUpdateMaterialsArray(item);
                break;
            case reGameStates.BuildType.TimberYard:
                // cc.log('木材厂工作的建筑信息：', item.buildInfo);
                for (let i = 0; i < this.TimberYardBuildingArray.length; i++) {
                    if (item.buildInfo.id == this.TimberYardBuildingArray[i].buildInfo.id) {
                        this.TimberYardBuildingArray.splice(i, 1, item);
                    }
                }
                this.onUpdateMaterialsArray(item);
                break;
            case reGameStates.BuildType.MiningPit:
                // cc.log('矿产工作的建筑信息：', item.buildInfo);
                for (let i = 0; i < this.MiningPitBuildingArray.length; i++) {
                    if (item.buildInfo.id == this.MiningPitBuildingArray[i].buildInfo.id) {
                        this.MiningPitBuildingArray.splice(i, 1, item);
                    }
                }
                this.onUpdateMaterialsArray(item);
                break;
            case reGameStates.BuildType.Factory:
                // cc.log('工厂', item.buildInfo);
                for (let i = 0; i < this.FactoryArray.length; i++) {
                    if (item.buildInfo.id == this.FactoryArray[i].buildInfo.id) {
                        this.FactoryArray.splice(i, 1, item);
                    }
                }
                break;
            case reGameStates.BuildType.Shop:
                // cc.log('商店', item.buildInfo);
                for (let i = 0; i < this.shopBuildingSalesArray.length; i++) {
                    if (item.buildInfo.id == this.shopBuildingSalesArray[i].buildInfo.id) {
                        this.shopBuildingSalesArray.splice(i, 1, item);
                    }
                }
                break;
        }



        let BuildingsItem = {
            "buildingNodeName": item.node.name,
            "buildingId": item.buildInfo.id,
            "startTilePos": item.buildInfo.startTilePos,
            "isDefault": false,
            "isItSaleable": item.buildInfo.isItSaleable ? 1 : 0,//建筑当前的销售状态
            "isItStopOperation": item.buildInfo.isItStopOperation ? 1 : 0,//建筑当前的运营状态
            "consumeStrengthAddValue": item.buildInfo.consumeStrengthAddValue,//建筑体力值变化的加成
            "goodsPriceAddValue": item.buildInfo.goodsPriceAddValue,//商品销售的加成值
        };

        // cc.log('更新的建筑信息BuildingsItem：',BuildingsItem);
        //更新建筑物存储信息
        let gameDataBuildings = GlobalD.GameData.GameData_buildings;
        for (let i = 0; i < gameDataBuildings.length; i++) {
            if (item.buildInfo.id == gameDataBuildings[i].buildingId) {
                // isDefault 是默认值，以数组为准
                BuildingsItem.isDefault = gameDataBuildings[i].isDefault;
                gameDataBuildings.splice(i, 1, BuildingsItem);
            }
        }
    },
    //关闭所有商店
    onClosingAllShopArray() {
        for (let i = 0; i < this.shopBuildingSalesArray.length; i++) {
            this.shopBuildingSalesArray[i].buildInfo.isItSaleable = false;

            // console.log("商店信息",this.shopBuildingSalesArray[i]);
            this.shopBuildingSalesArray[i].node.getComponent("buildingTips").playBoard();
        }
    },
    //开放所有商店
    onOpenAllShopArray() {
        for (let i = 0; i < this.shopBuildingSalesArray.length; i++) {
            this.shopBuildingSalesArray[i].buildInfo.isItSaleable = true;
            this.shopBuildingSalesArray[i].node.getComponent("buildingTips").stopBoard();
        }
    },
    //关闭所有销售原料的地方
    onClosingAllSalesArray() {
        for (let i = 0; i < this.MaterialsArray.length; i++) {
            this.MaterialsArray[i].buildInfo.isItSaleable = false;

        }
    },
    //开放所有销售原料的地方
    onOpenAllSalesArray() {
        for (let i = 0; i < this.MaterialsArray.length; i++) {
            this.MaterialsArray[i].buildInfo.isItSaleable = true;
        }
    },
    // 设置可以销售的建筑对象
    onSetMaterialsArray(item) {
        // cc.log("onSetMaterialsArray = ",item.buildInfo.buildingName,item.buildInfo.isItSaleable);
        GlobalD.game.MaterialsArray.push(item);
    },
    // 更新可以销售的建筑对象
    //如果isRemove 为true 的话，可移除对象
    onUpdateMaterialsArray(item, isRemove = false) {
        // cc.log("onUpdateSalesMaterialsArray1",this.MaterialsArray);
        for (let i = 0; i < this.MaterialsArray.length; i++) {
            if (item.buildInfo.id == this.MaterialsArray[i].buildInfo.id) {
                if (isRemove) {
                    this.MaterialsArray.splice(i, 1);
                } else {
                    this.MaterialsArray.splice(i, 1, item);
                }
                break;
            }
        }
        // cc.log("onUpdateSalesMaterialsArray2",this.MaterialsArray);
    },
    //新建，移动，删除，旋转的时候，判断是否在数组中
    //_buildId 对应 Occupy数组的x值；
    //return Boolean
    doesItExistArray(_buildId) {
        let isHas = false;
        let length = this.OccupyArray.length;
        if (length > 0) {
            for (let i = 0; i < length; i++) {
                if (this.OccupyArray[i].x == _buildId) {
                    isHas = true;
                    break;
                }
            }
        }
        return isHas;
    },
    //获取ManageGame index 的占位信息
    getManageGameIndexArrayAt(tiledVector2) {
        let index = GlobalD.TiledMap.getIndex(tiledVector2);
        let isHas = false;
        let length = this.OccupyArray.length;
        if (length > 0) {
            for (let i = 0; i < length; i++) {
                if (index == this.OccupyArray[i].y) {
                    isHas = true;
                    break;
                }
            }
        }
        return isHas;
    },
    //清空对应build id 的label节点
    clearChildren(_buildId) {
        let children = this.SpawnPoint.children;
        let length = children.length;
        for (let i = 0; i < length; i++) {
            if (cc.isValid(children[i]) && children[i].getComponent('LabelInfo').BuildId == _buildId) {
                children[i].destroy();
            }
        }
        // cc.log(this.SpawnPoint.children);
    },
    //清除当前编辑建筑的提示框
    onClearSpawnEditorBuildingTip(_parentNode) {
        //删除对应层的子节点
        let tempNode = [];
        if (_parentNode) {
            tempNode = _parentNode.children
        } else {
            tempNode = this.EditorBuildingTipArray;
        }
        let length = tempNode.length;
        for (let i = length - 1; i >= 0; i--) {
            //设置回默认的提示图片
            tempNode[i].getComponent('TipSprite').onReset();
            this.HighTipPool.put(tempNode[i]);

            this.EditorBuildingTipArray.splice(i, 1);
        }
        // cc.log('this.EditorBuildingTipArray',this.EditorBuildingTipArray);

        //清空记录的数组
        this.EditorBuildingEffectNodeArray = [];
    },
    // 当前编辑建筑的提示框
    onSpawnEditorBuildingTip(_parentNode, _startTiledPos, _occupyingArea, _isHas, _buildType) {
        // cc.log('_parentNode:',_parentNode);
        this.onClearSpawnEditorBuildingTip(_parentNode);
        let areaX = _occupyingArea.x;
        let areaY = _occupyingArea.y;

        //设置移动边界
        if (GlobalD.TiledMap.DynamicMinBoundary != _occupyingArea)
            GlobalD.TiledMap.DynamicMinBoundary = _occupyingArea;

        let selfArray = [];

        for (let i = 0; i < areaX; i++) {
            for (let j = 0; j < areaY; j++) {

                let TipPrefabTemp = null;

                if (this.HighTipPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                    TipPrefabTemp = this.HighTipPool.get();
                } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建      
                    TipPrefabTemp = cc.instantiate(this.currentEditorBuildingTipPrefab);
                }
                TipPrefabTemp.parent = _parentNode;
                TipPrefabTemp.active = true;
                let tipTiledtileTemp = TipPrefabTemp.getComponent('TiledTile');
                tipTiledtileTemp.setTiledTilePos(_startTiledPos.x - i, _startTiledPos.y - j);
                if (_isHas) {
                    TipPrefabTemp.getComponent('TipSprite').onSetRedSpriteFrame(230);
                } else {
                    TipPrefabTemp.getComponent('TipSprite').onReset();
                }
                this.EditorBuildingTipArray.push(TipPrefabTemp);

                selfArray.push(GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x - i, _startTiledPos.y - j)))
            }
        }

        let isOpenEffect = _buildType === reGameStates.BuildType.Special ? true : false;

        //特殊效果
        if (!isOpenEffect) return;
        //影响力提示
        for (let i = 0; i < areaX + 4; i++) {
            for (let j = 0; j < areaY + 4; j++) {

                if (GlobalD.TiledMap.getIndexArrayAt(cc.v2(_startTiledPos.x + 2 - i, _startTiledPos.y + 2 - j), selfArray))
                    continue;

                let TipPrefabTemp = null;
                if (this.HighTipPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                    TipPrefabTemp = this.HighTipPool.get();
                } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建      
                    TipPrefabTemp = cc.instantiate(this.currentEditorBuildingTipPrefab);
                }
                TipPrefabTemp.parent = _parentNode;
                TipPrefabTemp.active = true;
                let tipTiledtileTemp = TipPrefabTemp.getComponent('TiledTile');
                tipTiledtileTemp.setTiledTilePos(_startTiledPos.x + 2 - i, _startTiledPos.y + 2 - j);
                let _tiledPos = cc.v2(_startTiledPos.x + 2 - i, _startTiledPos.y + 2 - j)

                //如果不需要删除的
                let isPushArray = true;
                // if ((i == areaX + 4 - 1 || i == 0) || (j == areaY + 4 - 1 || j == 0)) {
                    TipPrefabTemp.getComponent('TipSprite').onSetEffectGreenSpriteFrame();
                    let buildIndex = GlobalD.TiledMap.getIndex(_tiledPos);
                    let _targetBuildingsInfo = GlobalD.game.onGetBuildingsTiledMapUnitFromIndex(buildIndex);
                    if (_targetBuildingsInfo) {
                        // cc.log('绿色区域影响力接触到的房子', _targetBuildingsInfo.buildInfo.buildingName);
                        TipPrefabTemp.getComponent('TipSprite').onSetEffectYellowSpriteFrame();
                        isPushArray = this._AddEditorBuildinsEffectArray(_targetBuildingsInfo);
                     
                    }
                // } else {
                //     TipPrefabTemp.getComponent('TipSprite').onSetEffectYellowSpriteFrame();
                //     let buildIndex = GlobalD.TiledMap.getIndex(_tiledPos);
                //     let _targetBuildingsInfo = GlobalD.game.onGetBuildingsTiledMapUnitFromIndex(buildIndex);
                //     if (_targetBuildingsInfo) {
                //         // cc.log('黄色区域影响力接触到的房子', _targetBuildingsInfo.buildInfo.buildingName);
                //         TipPrefabTemp.getComponent('TipSprite').onSetRedSpriteFrame(180);
                //         isPushArray = this._AddEditorBuildinsEffectArray(_targetBuildingsInfo);
                       
                //     }
                // }

                // if (!isPushArray) {
                //     TipPrefabTemp.destroy();
                //     cc.log('删除！');
                // }


            }
        }

    },

    //如果拆除建筑的时候，清除对应的影响力
    onClearBuildingsEffect(_targetBuildingsInfo) {

        if (_targetBuildingsInfo.buildInfo.buildType !== reGameStates.BuildType.Special) {
            //如果不是特殊建筑调用，返回。
            return;
        }
        let areaX = _targetBuildingsInfo.buildInfo.occupyArea.x;
        let areaY = _targetBuildingsInfo.buildInfo.occupyArea.y;
        let _startTiledPos = _targetBuildingsInfo.buildInfo.startTilePos;

        let selfArray = [];
        for (let i = 0; i < areaX; i++) {
            for (let j = 0; j < areaY; j++) {
                selfArray.push(GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x - i, _startTiledPos.y - j)))
            }
        }
        let _SpecialAroundBuildings = [];
        //影响力提示
        for (let i = 0; i < areaX + 4; i++) {
            for (let j = 0; j < areaY + 4; j++) {

                if (GlobalD.TiledMap.getIndexArrayAt(cc.v2(_startTiledPos.x + 2 - i, _startTiledPos.y + 2 - j), selfArray))
                    continue;

                let _tiledPos = cc.v2(_startTiledPos.x + 2 - i, _startTiledPos.y + 2 - j)
                let effectAddValue = 0;
                if ((i == areaX + 4 - 1 || i == 0) || (j == areaY + 4 - 1 || j == 0)) {
                    let buildIndex = GlobalD.TiledMap.getIndex(_tiledPos);
                    let _targetBuildingsInfo = GlobalD.game.onGetBuildingsTiledMapUnitFromIndex(buildIndex);
                    if (_targetBuildingsInfo) {
                        // cc.log('绿色区域影响力接触到的房子', _targetBuildingsInfo.buildInfo.buildingName);
                        _SpecialAroundBuildings = this._AddTargetEffectArray(_targetBuildingsInfo, _SpecialAroundBuildings);
                        effectAddValue = 10;//增加10点回复或者生产力
                    }
                } else {
                    let buildIndex = GlobalD.TiledMap.getIndex(_tiledPos);
                    let _targetBuildingsInfo = GlobalD.game.onGetBuildingsTiledMapUnitFromIndex(buildIndex);
                    if (_targetBuildingsInfo) {
                        // cc.log('黄色区域影响力接触到的房子', _targetBuildingsInfo.buildInfo.buildingName);
                        _SpecialAroundBuildings = this._AddTargetEffectArray(_targetBuildingsInfo, _SpecialAroundBuildings);
                        effectAddValue = 20;//增加20点回复或者生产力
                    }
                }

            }
        }
        // cc.log('_SpecialAroundBuildings', _SpecialAroundBuildings);
        //拿到对应的特殊建筑
        let _length = _SpecialAroundBuildings.length;

        for (let i = 0; i < _length; i++) {
            if (_SpecialAroundBuildings[i].buildInfo.buildType === reGameStates.BuildType.Shop) {
                //提升销售价格
                _SpecialAroundBuildings[i].buildInfo.goodsPriceAddValue -= _targetBuildingsInfo.buildInfo.specialSetValue;

                this.updateBuilding(_SpecialAroundBuildings[i]);

                this._showDownEffectPrefab(_SpecialAroundBuildings[i]);

            } else if (_SpecialAroundBuildings[i].buildInfo.buildType === reGameStates.BuildType.Special) {
                //特殊建筑不影响周围的特殊建筑
                continue;
            } else {
                //增加消耗的加成值
                _SpecialAroundBuildings[i].buildInfo.consumeStrengthAddValue -= _targetBuildingsInfo.buildInfo.specialSetValue;

                this.updateBuilding(_SpecialAroundBuildings[i]);

                this._showDownEffectPrefab(_SpecialAroundBuildings[i]);

            }
        }
    },

    //如果完成建筑，为对应建筑添加影响力
    onFinishAddEditorBuildingsEffect(_targetBuildingsInfo) {

        if (_targetBuildingsInfo.buildInfo.buildType !== reGameStates.BuildType.Special) {
            //如果不是特殊建筑调用，返回。
            return;
        }
        let _length = this.EditorBuildingEffectNodeArray.length;

        for (let i = 0; i < _length; i++) {

            if (this.EditorBuildingEffectNodeArray[i].buildInfo.buildType === reGameStates.BuildType.Shop) {
                //提升销售价格
                this.EditorBuildingEffectNodeArray[i].buildInfo.goodsPriceAddValue += _targetBuildingsInfo.buildInfo.specialSetValue;

                this.updateBuilding(this.EditorBuildingEffectNodeArray[i]);

                this._showUpEffectPrefab(this.EditorBuildingEffectNodeArray[i]);

            } else if (this.EditorBuildingEffectNodeArray[i].buildInfo.buildType === reGameStates.BuildType.Special) {
                //特殊建筑不影响周围的特殊建筑
                continue;
            } else {
                //剩余的是：
                ////农田
                // Farmland: -1,
                // //采木场
                // TimberYard: -1,
                // //矿坑
                // MiningPit: -1,
                //Housing
                //Factory

                //增加消耗的加成值
                this.EditorBuildingEffectNodeArray[i].buildInfo.consumeStrengthAddValue += _targetBuildingsInfo.buildInfo.specialSetValue;

                this.updateBuilding(this.EditorBuildingEffectNodeArray[i]);

                this._showUpEffectPrefab(this.EditorBuildingEffectNodeArray[i]);
            }
        }


    },

    _showUpEffectPrefab(_target) {

        if (!this.EffectUpAndDown) return;

        let _effectObj = cc.instantiate(this.EffectUpAndDown);

        _effectObj.parent = _target.node;

        _effectObj.y = _target.node.height + 5;

        _effectObj.getChildByName('GoUp').active = true;
        setTimeout(() => {
            // cc.log('删除上升提示', _effectObj.name);

            _effectObj.destroy();
        }, 1000);

    },

    _showDownEffectPrefab(_target) {

        if (!this.EffectUpAndDown) return;

        let _effectObj = cc.instantiate(this.EffectUpAndDown);

        _effectObj.parent = _target.node;

        _effectObj.y = _target.node.height + 5;

        _effectObj.getChildByName('Down').active = true;

        setTimeout(() => {
            // cc.log('删除提示', _effectObj.name);

            _effectObj.destroy();
        }, 1000);

    },

    _AddTargetEffectArray(_targetBuildingsInfo, _targetArray) {
        // cc.log('_targetArray',_targetArray);
        //如果此位置有影响的节点
        let length = _targetArray.length;
        if (length == 0) {
            _targetArray.push(_targetBuildingsInfo);
            // cc.log('影响力接触到的房子1：', _targetBuildingsInfo.buildInfo.id, _targetBuildingsInfo.buildInfo.buildingName);
            return _targetArray;
        }
        for (let i = 0; i < length; i++) {
            if (_targetBuildingsInfo.buildInfo.id === _targetArray[i].buildInfo.id) {
                break;
            }
            //如果遍历完没有存在，则添加进数组
            if (i == length - 1) {
                _targetArray.push(_targetBuildingsInfo);
                // cc.log('影响力接触到的房子2：', _targetBuildingsInfo.buildInfo.id, _targetBuildingsInfo.buildInfo.buildingName);

            }
        }

        return _targetArray;
    },
    _AddEditorBuildinsEffectArray(_targetBuildingsInfo) {
        //如果此位置有影响的节点
        let length = this.EditorBuildingEffectNodeArray.length;
        if (length == 0) {
            this.EditorBuildingEffectNodeArray.push(_targetBuildingsInfo);
            // cc.log('影响力接触到的房子1：', _targetBuildingsInfo.buildInfo.id, _targetBuildingsInfo.buildInfo.buildingName);
            return true;
        }
        for (let i = 0; i < length; i++) {
            if (_targetBuildingsInfo.buildInfo.id === this.EditorBuildingEffectNodeArray[i].buildInfo.id) {
                break;
            }
            //如果遍历完没有存在，则添加进数组
            if (i == length - 1) {
                this.EditorBuildingEffectNodeArray.push(_targetBuildingsInfo);
                // cc.log('影响力接触到的房子2：', _targetBuildingsInfo.buildInfo.id, _targetBuildingsInfo.buildInfo.buildingName);
                return true;
            }
        }

        return false;

    },
    //判断两个建筑是否重叠区域
    //取四个顶点来判定，减少判断o（n）,顶点为false时候，以此回退点判断，直到判断完四边形的tile位置。
    //buildTilePos 对应 Occupy 数组的y值
    //direction 0,自上而下来检测，1自下而上。根据移动来优先判断检测
    //return Boolean
    areTheraOverlappingAreas(_startTiledPos, _occupyingArea, direction = 1) {
        // // let isHas = false;
        // let areaX = _occupyingArea.x;
        // let areaY = _occupyingArea.y;
        // let _length = this.OccupyArray.length;

        // for (let i = 0; i < areaX; i++) {
        //     for (let j = 0; j < areaY; j++) {
        //         let indexTemp = GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x - i, _startTiledPos.y - j));
        //         for (let K = 0; K < _length; K++) {
        //             if (indexTemp == this.OccupyArray[K].y) {
        //                 cc.log('存在',_startTiledPos)
        //                return true;
        //             }
        //         }
        //     }
        // }

        // return false;

        let isHas = false;
        let length = this.OccupyArray.length;
        //判断完四个点
        //判断左上的全部点(0,0)->(0,2) check 0
        for (let i = _occupyingArea.y; i > 0; i--) {
            // let indexTemp = this.WIDHT * (_startTiledPos.y - i + 1) + (_startTiledPos.x - _occupyingArea.x + 1);
            let indexTemp = GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x - _occupyingArea.x + 1, _startTiledPos.y - i + 1));
            for (let j = 0; j < length; j++) {
                if (indexTemp == this.OccupyArray[j].y) {
                    isHas = true;
                    break;
                }
            }
            if (isHas) break;
        }
        //判断右上的全部点(0,0)->(2,0) check 1
        for (let i = _occupyingArea.x; i > 0; i--) {
            // let indexTemp = this.WIDHT * (_startTiledPos.y - _occupyingArea.y + 1) + (_startTiledPos.x - i + 1);
            let indexTemp = GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x - i + 1, _startTiledPos.y - _occupyingArea.y + 1));
            for (let j = 0; j < length; j++) {
                if (indexTemp == this.OccupyArray[j].y) {
                    isHas = true;
                    break;
                }
            }
            if (isHas) break;
        }
        //判断左下的全部点 (0,2)->(2,2) check 2
        for (let i = _occupyingArea.x; i > 0; i--) {
            // let indexTemp = this.WIDHT * (_startTiledPos.y) + (_startTiledPos.x - i + 1);
            let indexTemp = GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x - i + 1, _startTiledPos.y));
            for (let j = 0; j < length; j++) {
                if (indexTemp == this.OccupyArray[j].y) {
                    isHas = true;
                    break;
                }
            }
            if (isHas) break;
        }
        //判断右下的全部点(2,0)->(2,2) check 3
        for (let i = _occupyingArea.y; i > 0; i--) {
            // let indexTemp = this.WIDHT * (_startTiledPos.y - i + 1) + (_startTiledPos.x);
            let indexTemp = GlobalD.TiledMap.getIndex(cc.v2(_startTiledPos.x, _startTiledPos.y - i + 1));
            for (let j = 0; j < length; j++) {
                if (indexTemp == this.OccupyArray[j].y) {
                    isHas = true;
                    break;
                }
            }
            if (isHas) break;
        }
        return isHas;
    },

    //更新人物的深度检测
    onUpdateVertexZFromSlibling(currentNode, pos, isMovex) {

        let selfIndex = GlobalD.TiledMap.getIndex(pos);
        let minIndex = -1;
        let maxIndex = -1;
        //如果人物是x轴移动的
        if (isMovex) {
            //目标位置在其右边或左边
            minIndex = GlobalD.TiledMap.getIndex(cc.v2(pos.x, pos.y - 1));
            maxIndex = GlobalD.TiledMap.getIndex(cc.v2(pos.x, pos.y + 1));
        } else {
            //目标位置在其上面或下面
            minIndex = GlobalD.TiledMap.getIndex(cc.v2(pos.x - 1, pos.y));
            maxIndex = GlobalD.TiledMap.getIndex(cc.v2(pos.x + 1, pos.y));
        }
        let length = this.sliblingIndexArray.length;
        for (let i = 0; i < length; i++) {
            //x轴向移动时候目标位置在其右边，y移动时候目标位置在其上面，反之亦然
            if (selfIndex > this.sliblingIndexArray[i].y && minIndex == this.sliblingIndexArray[i].y) {
                currentNode.parent.insertChild(currentNode, this.sliblingIndexArray[i].x + 1);
            } else if (selfIndex <= this.sliblingIndexArray[i].y && maxIndex == this.sliblingIndexArray[i].y) {
                currentNode.parent.insertChild(currentNode, this.sliblingIndexArray[i].x);
            }
        }
    },

    //计算Z排序
    onUpdateVertexZFromZIndex(_itemNode, tilePos) {
        let lowestZ = -(GlobalD.TiledMap._tiledMap.getMapSize().width + GlobalD.TiledMap._tiledMap.getMapSize().height);
        let currentZ = tilePos.x + tilePos.y;
        let vertexZ = lowestZ + currentZ - 1;

        // this._SortEqualFromZIndex(_itemNode, tilePos);
        _itemNode.zIndex = vertexZ;
        // cc.log('onUpdateVertexZFromZIndex ', _itemNode.getSiblingIndex());

        // _itemNode.parent.sortAllChildren();
        return vertexZ;
    },

    //给同一条线的 ZIndex的节点排序
    _SortEqualFromZIndex(currentNode, tilePos) {

        let length = this.sliblingIndexArray.length;
        // let sliblingTemp = getSiblingIndex();
        let targetIndex = GlobalD.TiledMap.getIndex(cc.v2(tilePos.x + 1, tilePos.y - 1));
        for (let i = 0; i < length; i++) {
            if (targetIndex == this.sliblingIndexArray[i].y) {
                cc.log('targetIndex', this.sliblingIndexArray[i].x, currentNode.getSiblingIndex(), cc.v2(tilePos.x + 1, tilePos.y - 1));
                currentNode.parent.insertChild(currentNode, this.sliblingIndexArray[i].x - 1);
                cc.log('targetIndex', this.sliblingIndexArray[i].x, currentNode.getSiblingIndex(), cc.v2(tilePos.x + 1, tilePos.y - 1));

                break;
            }

        }
    },


    //与建筑物重叠但是不消失
    onUpdateOverlapVertexZ(currentNode, selfNode, isAtTheTop) {
        //如果在最顶部
        if (isAtTheTop) {
            currentNode.parent.insertChild(currentNode, selfNode.getSiblingIndex() + 1);
        } else {
            currentNode.parent.insertChild(currentNode, selfNode.getSiblingIndex());
        }
    },
    //设置需要生产的商品
    onNotificationFactory(reqBuildingsInfo) {
        //通知最近的没有被占用的工厂，分配资源
        let _NearestFactory = null, startIndex = 0;
        //一对一工厂，寻找距离最近的
        if (reqBuildingsInfo.buildInfo._targetBuildingsInfo) {
            // cc.log("商店存在目标:", reqBuildingsInfo.buildInfo._targetBuildingsInfo.buildInfo);
            return;
        }
        for (let i = 0; i < this.FactoryArray.length; i++) {

            //要注意的是，最近的工厂可能没有道路，所以要检测道路，没道路的就去掉
            if (!this.onCheckForRoads(reqBuildingsInfo, this.FactoryArray[i])) continue;

            //如果工厂不存在商店
            if (!this.FactoryArray[i].buildInfo.isItStopOperation
                && !this.FactoryArray[i].buildInfo._targetBuildingsInfo) {
                _NearestFactory = this.FactoryArray[i];
                startIndex = i;
                break;
            }
        }
        // cc.log("商店不存在目标:", reqBuildingsInfo.buildInfo);
        if (_NearestFactory && startIndex + 1 < this.FactoryArray.length) {
            for (let i = startIndex + 1; i < this.FactoryArray.length; i++) {
                //如果工厂停运，并且存在商店
                if (this.FactoryArray[i].buildInfo.isItStopOperation || this.FactoryArray[i].buildInfo._targetBuildingsInfo) {
                    // cc.log('被占用了！');
                    continue;
                }
                // cc.log('检测最近的工厂',_NearestFactory);
                //要注意的是，最近的工厂可能没有道路，所以要检测道路，没道路的就去掉
                if (!this.onCheckForRoads(reqBuildingsInfo, this.FactoryArray[i])) continue;

                if (reqBuildingsInfo.node.position.sub(_NearestFactory.node.position).mag() >
                    reqBuildingsInfo.node.position.sub(this.FactoryArray[i].node.position).mag()) {
                    _NearestFactory = this.FactoryArray[i];
                }
            }
        }
        if (_NearestFactory) {
            // cc.log('_NearestFactory == ',reqBuildingsInfo.buildInfo.id, _NearestFactory.buildInfo.startTilePos);
            // cc.log('商店设置并通知工厂！');
            //设置商店的的目标为工厂
            reqBuildingsInfo.buildInfo._targetBuildingsInfo = _NearestFactory;
            //如果是最近的工厂，并且没有被占用的,
            //设置工厂对应的商店建筑
            _NearestFactory.buildInfo._goods = reqBuildingsInfo.buildInfo._goods;
            _NearestFactory.buildInfo._targetBuildingsInfo = reqBuildingsInfo;
            //添加需要工作的工厂
        } else {
            // cc.log('请建造工厂！');
        }
    },

    //检测两个建筑是否通路
    onCheckForRoads(selfBuildingsInfo, targetBuildingsInfo) {

        //自己的节点
        let selfPositionArray = selfBuildingsInfo.buildInfo._gotoPosistion;
        let selfLength = selfPositionArray.length;

        //目标的节点
        let targetPositionArray = targetBuildingsInfo.buildInfo._gotoPosistion;
        let targetLength = targetPositionArray.length;
        // cc.log('检测道路', targetBuildingsInfo.buildInfo.startTilePos,
        // selfBuildingsInfo.buildInfo.startTilePos);
        for (let i = 0; i < selfLength; i++) {
            for (let j = 0; j < targetLength; j++) {
                //如果存在道路，返回true；
                if (this._getPath(selfPositionArray[i], targetPositionArray[j])) {
                    // cc.log('存在道路', targetBuildingsInfo.buildInfo.startTilePos);
                    return true;
                }
            }
        }
        // cc.log('不存在道路', targetBuildingsInfo.buildInfo.startTilePos);
        return false;

    },
    //获得寻路路径
    _getPath(start, end) {
        AStar.setStart(start);
        let getPath = AStar.pathFind(start.x, start.y, end.x, end.y);
        // //路径取反
        // getPath.reverse();
        if (getPath.length == 0) {
            return false;
        } else {
            // if (this._path.length == 0 || this._path.length > getPath.length) {
            //     this._path = getPath;
            // }
            return true;
        }
    },

    // 把工人添加进数组
    onSetWorkerArray(item) {
        // cc.log("onSetWorkerArray = ", item);
        this.WorkerArray.push(item);
    },
    // 更新工人数组
    // onUpdateWorkerArray(item) {
    //     // cc.log("onUpdateSalesMaterialsArray1",this.MaterialsArray);
    //     for (let i = 0; i < this.WorkerArray.length; i++) {
    //         if (item.characterInfo.id == this.WorkerArray[i].characterInfo.id) {
    //             this.WorkerArray.splice(i, 1, item);
    //         }
    //     }
    // },
    //移除工人对象
    onRemoveAIFromWorkerArray(index) {
        this.WorkerArray[index].onWorkerRemoveMyself();
        this.WorkerArray.splice(index, 1);
        //移除工人信息记录的信息
        this.WorkerInitInfoArray.splice(index, 1);
        GlobalD.GameData.SetWorkerCharacterInfoArray(this.WorkerInitInfoArray);

    },

    //把工人信息记录起来
    onAddWorkerCharacterInfoToArray(_characterInfo, _isInit = false) {
        this.WorkerInitInfoArray.push(_characterInfo);
        //如果不是初始化的数据，就记录到内存中
        if (!_isInit)
            GlobalD.GameData.SetWorkerCharacterInfoArray(this.WorkerInitInfoArray);
    },
    // 更新工人数组
    onUpdateWorkerCharacterInfoToArray(_characterInfo) {
        // cc.log('更新人工数组', _characterInfo);
        for (let i = 0; i < this.WorkerInitInfoArray.length; i++) {
            if (_characterInfo.id == this.WorkerInitInfoArray.id) {
                this.WorkerInitInfoArray.splice(i, 1, _characterInfo);
                GlobalD.GameData.SetWorkerCharacterInfoArray(this.WorkerInitInfoArray);
                break;
            }
        }
    },
    AllowFoodTrade(event, customEventData) {
        if (customEventData == '0') {
            this.FoodTradeState.getComponent(cc.Sprite).spriteFrame = this.NoAllowPrefabs;
            GlobalD.GameData.SetFoodTradeState(0);
            this.ClosingAllSales(this.FarmlandBuildingArray);
        }
        else {
            this.FoodTradeState.getComponent(cc.Sprite).spriteFrame = this.AllowPrefabs;
            GlobalD.GameData.SetFoodTradeState(1);
            this.OpenAllSale(this.FarmlandBuildingArray);
        }
    },
    AllowWoodTrade(event, customEventData) {
        if (customEventData == '0') {
            this.WoodTradeState.getComponent(cc.Sprite).spriteFrame = this.NoAllowPrefabs;
            GlobalD.GameData.SetWoodTradeState(0);
            this.ClosingAllSales(this.TimberYardBuildingArray);
        }
        else {
            this.WoodTradeState.getComponent(cc.Sprite).spriteFrame = this.AllowPrefabs;
            GlobalD.GameData.SetWoodTradeState(1);
            this.OpenAllSale(this.TimberYardBuildingArray);
        }
    },
    AllowMineralTrade(event, customEventData) {
        if (customEventData == '0') {
            this.MineralTradeState.getComponent(cc.Sprite).spriteFrame = this.NoAllowPrefabs;
            GlobalD.GameData.SetMineralTradeState(0);
            this.ClosingAllSales(this.MiningPitBuildingArray);
        }
        else {
            this.MineralTradeState.getComponent(cc.Sprite).spriteFrame = this.AllowPrefabs;
            GlobalD.GameData.SetMineralTradeState(1);
            this.OpenAllSale(this.MiningPitBuildingArray);
        }
    },

    onUpdatePersonInventory(_type, _num) {

        switch (_type) {
            case reGameStates.BuildType.Farmland:
                this.cropContentNum += _num;
                this._ManageUIScript.cropContent.string = this.cropContentNum;
                break;
            case reGameStates.BuildType.MiningPit:

                this.mineContentNum += _num;
                this._ManageUIScript.mineContent.string = this.mineContentNum;
                break;
            case reGameStates.BuildType.TimberYard:
                this.woodContentNum += _num;
                this._ManageUIScript.woodContent.string = this.woodContentNum;
                break;

        }


    },

    // //开放所有销售
    OpenAllSale(AArray) {
        for (let i = 0; i < AArray.length; i++) {
            AArray[i].buildInfo.isItSaleable = true;
            AArray[i].node.getComponent("buildingTips").stopBoard();
        }
    },
    // //关闭所有销售
    ClosingAllSales(AArray) {
        for (let i = 0; i < AArray.length; i++) {
            AArray[i].buildInfo.isItSaleable = false;
        }
    },
    onResetScene() {
        //从新开始游戏
        cc.director.loadScene("MyCityScene");
    },
    //获取当前编辑建筑
    onGetCurrentBuildingTarget() {
        return this.currentEditorBuilding;
    },
    onSetCurrentBuildingTarget(_target) {
        this.currentEditorBuilding = _target;
    },
    onClearCurrentBuildingTarget() {
        this.currentEditorBuilding = null
    },

    //创建不同的公路样式
    onCreateDifferentRoadStyles(data) {

        let _StaylesAndIndex = new highwayInfo();
        _StaylesAndIndex.highwayInfoId = data._buildId;
        _StaylesAndIndex.highwayInfoType = data._highwayType;// reGameStates.HighwayType.moveX;
        _StaylesAndIndex.highwayInfoIndex = data._roadIndex;
        this.AllHighwayStylesAndIndex.push(_StaylesAndIndex);

        data._hightwayNode.getComponent('HighwayInfo').onChangeHighwayStyles(data._highwayType);

    },
    //更新公路样式
    onUpdateDifferentRoadStyles(data) {

        let _length = this.AllHighwayStylesAndIndex.length;
        for (let i = 0; i < _length; i++) {

            if (data._roadIndex == this.AllHighwayStylesAndIndex[i].highwayInfoIndex) {
                this.AllHighwayStylesAndIndex[i].highwayInfoType = data._highwayType;
                break;
            }
        }
    },



});
