'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var three = require('three');
var map = require('@ktmap/map');
var shared = require('@ktmap/shared');

// circle = false,
//   circleColor = '#000000',
//   // 推测出来的一个比例
//   radius = fontSize / 1,
//   fontSize = 12,
//   color = '#222',
//   padding = 10,
//   // center = new Vector2(0.5, 0),
//   center:Vector2,
//   renderOrder:number,
//   // depthTest = false
class LabelMarker extends map.Element {
    constructor(options) {
        var _a, _b, _c, _d, _e, _f;
        super();
        Object.defineProperty(this, "options", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: options
        });
        Object.defineProperty(this, "scale", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 4
        });
        Object.defineProperty(this, "sprite", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        options.position = (_a = options.position) !== null && _a !== void 0 ? _a : new three.Vector3();
        // 放大 4 倍，为了 retina 屏幕的高清
        options.fontSize = ((_b = options.fontSize) !== null && _b !== void 0 ? _b : 12) * this.scale;
        options.color = (_c = options.color) !== null && _c !== void 0 ? _c : '#222';
        // options.padding = options.padding ?? 10;
        // padding 可以大一点，让碰撞检测"尽早检测"
        options.padding = (_d = options.padding) !== null && _d !== void 0 ? _d : 50;
        options.center = (_e = options.center) !== null && _e !== void 0 ? _e : new three.Vector2(0.5, 0.5);
        options.renderOrder = (_f = options.renderOrder) !== null && _f !== void 0 ? _f : 0;
    }
    complete() { }
    // 重写父类 _inject
    // __inject(map: Map, _scale?: number) {
    //   super.__inject(map);
    //   this._scale = _scale!;
    //   return this;
    // }
    __init() { }
    create() {
        const canvas = this.generateCanvas(this.options);
        this.sprite = this.makeCanvasSprite(canvas, this.options);
        return this.sprite;
    }
    setPosition(position) {
        this.sprite && this.sprite.position.copy(position);
        this.map.reDraw();
    }
    /**
     * 生成 canvas
     */
    generateCanvas({ text, fontSize, padding, color }) {
        // const strokeStyle = 'rgba(255,255,255,.9)';
        const strokeStyle = 'rgba(255,255,255,1)';
        // const marginLeft = this.radius * 2;
        // const marginLeft = this.radius * 1.5;
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        context.font = `${fontSize}px Microsoft YaHei`;
        // 根据文字内容获取宽度
        canvas.width = context.measureText(text).width + padding * 2;
        // +
        // (this.circle ? this.radius * 2 + marginLeft : 0);
        // fontsize * 1.5 = 58;
        // canvas.height = this.fontSize * 1.5 + this.padding * 2;
        canvas.height = fontSize * 1.2 + padding * 2;
        context.font = `${fontSize}px Microsoft YaHei`;
        context.save();
        const textX = 0 + padding;
        // + (this.circle ? this.radius * 2 + marginLeft : 0);
        // 白色边框
        context.lineWidth = 12;
        context.strokeStyle = strokeStyle;
        context.strokeText(text, textX, fontSize + padding);
        context.fillStyle = color;
        context.fillText(text, textX, fontSize + padding);
        context.restore();
        // if (this.circle) {
        //   // 是否需要前面的圆圈 icon
        //   context.strokeStyle = strokeStyle;
        //   context.lineWidth = 12;
        //   context.beginPath();
        //   // console.log('canvas.height/2 :>> ', canvas.height / 2);
        //   context.arc(
        //     0 + this.padding + this.radius,
        //     canvas.height / 2,
        //     this.radius,
        //     0,
        //     2 * Math.PI
        //   );
        //   context.stroke();
        //   context.fillStyle = circleColor;
        //   context.arc(
        //     0 + this.padding + this.radius,
        //     canvas.height / 2,
        //     this.radius,
        //     0,
        //     2 * Math.PI
        //   );
        //   context.fill();
        // }
        return canvas;
    }
    makeCanvasSprite(canvas, { name, renderOrder, position, center }) {
        // https://discourse.threejs.org/t/keep-sprite-size-the-same-as-canvas-texture-size/4407/5
        const texture = new three.CanvasTexture(canvas);
        // texture.minFilter = LinearFilter;
        // texture.needsUpdate = true;
        const spriteMaterial = new three.SpriteMaterial({
            map: texture,
            depthTest: false,
            depthWrite: false,
            // 设置透明，比较协调
            transparent: true,
            // opacity: 0.7
            opacity: 0.8
        });
        const sprite = new three.Sprite(spriteMaterial);
        // sprite.name = OBJECT_NAME.POILabel
        sprite.name = name;
        // sprite.userData.name = name
        sprite.renderOrder = renderOrder;
        sprite.center = center;
        sprite.position.copy(position);
        // sprite.position.z += 10
        // this.group.add(sprite)
        // reDraw()
        return sprite;
    }
}
Object.defineProperty(LabelMarker, "NAME", {
    enumerable: true,
    configurable: true,
    writable: true,
    value: 'LabelMarker'
});

class LabelsLayer extends map.Element {
    constructor({ name, collision }) {
        super();
        Object.defineProperty(this, "scale", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 4
        });
        Object.defineProperty(this, "options", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        Object.defineProperty(this, "group", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        Object.defineProperty(this, "updateSize", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        this.options = { name, collision };
        this.group = new three.Object3D();
        this.group.name = name;
        this.updateSize = shared.throttle(() => {
            const sprites = this.group ? this.group.children : [];
            if (sprites.length === 0)
                return;
            //  是否需要碰撞检测
            if (this.options.collision) {
                for (let i = 0, il = sprites.length; i < il; i++) {
                    const sprite = sprites[i];
                    sprite.visible = true;
                }
            }
            for (let i = 0, il = sprites.length; i < il; i++) {
                const compareSprite = sprites[i];
                // @ts-ignore
                const canvas = compareSprite.material.map.image;
                if (canvas) {
                    const position = compareSprite.position;
                    const scale = this.getPoiScale(position, {
                        w: canvas.width,
                        h: canvas.height
                    });
                    // ✨ 距离相机较远的标签，不进行展示
                    if (scale.distance > this.map.info.fitDistance) {
                        // if (scale.top > 100000) {
                        compareSprite.visible = false;
                    }
                    // ✨ 在视野外，进行隐藏，减少没有必要的计算
                    if (scale.out)
                        compareSprite.visible = false;
                    // // 缩小 4 倍在 retina 屏幕会比较高清
                    // compareSprite.scale.set(
                    //   scale[0] / this.scale,
                    //   scale[1] / this.scale,
                    //   1.0
                    // );
                    // 缩小 4 倍在 retina 屏幕会比较高清
                    compareSprite.scale.set(scale.x / this.scale, scale.y / this.scale, 1.0);
                    // 是否需要碰撞检测
                    if (this.options.collision && compareSprite.visible) {
                        for (let j = i + 1, jl = sprites.length; j < jl; j++) {
                            const sprite = sprites[j];
                            if (sprite.visible) {
                                if (this.isMarkerCollision(compareSprite, sprite))
                                    sprite.visible = false;
                            }
                        }
                    }
                }
            }
        }, 10);
    }
    complete() { }
    __init() {
        this.map.scene.add(this.group);
        this.map.updateSizeMap.set(this, () => this.updateSize());
    }
    add(...markers) {
        for (const item of markers) {
            item.__inject(this.map);
            // item.__inject(this.map, this.scale);
            // const marker = await item.create();
            const marker = item.create();
            this.group.add(marker);
        }
        this.map.reDraw();
        return this;
    }
    remove(...markers) {
        var _a, _b, _c, _d, _e, _f;
        for (const item of markers) {
            (_c = (_b = (_a = item === null || item === void 0 ? void 0 : item.sprite) === null || _a === void 0 ? void 0 : _a.geometry) === null || _b === void 0 ? void 0 : _b.dispose) === null || _c === void 0 ? void 0 : _c.call(_b);
            (_f = (_e = (_d = item === null || item === void 0 ? void 0 : item.sprite) === null || _d === void 0 ? void 0 : _d.material) === null || _e === void 0 ? void 0 : _e.dispose) === null || _f === void 0 ? void 0 : _f.call(_e);
            (item === null || item === void 0 ? void 0 : item.sprite) && this.group.remove(item === null || item === void 0 ? void 0 : item.sprite);
        }
        this.map.reDraw();
        return this;
    }
    // /**
    //  * 暴露出更新size方法，使其可以在 cameraControls 控制时候更新
    //  */
    // private updateSize() {
    //   const sprites = this.group ? this.group.children : [];
    //   if (sprites.length === 0) return;
    //   //  是否需要碰撞检测
    //   if (this.options.collision) {
    //     for (let i = 0, il = sprites.length; i < il; i++) {
    //       const sprite = sprites[i];
    //       sprite.visible = true;
    //     }
    //   }
    //   for (let i = 0, il = sprites.length; i < il; i++) {
    //     const compareSprite = sprites[i];
    //     // @ts-ignore
    //     const canvas = compareSprite.material.map.image;
    //     if (canvas) {
    //       const position = compareSprite.position;
    //       const scale = this.getPoiScale(position, {
    //         w: canvas.width,
    //         h: canvas.height
    //       });
    //       // ✨ 在视野外，进行隐藏，减少没有必要的计算
    //       if (scale.out) compareSprite.visible = false;
    //       // // if (scale.distance > 100000) {
    //       // if (scale.top > 100000) {
    //       //   compareSprite.visible = false;
    //       // }
    //       // // 缩小 4 倍在 retina 屏幕会比较高清
    //       // compareSprite.scale.set(
    //       //   scale[0] / this.scale,
    //       //   scale[1] / this.scale,
    //       //   1.0
    //       // );
    //       // 缩小 4 倍在 retina 屏幕会比较高清
    //       compareSprite.scale.set(
    //         scale.x / this.scale,
    //         scale.y / this.scale,
    //         1.0
    //       );
    //       // 是否需要碰撞检测
    //       if (this.options.collision && compareSprite.visible) {
    //         for (let j = i + 1, jl = sprites.length; j < jl; j++) {
    //           const sprite = sprites[j];
    //           if (sprite.visible) {
    //             if (this.isMarkerCollision(compareSprite, sprite))
    //               sprite.visible = false;
    //           }
    //         }
    //       }
    //     }
    //   }
    // }
    getPoiScale(position, poiRect) {
        //   const tempV = firstArrow.position
        //   .clone()
        //   .applyMatrix4(camera.matrixWorldInverse)
        //   .applyMatrix4(camera.projectionMatrix);
        // if (
        //   Math.abs(tempV.x) > 1 ||
        //   Math.abs(tempV.y) > 1 ||
        //   Math.abs(tempV.z) > 1
        // ) {
        //   status = 'out';
        //   // 在视野外了
        //   // console.log('在视野外了 :>> ', '在视野外了');
        // } else {
        //   status = 'in';
        //   // 在视野内了
        //   // console.log('在视野内 :>> ', '在视野内');
        // }
        const { camera, info: { boundingClientRect: { height } } } = this.map;
        const distance = camera.position.distanceTo(position); // 相机和标注点的距离
        const top = Math.tan(((camera.fov / 2) * Math.PI) / 180) * distance; // camera.fov 相机的拍摄距离
        const meterPerPixel = (2 * top) / height;
        const scaleX = poiRect.w * meterPerPixel;
        const scaleY = poiRect.h * meterPerPixel;
        // 是否在视野外
        const tempPosi = position.clone().project(camera);
        const SCALE = 1;
        const out = Math.abs(tempPosi.x) > SCALE ||
            Math.abs(tempPosi.y) > SCALE ||
            Math.abs(tempPosi.z) > SCALE;
        // return [scaleX, scaleY, 1.0];
        return { x: scaleX, y: scaleY, distance, top, out };
    }
    // /**
    //  * 检测两个标注 sprite 是否碰撞
    //  */
    isMarkerCollision(compareSprite, sprite) {
        const comparePosition = this.toScreenPos([
            compareSprite.position.x,
            compareSprite.position.y,
            compareSprite.position.z
        ], this.map.camera);
        const spritePosition = this.toScreenPos([sprite.position.x, sprite.position.y, sprite.position.z], this.map.camera);
        const image1 = compareSprite.material.map.image;
        const image2 = sprite.material.map.image;
        const w1 = image1.width / this.scale;
        const h1 = image1.height / this.scale;
        const x1 = comparePosition.x - w1 / 2;
        const y1 = comparePosition.y - h1 / 2;
        const w2 = image2 ? image2.width / this.scale : 0;
        const h2 = image2 ? image2.height / this.scale : 0;
        const x2 = spritePosition.x - w2 / 2; // 点2左下角的xy点
        const y2 = spritePosition.y - h2 / 2;
        if (x1 >= x2 && x1 >= x2 + w2) {
            return false;
        }
        else if (x1 <= x2 && x1 + w1 <= x2) {
            return false;
        }
        else if (y1 >= y2 && y1 >= y2 + h2) {
            return false;
        }
        else if (y1 <= y2 && y1 + h1 <= y2) {
            return false;
        }
        else {
            return true;
        }
    }
    /**
     * three世界坐标转为屏幕坐标
     */
    toScreenPos(position, camera) {
        const { info: { boundingClientRect: { left, top, width, height } } } = this.map;
        const worldVector = new three.Vector3(position[0], position[1], position[2]);
        const standardVector = worldVector.project(camera); // 世界坐标转标准设备坐标
        // // ❌ 这些写法会触发重排，导致性能下降
        // // this.map.$map!.getBoundingClientRect();
        // // this.halfMapWidth = this.map.$map!.clientWidth / 2;
        // // this.halfMapHeight = this.map.$map!.clientHeight / 2;
        // // window.innerWidth;
        // // window.innerHeight;
        const halfWidth = width / 2;
        const halfHeight = height / 2;
        const x = Math.round(standardVector.x * halfWidth + halfWidth); // 标准设备坐标转屏幕坐标
        const y = Math.round(-standardVector.y * halfHeight + halfHeight); // 标准设备坐标转屏幕坐标
        return {
            x: x + left,
            y: y + top
        };
    }
}
Object.defineProperty(LabelsLayer, "NAME", {
    enumerable: true,
    configurable: true,
    writable: true,
    value: 'LabelsLayer'
});

exports.LabelMarker = LabelMarker;
exports.LabelsLayer = LabelsLayer;
