cc.Class({

    extends: cc.Component,
    editor: {
        requireComponent: cc.TiledMap
    },

    properties: {

        Show: {
            default: null,
            type: cc.Label,
        },

        DrawPathNode: cc.Node,

        //场景树木的预制
        BarrierPrefab: cc.Prefab,

        //场景栏杆的预制
        RailingXPrefab: cc.Prefab,
        RailingYPrefab: cc.Prefab,

        MyMapNode: cc.Node,

        //没有激活的节点，也就是还没有深度排序的
        MyMapNoActivationNode: cc.Node,
        //画网格
        isDraw: false,


        //记录道路的index
        _highwayIndex: {
            default: [],
            type: [cc.Integer],
            visible: false,
        },
        //记录道路的Node节点
        _highwayNodes: {
            default: [],
            type: [cc.Node],
            visible: false,
        },

        _tiledMap: {
            default: null,
            type: cc.TiledMap,
            serializable: false,
            visible: false,
        },

        // _IndexFromTiledPos: {
        //     default: [],
        //     type: [cc.Integer],
        //     serializable: false,
        //     visible: false,
        // },

        DynamicMinBoundary: {
            default: cc.v2(),
            visible: false,
            tooltip: '建筑可建区域边界值，针对上面两边边界越界',
        },
    },

    // use this for initialization
    onLoad: function () {
        //初始化TiledMap全局变量
        GlobalD.TiledMap = this;
        this._tiledMap = this.node.getComponent(cc.TiledMap);
    },

    start: function () {

        if (this.isDraw && this.DrawPathNode) {
            //画网格
            for (let i = 0; i < this._tiledMap.getMapSize().width + 1; i++) {
                var tilesPos1 = cc.v2(i, 0);
                var pos1 = this._locationFromtilePos(tilesPos1);
                var tilesPos2 = cc.v2(i, this._tiledMap.getMapSize().width);
                var pos2 = this._locationFromtilePos(tilesPos2);
                this.DrawPathNode.getComponent('Draw').onDrawFromTwoPoints(pos1, pos2);
            }
            for (let j = 0; j < this._tiledMap.getMapSize().width + 1; j++) {
                var tilesPos1 = cc.v2(0, j);
                var pos1 = this._locationFromtilePos(tilesPos1);
                var tilesPos2 = cc.v2(this._tiledMap.getMapSize().width, j);
                var pos2 = this._locationFromtilePos(tilesPos2);
                this.DrawPathNode.getComponent('Draw').onDrawFromTwoPoints(pos1, pos2);
            }
            this.DrawPathNode.getComponent('Draw').onStroke();
        }


    },


    //初始化TiledMap的障碍物
    onInitSolid() {
        //设置地图障碍物
        //隐藏地图树木
        // this._tiledMap.getLayer('Trees').enabled = false;
        var objectGroup = this._tiledMap.getObjectGroup('Barrier');
        let objects = objectGroup.getObjects();
        //-1代表障碍物
        let _buildIdSolid = -1;
        let length = objects.length;
        for (let i = 0; i < length; i++) {
            let areaX = objects[i].areaX;
            let areaY = objects[i].areaY;
            for (let j = 0; j < areaX; j++) {
                for (let k = 0; k < areaY; k++) {
                    let _tilePos = cc.v2(objects[i].startTiledX + j, objects[i].startTiledY + k);
                    let solidIndex = this.getIndex(_tilePos);
                    // this.sliblingIndexArray.push(cc.v2(item.node.getSiblingIndex(), buildIndex));
                    //地图设置障碍物
                    AStar.setMapSolid(_tilePos.x, _tilePos.y, 1);

                    // if (objects[i].name == 'TreeBarrier') {
                    //     let BarrierTemp = cc.instantiate(this.BarrierPrefab);
                    //     BarrierTemp.parent = this.MyMapNode;
                    //     let tiledTile = BarrierTemp.addComponent('TiledTile');
                    //     tiledTile.x = _tilePos.x;
                    //     tiledTile.y = _tilePos.y;

                    //     GlobalD.game.onUpdateVertexZFromZIndex(BarrierTemp, _tilePos);
                    // }

                    let occupyTemp = cc.v2(_buildIdSolid, solidIndex);
                    GlobalD.game.OccupyArray.push(occupyTemp);
                    // console.log('objectGroup  objects= ',objects[i].id,targetPosition);
                }
            }

        }


        // //栏杆对象
        // let _buildIdRailing = -2;
        // let RailingXLayer = this._tiledMap.getLayer('RailingX');
        // let RailingYLayer = this._tiledMap.getLayer('RailingY');
        // RailingXLayer.enabled = false;
        // RailingYLayer.enabled = false;
        // // let RailingLayer = this._tiledMap.getLayer('Railing');
        // // RailingLayer.enabled = false;

        // for (let i = 0; i < 32; i++) {
        //     for (let j = 0; j < 32; j++) {
        //         let _tilesPos = cc.v2(i, j);
        //         if (RailingXLayer.getTileGIDAt(_tilesPos)) {
        //             let solidIndex = this.getIndex(_tilesPos);
        //             let railingXTemp = cc.instantiate(this.RailingXPrefab);
        //             railingXTemp.parent = this.MyMapNoActivationNode;
        //             let tiledTile = railingXTemp.addComponent('TiledTile');
        //             tiledTile.x = _tilesPos.x;
        //             tiledTile.y = _tilesPos.y;
        //             let occupyTemp = cc.v2(_buildIdRailing, solidIndex);
        //             GlobalD.game.OccupyArray.push(occupyTemp);


        //         }
        //         if (RailingYLayer.getTileGIDAt(_tilesPos)) {
        //             let solidIndex = this.getIndex(_tilesPos);
        //             let railingYTemp = cc.instantiate(this.RailingYPrefab);
        //             railingYTemp.parent = this.MyMapNoActivationNode;
        //             let tiledTile = railingYTemp.addComponent('TiledTile');
        //             tiledTile.x = _tilesPos.x;
        //             tiledTile.y = _tilesPos.y;
        //             let occupyTemp = cc.v2(_buildIdRailing, solidIndex);
        //             GlobalD.game.OccupyArray.push(occupyTemp);

        //         }

        //         if (RailingLayer.getTileGIDAt(_tilesPos)) {
        //             let railingYTemp = cc.instantiate(this.RailingYPrefab);
        //             railingYTemp.parent = this.MyMapNoActivationNode;
        //             let tiledTile = railingYTemp.addComponent('TiledTile');
        //             tiledTile.x = _tilesPos.x;
        //             tiledTile.y = _tilesPos.y;
        //         }
        //     }
        // }
    },
    //根据tiled坐标清除指定栏杆
    onClearRailingFromTilesPos(_regionIndex) {
        // cc.log('onClearRailingFromTilesPos', _regionIndex);

        var objectGroup = this._tiledMap.getObjectGroup('Region');
        let objects = objectGroup.getObjects();
        //-1代表障碍物
        let _buildIdRailing = -2;
        let length = objects.length;
        for (let i = 0; i < length; i++) {
            if (objects[i].name == 'Region' + _regionIndex) {
                // cc.log('清除区域是：', objects[i]);
                let areaX = objects[i].areaX;
                let areaY = objects[i].areaY;
                let startX = objects[i].startTiledX;
                let startY = objects[i].startTiledY;
                for (let j = 0; j < areaX; j++) {
                    for (let k = 0; k < areaY; k++) {
                        // cc.log('清除区域是2：', startX,startY);

                        let _tilePos = cc.v2(startX + j, startY + k);
                        let solidIndex = this.getIndex(_tilePos);

                        //清除栏杆节点
                        let children = this.MyMapNoActivationNode.children;
                        let length = children.length;
                        for (let i = 0; i < length; i++) {
                            if (cc.isValid(children[i]) && children[i].getComponent('TiledTile').x == _tilePos.x
                                && children[i].getComponent('TiledTile').y == _tilePos.y) {
                                children[i].destroy();
                            }
                        }

                        //清除占位信息
                        let occupyArray = GlobalD.game.OccupyArray;
                        let length1 = occupyArray.length;
                        for (let i = length1 - 1; i >= 0; i--) {
                            if (occupyArray[i].y == solidIndex && occupyArray[i].x == _buildIdRailing) {
                                GlobalD.game.OccupyArray.splice(i, 1);
                            }
                        }
                    }
                }

            }


        }


    },

   

    //根据屏幕坐标获取瓷砖块坐标
    _tilePosFromLocation(location) {
        //mapsize 目前是50*50
        var mapSize = this._tiledMap.getMapSize();
        //tilesize 目前是100*50
        var tileSize = this._tiledMap.getTileSize();

        // 触摸的位置信息必须减去瓷砖地图的位置信息,因为地图的位置可能在滚动变化
        var pos = new cc.v2();
        pos.x = location.x - this._tiledMap.node.getPosition().x;
        pos.y = location.y - this._tiledMap.node.getPosition().y;
        var halfMapWidth = mapSize.width * 0.5;
        var mapHeight = mapSize.height;
        var tileWidth = tileSize.width;
        var tileHeight = tileSize.height;
        //偏移量
        var tilePosDiv = cc.v2(pos.x / tileWidth, pos.y / tileHeight);
        var inverseTileY = mapHeight - tilePosDiv.y;
        // 将得到的计算结果转换成 int,以确保得到的是整数
        var posX = parseInt(inverseTileY + tilePosDiv.x - halfMapWidth);
        var posY = parseInt(inverseTileY - tilePosDiv.x + halfMapWidth);//****** */Anchor

        //外围不可活动区域的瓷砖块数
        var borderSize = 0;
        //最小活动区域
        var playableAreaMin = cc.v2(borderSize, borderSize);
        var playableAreaMax = cc.v2(this._tiledMap.getMapSize().width - 1 - borderSize, this._tiledMap.getMapSize().height - 1 - borderSize);



        let DeMinX = this.DynamicMinBoundary.x > 1 ? this.DynamicMinBoundary.x - 1 : 0;
        let DeMinY = this.DynamicMinBoundary.y > 1 ? this.DynamicMinBoundary.y - 1 : 0;

        // 确保坐标在MAP范围内
        posX = Math.max(playableAreaMin.x + DeMinX, posX);
        posX = Math.min(playableAreaMax.x, posX);
        posY = Math.max(playableAreaMin.y + DeMinY, posY);
        posY = Math.min(playableAreaMax.y, posY);

        // this.Show.string = "(" + posX + "," + posY + ")";
        return cc.v2(posX, posY);
    },

    //把tile坐标转换成屏幕坐标
    _locationFromtilePos(tilePos) {
        var halfMapWidth = this._tiledMap.getMapSize().width * 0.5;
        var mapHeight = this._tiledMap.getMapSize().height;
        var tileWidth = 0.0;
        var tileHeight = 0.0;
        tileWidth = this._tiledMap.getTileSize().width;
        tileHeight = this._tiledMap.getTileSize().height;
        var tilePosDiv = new cc.v2();
        var pos = new cc.v2();
        tilePosDiv.y = mapHeight - (tilePos.x + tilePos.y) / 2;
        tilePosDiv.x = (tilePos.x - tilePos.y) / 2 + halfMapWidth;//***** */Anchor
        pos.x = tilePosDiv.x * tileWidth;
        pos.y = tilePosDiv.y * tileHeight;

        var outpos = new cc.v2();
        outpos.x = pos.x + this._tiledMap.node.getPosition().x;
        outpos.y = pos.y + this._tiledMap.node.getPosition().y;
        return outpos;
    },





    //获取tilePos坐标对应的图块居中的位置
    getblockInTheMiddle(tilePos) {
        let getOriPos = this._locationFromtilePos(tilePos);
        // 图块的大小是（165,96）
        //我们计算的点事顶点为起始点，所以y轴要减去图块的一半。
        return cc.v2(getOriPos.x, getOriPos.y - 48);
    },
    //获取tilePos坐标对应的图块居中的位置
    _getTheMiddleLocationFromtilePos(tilePos) {
        let getOriPos = this._locationFromtilePos(tilePos);
        // 图块的大小是（165,96）
        //我们计算的点事顶点为起始点，所以y轴要减去图块的一半。
        return cc.v2(getOriPos.x, getOriPos.y - 48);
    },
    /**
   * 通过指定的 tile 坐标获取对应的 TiledTile。 <br/>
   * @method getTiledTileAt
   * @param {Integer} x
   * @param {Integer} y
   * @param {[TiledTile]} tiledsArray
   * @return {TiledTile}
   */
    getTiledTileAt(x, y, tiledsArray) {
        let index = Math.floor(x) + Math.floor(y) * this._tiledMap.getMapSize().width;
        let tile = null;
        if (tiledsArray) {
            tile = tiledsArray[index];
        } else {//如果不存在，默认获取已保存的数组
            tile = this._highwayIndex[index];
        }

        cc.log('tile', tile);
        if (tile) {
            return tile;
        } else {
            return false;
        }
    },
    /** 
       * 替换为指定的 TiledTile。
       * @method setTiledTile
       * @param {TiledTile} tiledTile
       * @param {[TiledTile]} tiledsArray
       * @return {TiledTile}
       */
    setTiledTile(tiledTile, tiledsArray) {
        let index = Math.floor(tiledTile.x) + Math.floor(tiledTile.y) * this._tiledMap.getMapSize().width;
        let node = cc.instantiate(tiledTile.node);

        if (tiledsArray) {
            return tiledsArray[index] = node.getComponent('TiledTile');
        } else {//如果不存在，默认获取已保存的数组
            return this._highwayIndex[index] = node.getComponent('TiledTile');
        }


    },

    /** 
     * 存储一个index 值到目标数组。analyticalX 存在的话，保存对应的x值
     * @method setIndexArray
     * @param {vec2} vector2
     * @param {[IndexArray]} indexArray
     * @return {IndexArray}
     */
    setIndexArray(vector2, indexArray) {
        let index = Math.floor(vector2.x) + Math.floor(vector2.y) * this._tiledMap.getMapSize().width;
        indexArray.push(index);
        return indexArray;

    },


    /** 
 * 计算一个index 并返回
 * @method getIndex
 * @param {vec2} vector2
 * @return {index}
 */
    getIndex(vector2) {
        let index = Math.floor(vector2.x) + Math.floor(vector2.y) * this._tiledMap.getMapSize().width;
        return index;

    },


    /** 
       * 判断是否存在一个值在目标数组。
       * @method getIndexArrayAt
       * @param {vec2} vector2
       * @param {[IndexArray]} indexArray
       * @return {Boolean}
       */
    getIndexArrayAt(vector2, indexArray) {
        let index = Math.floor(vector2.x) + Math.floor(vector2.y) * this._tiledMap.getMapSize().width;

        let length = indexArray.length;
        // let isHas = false;
        for (let i = 0; i < length; i++) {
            if (index == indexArray[i]) {
                // isHas = true;
                // break;
                return true;
            }
        }

        return false;

    },

    /** 
     * 解析一个indexArray数组。
     * @method analyticalIndexArrayData
     * @param {[IndexArray]} indexArray
     * @return {[cc.Vec2]]}
     */
    analyticalIndexArrayData(indexArray) {

        let width = this._tiledMap.getMapSize().width;
        let length = indexArray.length;
        let out = [];
        for (let i = 0; i < length; i++) {
            //向下取整
            let Y = Math.floor(indexArray[i] / width);
            //取余数
            //cc.log('2130%50 ============',2499%50, Math.floor(2499/50));
            let X = indexArray[i] % width;//indexArray[i] - Y*width;

            out.push(new cc.Vec2(X, Y));
        }

        return out;

    },

    /** 
  * 解析一个index。
  * @method analyticalIndexArrayData
  * @param {Index} index
  * @return {[cc.Vec2]]}
  */
    analyticalIndexData(index) {
        let width = this._tiledMap.getMapSize().width;
        //向下取整
        let Y = Math.floor(index / width);
        //取余数
        let X = index % width;//index[i] - Y*width;
        return new cc.Vec2(X, Y);

    }
});
