
const Constants = require('Constants');
var reGameStates = require('GameStates');
cc.Class({
    extends: cc.Component,

    properties: {
        HighWay: {
            // ATTRIBUTES:
            default: [],        // The default value will be used only when the component attaching
            // to a node for the first time
            type: cc.Prefab, // optional, default is typeof default
            serializable: true,   // optional, default is true
        },

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

        //触摸一开始的位置
        _touchPosition: {
            default: new cc.Vec2(),
            visible: false,
            serializable: false
        },

        _StartPosition: {
            default: new cc.Vec2(),
            serializable: false
        },

        _EndPosition: {
            default: new cc.Vec2(),
            serializable: false
        },
        //上一个位置
        _LastPosition: {
            default: new cc.Vec2(),
            serializable: false
        },

        _highPath: {
            default: [],
            type: [cc.Node],
            visible: false,
        },

        selectTouch: {
            default: null,
            type: cc.Node,
        },
        buildingTouch: {
            default: null,
            type: cc.Node,
        },

        //如果只初始化一次的话
        // _isInitOnce: {
        //     default: false,
        //     visible: false,
        // }

        //如果自动移动
        isAutoMove: { default: false, visible: false },

        //是否创建斑马线
        isCreateZebra: { default: true, visible: false },
        // createStartTiledPos: null,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.highwayPool = new cc.NodePool();
        let initCount = 50;
        for (let i = 0; i < initCount; ++i) {
            let highway = cc.instantiate(this.HighWay[0]); // 创建节点
            this.highwayPool.put(highway); // 通过 putInPool 接口放入对象池
        }
    },

    start() {
        var self = this;
        self._MainCamera = GlobalD.game.MainCamera;
        self._tiledMap = GlobalD.TiledMap._tiledMap;

        //获取对应的地图层级
        this.buildLayer = this._tiledMap.getLayer('BuildsHighway');

        self._game = GlobalD.game;

        //初始化时候设置一下位置
        //后面只要点击生成铺路就需要重置一下
        let startTiledPos = GlobalD.TiledMap._tilePosFromLocation(self.node.getPosition());
        let startEndPos = GlobalD.TiledMap._getTheMiddleLocationFromtilePos(startTiledPos);
        self.node.setPosition(startEndPos);

        //记录一下初始位置
        // self.createStartTiledPos = startTiledPos;

        self.node.on(cc.Node.EventType.TOUCH_MOVE, function (event) {



            // cc.log(event.touch.getDelta());
            GlobalD.GameControl._isBuildingMove = true;

            var delta = event.touch.getDelta();


            self._touchPosition.x += delta.x / self._MainCamera.zoomRatio;
            self._touchPosition.y += delta.y / self._MainCamera.zoomRatio;
            // self.node.setPosition(self._touchPosition);

            let tiledPos = GlobalD.TiledMap._tilePosFromLocation(self._touchPosition);
            //不相等的时候才绘制
            if (tiledPos.sub(self._EndPosition).mag() != 0) {

                // cc.log('tiledPostiledPostiledPos', tiledPos,self._EndPosition)
                self._EndPosition = tiledPos;

                if (self.buildingTouch.active) {
                    if (self._StartPosition.x == self._EndPosition.x
                        || self._StartPosition.y == self._EndPosition.y) {
                        self.onCancelCreateHighway();

                        self.onBuildingFromPath(self._StartPosition, self._EndPosition);

                        let endPos = GlobalD.TiledMap._getTheMiddleLocationFromtilePos(tiledPos);
                        self.node.setPosition(endPos);
                    }

                } else {
                    let endPos = GlobalD.TiledMap._getTheMiddleLocationFromtilePos(tiledPos);

                    self.node.setPosition(endPos);
                }


            }

            //开启编辑UI
            // self._game._ManageUIScript.onEditorialBuildings(self.node);

        }, self.node);

        self.node.on(cc.Node.EventType.TOUCH_START, function (event) {
            // var touches = event.getTouches();
            // var touchLoc = touches[0].getLocation();
            self.isMoving = true;
            // if(!self._isInitOnce){
            //     self._StartPosition = GlobalD.TiledMap._tilePosFromLocation(self.node.getPosition());
            // }
            //如果要选框就去掉这里
            // self.onInitStartPosition();

            self._touchPosition = self.node.getPosition();

            // cc.log('self._StartPosition', self._StartPosition, self._touchPosition);



        }, self.node);

        self.node.on(cc.Node.EventType.TOUCH_END, function (event) {

            //起始触摸位置
            GlobalD.GameControl._isBuildingMove = false;
        }, self.node);
        self.node.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {

            //起始触摸位置
            GlobalD.GameControl._isBuildingMove = false;
        }, self.node);

    },

    // 自动移动,在ManagerControl 里面调用
    onAutoMove(delta) {

        this.isAutoMove = true;

        let self = this;
        self._touchPosition.x += delta.x;
        self._touchPosition.y += delta.y;
        let tiledPos = GlobalD.TiledMap._tilePosFromLocation(self._touchPosition);
        //不相等的时候才绘制
        if (tiledPos.sub(self._EndPosition).mag() != 0) {
            self._EndPosition = tiledPos;
            if (self.buildingTouch.active) {
                if (self._StartPosition.x == self._EndPosition.x
                    || self._StartPosition.y == self._EndPosition.y) {
                    self.onCancelCreateHighway();
                    self.onBuildingFromPath(self._StartPosition, self._EndPosition);
                    let endPos = GlobalD.TiledMap._getTheMiddleLocationFromtilePos(tiledPos);
                    self.node.setPosition(endPos);
                }
            } else {
                let endPos = GlobalD.TiledMap._getTheMiddleLocationFromtilePos(tiledPos);
                self.node.setPosition(endPos);
            }
        }
    },
    onCancleAutoMove() {
        this.isAutoMove = false;

    },

    //隐藏时候铺路的状态
    onHideSetTouchState() {
        if (this.create1 || this.create2) {
            let _cancel1 = this.selectTouch.getChildByName('Cancel').getComponent(cc.Button);
            let _cancel2 = this.buildingTouch.getChildByName('Cancel').getComponent(cc.Button);
            _cancel1.interactable = true;
            _cancel1.enableAutoGrayEffect = false;
            _cancel2.interactable = true;
            _cancel2.enableAutoGrayEffect = false;
            if (this.create1)
                this.create1.stopAllActions();
            if (this.create2)
                this.create2.stopAllActions();
        }

    },
    //新手教程时候设置铺路状态
    onSetTouchState() {

        if (!task.virtualShadowPos) return;

        if (this.selectTouch.active) {
            let _cancel = this.selectTouch.getChildByName('Cancel').getComponent(cc.Button);
            _cancel.interactable = false;
            _cancel.enableAutoGrayEffect = true;
            this.create1 = this.selectTouch.getChildByName('Create');
            this.create1.stopAllActions();
            var s = cc.sequence(cc.scaleTo(0.6, 0.9), cc.scaleTo(0.9, 0.6));
            var repeat = cc.repeatForever(s);
            this.create1.runAction(repeat);

        } else {
            let _cancel = this.buildingTouch.getChildByName('Cancel').getComponent(cc.Button);
            _cancel.interactable = false;
            _cancel.enableAutoGrayEffect = true;
            this.create2 = this.buildingTouch.getChildByName('Create');
            this.create2.stopAllActions();
            var s = cc.sequence(cc.scaleTo(0.6, 0.9), cc.scaleTo(0.9, 0.6));
            var repeat = cc.repeatForever(s);
            this.create2.runAction(repeat);
        }


    },
    //切换状态
    onSwitchBuidingTouch() {

        //如果是新手指引的情况下,需要显示对应的遮挡模板
        if (task.virtualShadowPos) {
            let _curentTiled = GlobalD.TiledMap._tilePosFromLocation(this.node.getPosition());;
            if (_curentTiled.sub(task.virtualShadowPos).mag() !== 0) {

                // console.error('没有移动到指定位置：', _curentTiled, task.virtualShadowPos);
                cc.loader.loadRes('resUI/ShowNotEnoughMoney', function (err, texture) {
                    var prefab = cc.instantiate(texture);
                    prefab.getComponent('ShowNotEnoughMoney').Text('请移动到虚影的<起始>位置！');
                    cc.find('Canvas').getChildByName('UICamera').addChild(prefab);
                }.bind(this));
                return;
            } else {
                // console.log(task.virtualTarget);
                let _taskHighway = task.getTaskNode('taskPrefabTiledTileHighway');

                if (_taskHighway) {
                    _taskHighway.getChildByName('Arrow').active = false;
                    _taskHighway.getChildByName('Hand1').active = true;
                }
            }
        }


        this.selectTouch.active = false;
        this.buildingTouch.active = true;

        //设置一下状态
        this.onSetTouchState();
        //设置斑马线
        this.isCreateZebra = true;
        // this._isInitOnce = true;
        // 记录编辑状态时候的初始位置
        this.onInitStartPosition();
    },
    // 重置下初始位置
    onInitStartPosition() {
        this._StartPosition = GlobalD.TiledMap._tilePosFromLocation(this.node.getPosition());

        // //如果是新手指引的情况下,需要显示对应的遮挡模板
        // if (task.isMushBuildState) {
        //     let _confirmButton = this.HighwayBuildingNode.getChildByName('SelectTouch').getChildByName('Create');
        //     let _taskNodes = [];
        //     _taskNodes.push(_confirmButton);
        //     task.onInitTaskMask(_taskNodes);
        // }
    },
    //相同一个点的时候点的时候
    onBuildingFromPathEqual(tiledPos) {
        // cc.log('onBuildingFromPathEqual');
        if (!GlobalD.TiledMap.getTiledTileAt(tiledPos.x, tiledPos.y)) {

            let highwayTemp = null;

            if (this.highwayPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                highwayTemp = this.highwayPool.get();
            } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
                highwayTemp = cc.instantiate(this.HighWay[0]);
                // cc.log('重新创建')
            }
            highwayTemp.parent = this.buildLayer.node;
            let tiledTile = highwayTemp.addComponent('TiledTile');
            tiledTile.x = tiledPos.x;
            tiledTile.y = tiledPos.y;

        }
    },

    //不同点的时候
    //在路径上面创建公路预制
    onBuildingFromPath(start_tiledPos, end_tiledPos) {

        //移动了就不创建斑马线了
        this.isCreateZebra = false;

        let _highwayStart = null;
        let isChangeHighwayStart = false;

        let spawnPos = 0;

        //最后一个点判断是否重合
        let EndPos = [];
        let tempMaxY = 0;
        let tempMinY = 0;
        if (start_tiledPos.y > end_tiledPos.y) {
            tempMaxY = start_tiledPos.y;
            tempMinY = end_tiledPos.y;
        } else {
            tempMaxY = end_tiledPos.y;
            tempMinY = start_tiledPos.y;
        }
        let tempY = end_tiledPos.y - start_tiledPos.y;
        for (let i = tempMinY; i <= tempMaxY; i++) {
            spawnPos = cc.v2(start_tiledPos.x, i);
            //写入index 数组
            GlobalD.TiledMap.setIndexArray(spawnPos, EndPos);

            // if (!GlobalD.TiledMap.getTiledTileAt(spawnPos.x, spawnPos.y)) 
            {
                // cc.log('绘制Y', spawnPos)
                let highwayTemp = null;

                if (this.highwayPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                    highwayTemp = this.highwayPool.get();
                } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
                    highwayTemp = cc.instantiate(this.HighWay[0]);
                    // cc.log('重新创建')
                }

                highwayTemp.parent = this.buildLayer.node;
                let tiledTile = highwayTemp.addComponent('TiledTile');
                tiledTile.x = spawnPos.x;
                tiledTile.y = spawnPos.y;

                if (GlobalD.game.getManageGameIndexArrayAt(tiledTile)) {
                    highwayTemp.getComponent('TipSprite').onSetRedSpriteFrame();
                }
                //没有重复的时候

                // cc.log('设置Y值:', reGameStates.HighwayType.moveY);
                highwayTemp.getComponent('HighwayInfo').onChangeHighwayStyles(reGameStates.HighwayType.moveY);

                //记录第一个临时节点
                if (!_highwayStart) {
                    _highwayStart = highwayTemp;
                }
            }
        }



        let tempMaxX = 0;
        let tempMinX = 0;
        if (start_tiledPos.x > end_tiledPos.x) {
            tempMaxX = start_tiledPos.x;
            tempMinX = end_tiledPos.x;
        } else {
            tempMaxX = end_tiledPos.x;
            tempMinX = start_tiledPos.x;
        }

        for (let i = tempMinX; i <= tempMaxX; i++) {
            spawnPos = cc.v2(i, start_tiledPos.y + tempY);
            //这里判断最大最小点是否重合
            if (!GlobalD.TiledMap.getIndexArrayAt(spawnPos, EndPos)) {
                // cc.log('绘制x', spawnPos)
                let highwayTemp = null;
                if (this.highwayPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                    highwayTemp = this.highwayPool.get();
                } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
                    highwayTemp = cc.instantiate(this.HighWay[0]);
                    // cc.log('重新创建')
                }
                // let highwayTemp = cc.instantiate(this.HighWay[0]);
                highwayTemp.parent = this.buildLayer.node;
                let tiledTile = highwayTemp.addComponent('TiledTile');
                tiledTile.x = spawnPos.x;
                tiledTile.y = spawnPos.y;
                // this._highPath.push(highwayTemp);

                if (GlobalD.game.getManageGameIndexArrayAt(tiledTile)) {
                    highwayTemp.getComponent('TipSprite').onSetRedSpriteFrame();
                }

                highwayTemp.getComponent('HighwayInfo').onChangeHighwayStyles(reGameStates.HighwayType.moveX);


                if (_highwayStart && !isChangeHighwayStart) {
                    // cc.log('修正第一个起始点。');
                    isChangeHighwayStart = true;
                    _highwayStart.getComponent('HighwayInfo').onChangeHighwayStyles(reGameStates.HighwayType.moveX);

                }
            }


        }





    },

    //取消创建
    //对象池回收
    onCancelCreateHighway() {

        //删除对应层的子节点
        let tempNode = this.buildLayer.node.children;
        let length = tempNode.length;
        for (let i = length - 1; i >= 0; i--) {

            //设置回默认的提示图片
            tempNode[i].getComponent('TipSprite').onReset();
            tempNode[i].getComponent('HighwayInfo').onChangeHighwayStyles(reGameStates.HighwayType.none);

            if (tempNode[i].getComponent('TiledTile')) {
                tempNode[i].removeComponent('TiledTile');
            }
            // 和初始化时的方法一样，将节点放进对象池，这个方法会同时调用节点的 removeFromParent
            this.highwayPool.put(tempNode[i]);
        }
    },

    //创建道路
    onCreateHighway() {

        //获取最后建造公路的层级
        this.HighwayLayer = this._tiledMap.getLayer('Highway');

        if (this.isCreateZebra) {
            // cc.log('创建斑马线,', this._StartPosition);
            //检测新手引导时候道路，不设计一个点
            if (task.isMushBuildState) {
                console.error('新手教程下不创建单个公路');
                cc.loader.loadRes('resUI/ShowNotEnoughMoney', function (err, texture) {
                    var prefab = cc.instantiate(texture);
                    prefab.getComponent('ShowNotEnoughMoney').Text('请移动到虚影的<终点>位置！');
                    cc.find('Canvas').getChildByName('UICamera').addChild(prefab);
                }.bind(this));
                return;
            }

            let buildIndex = GlobalD.TiledMap.getIndex(this._StartPosition);
            if (GlobalD.game.onGetHighwayFromIndex(buildIndex)) {

                let tempNode = this.HighwayLayer.node.children;
                let length = tempNode.length;
                for (let i = length - 1; i >= 0; i--) {
                    let tiledTile = tempNode[i].getComponent('TiledTile');
                    let tiledVector2 = new cc.Vec2(tiledTile.x, tiledTile.y);
                    let tiledIndex = GlobalD.TiledMap.getIndex(tiledVector2);

                    if (tiledIndex === buildIndex) {
                        let _highwayInfo = tempNode[i].getComponent('HighwayInfo');
                        // cc.log(_highwayInfo);
                        let _switchHighwayType = reGameStates.HighwayType.none;
                        if (_highwayInfo.currenHighwayType == reGameStates.HighwayType.moveX) {
                            _switchHighwayType = reGameStates.HighwayType.ZebraCrossingX;
                        } else if (_highwayInfo.currenHighwayType == reGameStates.HighwayType.moveY) {
                            _switchHighwayType = reGameStates.HighwayType.ZebraCrossingY;
                            // cc.log('Y', _switchHighwayType)
                        }
                        //修改节点样式
                        _highwayInfo.onChangeHighwayStyles(_switchHighwayType);

                        //更新公路样式
                        GlobalD.game.onUpdateDifferentRoadStyles({
                            _highwayType: _switchHighwayType,
                            _roadIndex: buildIndex,
                        });
                        break;
                    }

                }
            } else {//没有就创建

                let tiledVector2 = this._StartPosition;
                let highwayTemp = cc.instantiate(this.HighWay[1]);
                highwayTemp.parent = this.HighwayLayer.node;

                let tiledTile = highwayTemp.addComponent('TiledTile');
                tiledTile.x = tiledVector2.x;
                tiledTile.y = tiledVector2.y;

                // cc.log('onCreateHighway');
                AStar.setMapSolid(tiledVector2.x, tiledVector2.y, 0);

                // _buildId ==0 是公路
                let _buildId = 0;
                let occupyTemp = cc.v2(_buildId, buildIndex);
                GlobalD.game.OccupyArray.push(occupyTemp);

                //添加公路样式
                GlobalD.game.onCreateDifferentRoadStyles({
                    _buildId: _buildId,
                    _highwayType: reGameStates.HighwayType.ZebraCrossingX,
                    _roadIndex: buildIndex,
                    _hightwayNode: highwayTemp
                });
            }


        } else {

            let tempNode = this.buildLayer.node.children;
            let length = tempNode.length;
            //检测新手引导时候道路,检测最后一个点
            //如果是新手指引的情况下,需要显示对应的遮挡模板
            if (task.virtualShadowPosEnd) {
                let _taskTiledTile = tempNode[length - 1].getComponent('TiledTile');


                if (task.virtualShadowPosEnd.sub(cc.v2(_taskTiledTile.x, _taskTiledTile.y)).mag() !== 0) {

                    console.error('没有移动到终点位置：', cc.v2(_taskTiledTile.x, _taskTiledTile.y), task.virtualShadowPosEnd);
                    cc.loader.loadRes('resUI/ShowNotEnoughMoney', function (err, texture) {
                        var prefab = cc.instantiate(texture);
                        prefab.getComponent('ShowNotEnoughMoney').Text('请移动到虚影的<终点>位置！');
                        cc.find('Canvas').getChildByName('UICamera').addChild(prefab);
                    }.bind(this));
                    return;
                } else {
                    //铺路教程成功
                    //移除虚影路径
                    task.removeTaskNode('taskPrefabTiledTileHighway');
                    //设置任务状态
                    task.onShadowArchitectureReset();
                    dialogmanager.init(task.Canvas, function () {
                        dialogmanager.paveEnd();
                    }.bind(this));
                    dialogmanager.setOnCloseDialog(function () {
                        task.showManagerhide();
                        // task.setListView(18);
                        task._setTaskIconCountClick(1);

                        setTimeout(() => {
                            task.taskCallBack();
                        }, 500);
                    }.bind(this));
                }
            }

            for (let i = length - 1; i >= 0; i--) {
                let tiledTile = tempNode[i].getComponent('TiledTile');

                //获取临时对象里面的公路脚本信息
                let _highwayInfoTemp = tempNode[i].getComponent('HighwayInfo');

                let tiledVector2 = new cc.Vec2(tiledTile.x, tiledTile.y);
                //重复的道路模块不创建
                if (!GlobalD.game.getManageGameIndexArrayAt(tiledVector2)) {
                    let highwayTemp = cc.instantiate(this.HighWay[1]);
                    highwayTemp.parent = this.HighwayLayer.node;

                    let tiledTile = highwayTemp.addComponent('TiledTile');
                    tiledTile.x = tiledVector2.x;
                    tiledTile.y = tiledVector2.y;

                    // cc.log('onCreateHighway');
                    AStar.setMapSolid(tiledVector2.x, tiledVector2.y, 0);

                    let index = GlobalD.TiledMap.getIndex(tiledVector2);
                    // _buildId ==0 是公路
                    let _buildId = 0;
                    let occupyTemp = cc.v2(_buildId, index);
                    GlobalD.game.OccupyArray.push(occupyTemp);

                    // cc.log('创建时候的值：', _highwayInfoTemp.currenHighwayType)
                    // highwayTemp.getComponent('HighwayInfo').onChangeHighwayStyles(_highwayInfoTemp.currenHighwayType);

                    //添加公路样式
                    GlobalD.game.onCreateDifferentRoadStyles({
                        _buildId: _buildId,
                        _highwayType: _highwayInfoTemp.currenHighwayType,
                        _roadIndex: index,
                        _hightwayNode: highwayTemp
                    });
                }

                else {
                    // cc.log('有道路重复！', tiledVector2);
                    let buildIndex = GlobalD.TiledMap.getIndex(tiledVector2);
                    let tempNode = this.HighwayLayer.node.children;
                    let length = tempNode.length;
                    for (let i = length - 1; i >= 0; i--) {
                        let tiledTile = tempNode[i].getComponent('TiledTile');
                        let tiledVector2 = new cc.Vec2(tiledTile.x, tiledTile.y);
                        let tiledIndex = GlobalD.TiledMap.getIndex(tiledVector2);

                        if (tiledIndex === buildIndex) {
                            let _highwayInfo = tempNode[i].getComponent('HighwayInfo');
                            //修改节点样式
                            _highwayInfo.onChangeHighwayStyles(_highwayInfoTemp.currenHighwayType);

                            //更新公路样式
                            GlobalD.game.onUpdateDifferentRoadStyles({
                                _highwayType: _highwayInfoTemp.currenHighwayType,
                                _roadIndex: buildIndex,
                            });
                            break;
                        }

                    }
                }

            }
        }


        //清空回收临时对象
        this.onCancelCreateHighway();

        //统一取消
        this.onHide();

        // if (this.isCreateZebra) {
        //     this.onHide();
        // } else {
        //     //成功创建后，重置下初始位置
        //     this.onInitStartPosition();
        // }

    },

    //删除
    onDelete() {
        this.onCancelCreateHighway();
        this.highwayPool.clear();// 调用这个方法就可以清空对象池
        this.node.destroy();
    },
    //隐藏
    onHide() {
        this.onCancelCreateHighway();
        this.node.active = false;
        // this._isInitOnce = false;

        //绿色选中框选中要下面两个代码切换
        this.selectTouch.active = true;
        this.buildingTouch.active = false;


        GlobalD.game.onClearCurrentBuildingTarget();

        //显示铺路引导
        task.onTaskPaveRoadsMask();
    },
    onDisable() {
        //隐藏时候重置下状态
        this.onHideSetTouchState();
        //收起底部菜单栏
        GlobalD.game._ManageUIScript.onBottomMenuView(true);
    },

    onEnable() {

        // console.log(111);
        //修改按钮状态
        this.onSetTouchState();
        //收起底部菜单栏
        GlobalD.game._ManageUIScript.onBottomMenuView(false);

    }


    // update (dt) {},
});
