const Constants = require('Constants');


//移动方向的枚举
var cameraMoveType = cc.Enum({
    none: 0,
    moveUp: 1,
    moveRight: 2,
    moveDown: 3,
    moveLeft: 4,
});


cc.Class({
    extends: cc.Component,

    properties: {

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

        BuildNodeArray: {
            default: [],
            type: cc.Node,
        },

        //如果进入编辑状态
        _isBuildingCanEdit: { default: false, visible: false },
        _isBuildingMove: { default: false, visible: false },


        //如果是UICamera移动
        isUICameraMove: { default: false, visible: false },

        UIMask: cc.Node,

        // 移动的边界值
        boundarylimitValue: {
            default: 10,
            type: cc.Integer,
            tooltip: '移动边界的限制值', // 名字注释

        },
        boundaryMoveSpeed: {
            default: 100,
            type: cc.Integer,
            tooltip: '边界值移动的速度', // 名字注释 
        },

        //camera 移动类
        cameraMoveType: {
            default: cameraMoveType.none,
            type: cc.Enum(cameraMoveType),
        },


        //碰到边界时候的delta
        _currentDelta: cc.v2(),

        //任务进行
        isTaskInProgress: false,

    },

    onLoad() {
        GlobalD.GameControl = this;
        this.initShare();
    },

    initShare: function () {
        this.UICamera = this.node;

        this._showShare(function () {
            this.sharegosharebtn.on(cc.Node.EventType.TOUCH_END, function (event) {
                // console.log("点击分享按钮");
                UtilsWX.sharebtn();
            }.bind(this));
        }.bind(this));
    },
    _showShare: function (callback) {
        return;
        cc.loader.loadRes("prefab/shareview", function (err, texture) {
            this.shareview = cc.instantiate(texture);
            if (this.UICamera.getChildByName(this.shareview.name) != null) {
                this.UICamera.getChildByName(this.shareview.name).destroy();
            }
            this.UICamera.addChild(this.shareview, -99);
            // this.dialogLuckView.active = false;
            // this.shareview.zIndex=-99;
            this.sharegosharebtn = this.getNode("gosharebtn", this.shareview);
            // this.close = this.getNode("close",this.dialogLuckView);
            this.sharegosharebtn.off(cc.Node.EventType.TOUCH_END);


            this.shareview.y = 500;
            this.shareview.x = -200;
            if (callback != null) {
                callback();
            }
        }.bind(this));
    },
    start() {
        var isTouch = false
        var self = this, parent = this.node.parent; this.MainCamera = GlobalD.game.MainCamera; this.Canvas = GlobalD.game.Canvas;
        self.target = self.MainCamera.node;
        // self.target.setScale(0.7);
        self.target.setScale(1.2);
        self.MainCamera.zoomRatio = 1.2;//0.7;
        self.myx = 432 / self.MainCamera.zoomRatio;
        self.myy = 768 / self.MainCamera.zoomRatio;

        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
            //设置为不移动
            self.cameraMoveType = cameraMoveType.none;
            // self.isUICameraMove = false;

        }, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {
            //设置为不移动
            self.cameraMoveType = cameraMoveType.none;
            // self.isUICameraMove = false;

        }, this);

        this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
            self.isUICameraMove = false;
            // 起始触摸位置
            // this.touchLocation = event.touch.getLocation();
            if (event.type === cc.Node.EventType.TOUCH_START && isTouch == false) {
                //穿透正常响应UI事件
                // this.BuildNodeArray[0]._touchListener.setSwallowTouches(false);
                this.node._touchListener.setSwallowTouches(false);
            } else {
                //吞掉事件 不让他继续传下去
                this.node._touchListener.setSwallowTouches(true);
                event.stopPropagation();
            }

        }, this);

        self.node.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
            if (self.UIMask && self.UIMask.active || self.isTaskInProgress) return;
            if (self._isBuildingMove) {
                // cc.log(event.touch.getDelta());
                //如果是编辑建筑物时候
                let uiTouchPos = event.touch.getLocation();
                // cc.log(uiTouchPos);
                if (uiTouchPos.x <= self.boundarylimitValue) {
                    // cc.log('屏幕左边', self.cameraMoveType);
                    if (self.cameraMoveType != cameraMoveType.moveLeft) {
                        self._currentDelta = event.touch.getDelta();
                    }
                    self.cameraMoveType = cameraMoveType.moveLeft;
                } else if (uiTouchPos.y <= self.boundarylimitValue) {
                    // cc.log('屏幕下边');
                    if (self.cameraMoveType != cameraMoveType.moveDown) {
                        self._currentDelta = event.touch.getDelta();
                    }
                    self.cameraMoveType = cameraMoveType.moveDown;

                } else if (uiTouchPos.x >= self.node.width - self.boundarylimitValue) {
                    // cc.log('屏幕右边');
                    if (self.cameraMoveType != cameraMoveType.moveRight) {
                        self._currentDelta = event.touch.getDelta();
                    }
                    self.cameraMoveType = cameraMoveType.moveRight;

                } else if (uiTouchPos.y >= self.node.height - self.boundarylimitValue) {
                    // cc.log('屏幕上边');
                    if (self.cameraMoveType != cameraMoveType.moveUp) {
                        self._currentDelta = event.touch.getDelta();
                    }
                    self.cameraMoveType = cameraMoveType.moveUp;

                } else {
                    if (self.cameraMoveType != cameraMoveType.none) {
                        self._currentDelta = 0;
                    }
                    self.cameraMoveType = cameraMoveType.none;
                }
                return
            };


            // cc.log(self.isUICameraMove);
            var touches = event.getTouches();
            // cc.log(touches);
            if (touches.length >= 2) {
                var touch1 = touches[0], touch2 = touches[1];
                var delta1 = touch1.getDelta(), delta2 = touch2.getDelta();
                var touchPoint1 = parent.convertToNodeSpaceAR(touch1.getLocation());
                var touchPoint2 = parent.convertToNodeSpaceAR(touch2.getLocation());
                //缩放
                var distance = touchPoint1.sub(touchPoint2);
                var delta = delta1.sub(delta2);
                var scale = 1;
                if (Math.abs(distance.x) > Math.abs(distance.y)) {
                    scale = (distance.x + delta.x) / distance.x * self.target.scale;
                }
                else {
                    scale = (distance.y + delta.y) / distance.y * self.target.scale;
                }
                // self.target.scale = scale < 0.1 ? 0.1 : scale;

                self.target.scale = scale = scale <= 0.4 ? 0.4 : scale;
                self.target.scale = scale = scale >= 1 ? 1 : scale;
                // self.Show.string = "(" + scale + ")";

                self.MainCamera.zoomRatio = scale;
                this.myx = 432 / self.MainCamera.zoomRatio;
                this.myy = 768 / self.MainCamera.zoomRatio;
                self.isUICameraMove = true;

                self._deteItem();
            } else {
                // 640 360
                //533.33  300

                // self.MainCamera.zoomRatio = 0.8;

                this.myx = 432 / self.MainCamera.zoomRatio;
                this.myy = 768 / self.MainCamera.zoomRatio;




                var delta = event.touch.getDelta();
                self.MainCamera.node.x -= delta.x / self.MainCamera.zoomRatio;
                self.MainCamera.node.y -= delta.y / self.MainCamera.zoomRatio;

                if (Math.abs(delta.x) > 2 || Math.abs(delta.y) > 2)
                    self.isUICameraMove = true;

                // cc.log(Math.abs(delta.x),'Math.abs(delta.y)',Math.abs(delta.y));
                // 控制节点移不出屏幕; 
                //Constants.MoveX 2700
                var minX = -(Constants.MoveX + 1000 * self.MainCamera.zoomRatio);//;//最小X坐标；
                var maxX = Constants.MoveX + 1000 * self.MainCamera.zoomRatio;//Constants.MoveMaxX;
                var minY = -(Constants.MoveY + 1550 * self.MainCamera.zoomRatio); //最小Y坐标；
                var maxY = Constants.MoveY + 1550 * self.MainCamera.zoomRatio;
                var nPos = self.MainCamera.node.position; //节点实时坐标；
                if (nPos.x < minX) {
                    nPos.x = minX;
                };
                if (nPos.x > maxX) {
                    nPos.x = maxX;
                };
                if (nPos.y < minY) {
                    nPos.y = minY;
                };
                if (nPos.y > maxY) {
                    nPos.y = maxY;
                };
                self.MainCamera.node.setPosition(nPos);
                // self.Show.string = "(" + self.MainCamera.node.position + ")";

                self._deteItem();

            }
        }.bind(this), self.node);

        return;
        //给所有的点注册事件，会自动冒泡到此节点

        for (var i = 0; i < this.BuildNodeArray.length; i++) {

            var BuildNodes = this.BuildNodeArray;

            //闭包传递i值

            (function (i) {

                var BuildNode = BuildNodes[i];

                BuildNode.on(cc.Node.EventType.TOUCH_START, function (event) {

                    cc.log('BuildNode TOUCH_START');

                }, BuildNode);



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

                    cc.log('BuildNode TOUCH_MOVE');

                }, BuildNode);



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

                    cc.log('BuildNode TOUCH_END');

                }, BuildNode);



                BuildNode.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {

                    cc.log('BuildNode TOUCH_CANCEL');

                }, BuildNode);





            })(i)



        }
    },


    update(dt) {

        if (cameraMoveType.none != this.cameraMoveType) {

            let deltaX = this._currentDelta.x > 0 ? 1 : -1;
            let deltaY = this._currentDelta.y > 0 ? 1 : -1;

            let speedX = (deltaX / this.MainCamera.zoomRatio) * dt * this.boundaryMoveSpeed;
            let speedY = (deltaY / this.MainCamera.zoomRatio) * dt * this.boundaryMoveSpeed;

            if (GlobalD.game.currentEditorBuilding) {

                if ('TouchMoveBuilding' == GlobalD.game.currentEditorBuilding.name) {
                    GlobalD.game.currentEditorBuilding.getComponent('DynamicBuilding').onAutoMove(cc.v2(speedX, speedY));
                } else {
                    GlobalD.game.currentEditorBuilding.getComponent('buildingsTouch').onAutoMove(cc.v2(speedX, speedY));
                }

                this.MainCamera.node.x += speedX;
                this.MainCamera.node.y += speedY;

                // 控制节点移不出屏幕; 
                //Constants.MoveX 2700
                var minX = -(Constants.MoveX + 500 * this.MainCamera.zoomRatio);//;//最小X坐标；
                var maxX = Constants.MoveX + 500 * this.MainCamera.zoomRatio;//Constants.MoveMaxX;
                var minY = -(Constants.MoveY + 775 * this.MainCamera.zoomRatio); //最小Y坐标；
                var maxY = Constants.MoveY + 775 * this.MainCamera.zoomRatio;
                var nPos = this.MainCamera.node.position; //节点实时坐标；
                if (nPos.x < minX) {
                    nPos.x = minX;
                };
                if (nPos.x > maxX) {
                    nPos.x = maxX;
                };
                if (nPos.y < minY) {
                    nPos.y = minY;
                };
                if (nPos.y > maxY) {
                    nPos.y = maxY;
                };
                this.MainCamera.node.setPosition(nPos);
            }

        }
    },
    getNode: function (name, parent) {
        if (parent == null) {
            return this.node.getChildByName(name);
        } else {
            return parent.getChildByName(name);
        }

    },

    _deteItem() {
        //建筑
        let buidingsLength = GlobalD.game.buildingsTiledMapUnit.length;
        for (let index = 0; index < buidingsLength; index++) {
            let _buildinginfo = GlobalD.game.buildingsTiledMapUnit[index].getBuildingsInfo;
            let _isShow = this._detecting(_buildinginfo.node);
            if (_buildinginfo.buildInfo.BuildingSprite) {
                _buildinginfo.buildInfo.BuildingSprite.node.active = _isShow;
            }
            // else {
            //     console.log("预制中不存在的BuildingSprite", _buildinginfo.node.name)
            // }
        }
        //公路
        let _HighwayLayer = GlobalD.TiledMap._tiledMap.getLayer('Highway');
        let _highwayChild = _HighwayLayer.node.children;
        for (let index = 0; index < _highwayChild.length; index++) {
            let _highwayNode = _highwayChild[index];
            _highwayNode.active = this._detecting(_highwayNode);
        }
    },

    _detecting(_targetNode) {

        let _worldpos = _targetNode.parent.convertToWorldSpaceAR(_targetNode.position);
        //取得的节点减去canvas的偏移
        let tempPos = cc.v2(_worldpos.x - this.Canvas.x, _worldpos.y - this.Canvas.y);

        // let _MaxY = this.MainCamera.node.position.y + 640;
        // let _minY = this.MainCamera.node.position.y - 640;
        // let _MaxX = this.MainCamera.node.position.x + 360;
        // let _minX = this.MainCamera.node.position.x - 360;
        // console.log("是啥x",this.myx);
        // console.log("是啥y",this.myy);
        let _MaxY = this.MainCamera.node.position.y + this.myy;
        let _minY = this.MainCamera.node.position.y - this.myy;
        let _MaxX = this.MainCamera.node.position.x + this.myx;
        let _minX = this.MainCamera.node.position.x - this.myx;
        if (tempPos.y < _MaxY
            && tempPos.y > _minY
            && tempPos.x < _MaxX
            && tempPos.x > _minX
        ) {
            // console.log("摄像机里面");
            return true;
        } else {
            // console.log('摄像机外面');
            return false;
        }
    }
});
