
cc.Class({
    extends: cc.Component,

    properties: {

        
        isHiddenTouch: { 
            default: false,
            tooltip:"初始化时候是否绑定touch"
         },

        //是否显示房屋信息
        isShowBuildingInfo: { default: false },

        // 是否是在预制生成
        _isInstance: { default: false, visible: false },
        //如果进入编辑状态
        _ifCanEdit: { default: false, visible: false },

        //触摸多久进入编辑状态
        touchTimer: { default: 0.8, visible: false },

        // //绘制底部颜色区域
        // Draw: cc.Node,

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

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

        targetNode: cc.Node,

        //编辑时候，记录旧的遮挡位置
        _OldIndex: 0,

        //如果是在新手引导时候建造的建筑
        //只要拖拽到虚影对应的位置，才能成功建造
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this._buildingsInfo = this.node.getComponent('buildingsInfo');
        this.buildInfo = this._buildingsInfo.buildInfo;
        this.title = this._buildingsInfo.title;

        if(!this.isHiddenTouch){
            this.node.on(cc.Node.EventType.TOUCH_START, this.TouchStartFunction, this);
            this.node.on(cc.Node.EventType.TOUCH_END, this.TouchEndFunction, this);
            this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.TouchCancelFunction, this);
        }
        // console.log("this.isHiddenTouch",this.isHiddenTouch);
        this.Draw = this._buildingsInfo._buildZone;
        if (!this.Draw)
            this.Draw = this.node.getChildByName('Draw');
        this.Draw.active = false;
    },

    start() {
        this.InitStartPos = this._buildingsInfo.InitStartPos;
        this._camera = GlobalD.game.MainCamera;
        this._canvas = GlobalD.game.Canvas;
        this._tileMap = GlobalD.TiledMap;
    },


    TouchStartFunction() {
        // console.log("TouchStartFunction");
        this._touchPosition = this.node.getPosition();
        GlobalD.GameControl._isBuildingMove = false;
        this._isMove = false;
        this.unschedule(this.callback);
        this.scheduleOnce(this.callback = function () {
            //编辑器移动的话，返回
            if (GlobalD.GameControl.isUICameraMove) return;
            //进入编辑状态
            // cc.log('进入编辑状态！',GlobalD.GameControl.isUICameraMove);
            // this.onEditorStatus(false);
            //按住可以编辑
        }, this.touchTimer);

    },
    //生成房屋时候的预制状态
    // 编辑状态
    onEditorStatus(isInstance) {

        // cc.log('onEditorStatus', isInstance);
        //如果是编辑状态下，返回
        if (this._ifCanEdit) return;

        //只要是编辑状态下。设为true
        GlobalD.GameControl._isBuildingCanEdit = true;

        this._isInstance = isInstance;
        this._ifCanEdit = true;
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.MoveFunction, this);
        GlobalD.game._ManageUIScript.onEditorialBuildings(this.node);
        GlobalD.game.onSetCurrentBuildingTarget(this.node);

        if (!this.Draw)
            this.Draw = this.node.getChildByName('Draw')
        this.Draw.active = true;

        if (isInstance) {
            // cc.log(11111);
            this._currentTiledValue = GlobalD.TiledMap._tilePosFromLocation(this.node.position);
            let endPos = GlobalD.TiledMap._getTheMiddleLocationFromtilePos(this._currentTiledValue);
            this.node.setPosition(endPos);
            this._canNotBuild = GlobalD.game.areTheraOverlappingAreas(this._currentTiledValue, this.buildInfo.occupyArea, 1);

        } else {// if (this._tileMap) 
            // cc.log(22222);
            this._currentTiledValue = this._tileMap._tilePosFromLocation(this._touchPosition);
            this._canNotBuild = GlobalD.game.areTheraOverlappingAreas(this._currentTiledValue, this.buildInfo.occupyArea, 1);
        }

        if (task.virtualShadowPos)
            this._canNotBuild = this._currentTiledValue.sub(task.virtualShadowPos).mag() == 0 ? false : true;

        GlobalD.game.onSpawnEditorBuildingTip(this.Draw, this._currentTiledValue, this.buildInfo.occupyArea, this._canNotBuild, this.buildInfo.buildType);

        this._OldIndex = this.node.zIndex;
        //设置最高显示
        this.node.zIndex = 1000;
    },
    TouchCancelFunction() {
        // console.log("TouchCancelFunction");
        this.unschedule(this.callback);
        GlobalD.GameControl._isBuildingMove = false;
    },
    TouchEndFunction() {
        // console.log("TouchEndFunction");
        // console.log("点击建筑物 之后",this.getOnClickTags());
        if (this.getOnClickTags()) {
            return;
        }

        GlobalD.GameControl._isBuildingMove = false;

        this.unschedule(this.callback);
        // cc.warn('touch End！');
        console.log("this.isShowBuildingInfo:",this.isShowBuildingInfo);
        //如果没有移动就判断点击
        if (!this._isMove
            && this.isShowBuildingInfo
            && !this._ifCanEdit
            && !GlobalD.GameControl.isUICameraMove
            && !GlobalD.GameControl._isBuildingCanEdit)
            GlobalD.game._ManageUIScript.onShowBuildingInfo(this.buildInfo);

    },
    MoveFunction(event) {
        // cc.log("MoveFunction");
        var delta = event.touch.getDelta();
        this._touchPosition.x += delta.x / this._camera.zoomRatio;
        this._touchPosition.y += delta.y / this._camera.zoomRatio;
        // var worldPos = this.node.parent.convertToWorldSpaceAR(this._touchPosition);
        //取得的节点减去canvas的偏移
        // let tempPos = cc.v2(worldPos.x - this._canvas.x, worldPos.y - this._canvas.y);
        this._currentTiledValue = this._tileMap._tilePosFromLocation(this._touchPosition);
        //不相等的时候才绘制
        if (this._currentTiledValue.sub(this._EndPosition).mag() != 0) {

            this._EndPosition = this._currentTiledValue;
            let endPos = this._tileMap._getTheMiddleLocationFromtilePos(this._currentTiledValue);
            this.node.setPosition(endPos);
            let isHas = this._canNotBuild = GlobalD.game.areTheraOverlappingAreas(this._currentTiledValue, this.buildInfo.occupyArea, 1);
            // this.title.string = "(" + (this._currentTiledValue.x) + "," + (this._currentTiledValue.y) + ")" + isHas;

            if (task.virtualShadowPos)
                this._canNotBuild = this._EndPosition.sub(task.virtualShadowPos).mag() == 0 ? false : true;


            GlobalD.game.onSpawnEditorBuildingTip(this.Draw, this._currentTiledValue, this.buildInfo.occupyArea, this._canNotBuild, this.buildInfo.buildType);

        }
        this._isMove = true;
        GlobalD.GameControl._isBuildingMove = true;
    },
    // 自动移动,在ManagerControl 里面调用
    onAutoMove(delta) {
        this.isAutoMove = true;
        this._touchPosition.x += delta.x;
        this._touchPosition.y += delta.y;
        this._currentTiledValue = this._tileMap._tilePosFromLocation(this._touchPosition);
        //不相等的时候才绘制
        if (this._currentTiledValue.sub(this._EndPosition).mag() != 0) {
            this._EndPosition = this._currentTiledValue;
            let endPos = this._tileMap._getTheMiddleLocationFromtilePos(this._currentTiledValue);
            this.node.setPosition(endPos);
            let isHas = this._canNotBuild = GlobalD.game.areTheraOverlappingAreas(this._currentTiledValue, this.buildInfo.occupyArea, 1);
            // this.title.string = "(" + (this._currentTiledValue.x) + "," + (this._currentTiledValue.y) + ")" + isHas;

            if (task.virtualShadowPos)
                this._canNotBuild = this._EndPosition.sub(task.virtualShadowPos).mag() == 0 ? false : true;

            GlobalD.game.onSpawnEditorBuildingTip(this.Draw, this._currentTiledValue, this.buildInfo.occupyArea, this._canNotBuild, this.buildInfo.buildType);


        }
    },

    onCancleAutoMove() {
        this.isAutoMove = false;

    },

    /**
     * 编辑房子时候
     * 完成建造房子流程
     */
    onFinishEdit() {

        GlobalD.GameControl._isBuildingCanEdit = false;
        GlobalD.game.onClearCurrentBuildingTarget();
        // cc.log(this._ifCanEdit, this._canNotBuild);
        if (this._canNotBuild) {
            //如果不可建造区域，跳回起始位置
            this.onCancelEdit();
            return;
        }
        //如果完成时候，还在初始化生成的状态，重置为false
        if (this._isInstance) {
            this._isInstance = false;
            GlobalD.game._ManageUIScript.onBottomMenuView(true);

            //只有初始化建筑建造成功才移除建筑数据
            /**
             * 操作记录的数据减少1
             */
            GlobalD.game.MuinusBuilding(this.buildInfo.buildingName);
        }
        if (!this._ifCanEdit) return;
        //把物体定位到对应的坐标上去
        if (this._currentTiledValue) {
            //如果可以移动的话，更新一次位置
            this.InitStartPos = this._currentTiledValue;
            var endTiledPos = cc.v2(this._currentTiledValue.x, this._currentTiledValue.y);
            var endPos = this._tileMap._getTheMiddleLocationFromtilePos(endTiledPos);
            this.node.setPosition(endPos);
            let isHas = GlobalD.game.doesItExistArray(this.buildInfo.id);
            if (!isHas) {
                //起始坐标，占位范围，是否占位
                GlobalD.game.addBuildTiled(this.buildInfo.id, this._currentTiledValue, this.buildInfo.occupyArea);
                this.buildInfo.startTilePos = this._currentTiledValue;
                GlobalD.game.addBuilding(this._buildingsInfo);
            } else {//如果已经存在，更新新位置
                //可以移动
                let isMove = true;
                GlobalD.game.updateBuildOccupy(isMove, this.buildInfo.id, this._currentTiledValue, this.buildInfo.occupyArea);
                this.buildInfo.startTilePos = this._currentTiledValue;
                GlobalD.game.updateBuilding(this._buildingsInfo);
            }
        }

        //完成后从新设置状态
        this.Draw.active = false;
        this._ifCanEdit = false;
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.MoveFunction, this);

        // cc.log('this.Draw.active', this.Draw.active);
        // cc.log('this._buildingsInfo='+this._buildingsInfo.buildInfo.EnglishName);

        //设置影响力
        GlobalD.game.onFinishAddEditorBuildingsEffect(this._buildingsInfo);

        if (task.TaskIconCountClick >= 13)
            return;
        //引导 开始 建造 农舍 确定之后
        if (task.taskCursor == 0 && this.node.name == "Env_101_house_low") {
            task.taskShare();
            task.onShadowArchitectureReset();

        }

        if (this.node.name == "Labour_201_Farmland") {
            task.Farming();
            task.onShadowArchitectureReset();
        }


        // if (this.node.name == "Labour_204_Factory") {
        //     //盖一个工厂
        //     task.taskfactory();
        // }
        // if (this.node.name == "Shops_30101_ColdDrinkStall") {
        //     //盖一个便利店
        //     task.taskConvenienceStore();
        // }
        // //
        // if (this.node.name == "Spe_402_GreenBelt") {

        //     task.taskGreenBeltShare();
        // }
        // if (this.node.name == "Env_101_house_low") {
        //     task.taskFarmhouse();
        // }
        UtilsWX.getAllBuild();
    },



    onTaskBuild() {
        // console.log(this._canNotBuild, task.isMushBuildState);
        if (task.isMushBuildState && this._canNotBuild) {
            //如果不可建造区域
            if (this.node.name == "Env_101_house_low" || this.node.name == "Labour_201_Farmland") {
                // task.onTaskBuildAHouseMask();
                cc.loader.loadRes('resUI/ShowNotEnoughMoney', function (err, texture) {
                    var prefab = cc.instantiate(texture);
                    prefab.getComponent('ShowNotEnoughMoney').Text('请在指定位置建造！');
                    // this.node.addChild(prefab);
                    cc.find('Canvas').getChildByName('UICamera').addChild(prefab);
                }.bind(this));
            }
            return false;
        }

        return true;
    },


    onCancelEdit() {

        GlobalD.GameControl._isBuildingCanEdit = false;

        this.node.zIndex = this._OldIndex;
        // cc.log('onCancelEdit');
        GlobalD.game.onClearCurrentBuildingTarget();

        if (this._isInstance) {
            // cc.log('删除1');
            //清除底部的提示，放回对象池
            GlobalD.game.onClearSpawnEditorBuildingTip();
            GlobalD.game._ManageUIScript.onBottomMenuView(true);
            //如果是预制生成的，取消生成的时候，删除预制
            this.scheduleOnce(() => {
                this.node.destroy();
            }, 0)
        } else {
            // cc.log('删除2');
            this.Draw.active = false;
            this._ifCanEdit = false;
            // cc.log(' buildingsInfo.buildInfo.InitStartPos', this.InitStartPos);
            this.node.off(cc.Node.EventType.TOUCH_MOVE, this.MoveFunction, this);
            var endTiledPos = cc.v2(this.InitStartPos.x, this.InitStartPos.y);
            var endPos = this._tileMap._getTheMiddleLocationFromtilePos(endTiledPos);
            this.node.setPosition(endPos);
        }

    },


    /**
     * 需要添加碰撞体
   * 不规则多边形触摸测试
   * @param {触摸点} point 
   * @param {监听} listener 
   */
    polygonHitTest(point, listener) {
        var polygonCollider = this.getComponent(cc.PolygonCollider);
        if (polygonCollider) {
            point = this.convertToNodeSpace(point);
            point.x -= this.getContentSize().width / 2;
            point.y -= this.getContentSize().height / 2;
            return cc.Intersection.pointInPolygon(point, polygonCollider.points);
        } else {
            return this._oldHitTest(point, listener);
        }
    },

    /**
     * 判断是否可以被优先点击
     * @returns {*}
     */
    getOnClickTags: function () {
        if (this.getComponent("Collect") != null) {
            return this.getComponent("Collect").getOnClickTag();
        } else {
            return false;
        }


    }

});
