cc.Class({
    extends: cc.Component,

    properties: {
        maskNode: cc.Node,
        picNode: cc.Node,
    },
    onLoad () {
        this.node.on('touchstart', this.onTouchStart, this);
        this.node.on('touchmove', this.onTouchMove, this);
    },
    // Zoom.js
    onTouchStart (event) {
        let touches = event.getTouches();
        if (touches.length == 1) {
            // 一根手指是移动，这里不用写任何代码       
        }
        else if (touches.length == 2) {
            this.startPos1 = this.node.convertToNodeSpaceAR(touches[0].getLocation());
            this.startPos2 = this.node.convertToNodeSpaceAR(touches[1].getLocation());
            this.pointsDis = this.startPos1.sub(this.startPos2).mag();
        }
    }, 
    // Zoom.js
    onTouchMove (event) {
        let touches = event.getTouches();
        if (touches.length == 1) {
            // 一根手指是移动
            let delta = event.getDelta();
            this.picNode.setPosition(this.picNode.position.add(delta));
            this.restrictPic();
        }
        else if (touches.length == 2) {
            // 两根手指是缩放
            let touchPoint1 = this.node.convertToNodeSpaceAR(touches[0].getLocation());
            let touchPoint2 = this.node.convertToNodeSpaceAR(touches[1].getLocation());
            let newPointsDis = touchPoint1.sub(touchPoint2).mag();

            if (!this.pointsDis)        // 该行代码针对安卓手机
                this.pointsDis = 0;
 
            if (newPointsDis > this.pointsDis) {
                // 表明两根手指在往外划
                this.pointsDis = newPointsDis;
                this.picNode.scale += 0.05;
            }   
            else if (newPointsDis < this.pointsDis) {
                // 表明两根手指在往内划
                if (this.picNode.scale <= 1) {
                    this.picNode.scale = 1;
                    return;
                }
 
                this.pointsDis = newPointsDis;
                this.picNode.scale -= 0.05;
            }
 
            this.restrictPic();
        }
    },
    // Zoom.js
    restrictPic () {
    // 限制移动，放置出现黑边
        let picWidth = this.picNode.getBoundingBox().width;
        let picHeight = this.picNode.getBoundingBox().height;
        if (this.picNode.x>0 && this.picNode.x-0>picWidth/2-this.maskNode.width/2)
            this.picNode.x = picWidth/2-this.maskNode.width/2;
        if (this.picNode.x<0 && this.picNode.x-0<this.maskNode.width/2-picWidth/2)
            this.picNode.x = this.maskNode.width/2-picWidth/2;
        if (this.picNode.y>0 && this.picNode.y-0>picHeight/2-this.maskNode.height/2)
            this.picNode.y = picHeight/2-this.maskNode.height/2;
        if (this.picNode.y<0 && this.picNode.y-0<this.maskNode.height/2-picHeight/2)
            this.picNode.y = this.maskNode.height/2-picHeight/2;
    }
});
