import * as THREE from 'three';
import TWEEN from '@tweenjs/tween.js';

export default function useMapMarkedLightPillar(options = {}) {
  const defaultOptions = {
    scaleFactor: 1.0,
    color: 0x00ffff,
    opacity: 0.8
  };
  
  const config = { ...defaultOptions, ...options };
  
  /**
   * 创建标记点网格
   * @param {number} x - X坐标
   * @param {number} y - Y坐标
   * @param {number} scaleFactor - 缩放因子
   * @returns {THREE.Mesh} 标记点网格
   */
  const createPointMesh = (x, y, scaleFactor = 1) => {
    const geometry = new THREE.SphereGeometry(0.05, 16, 16);
    const material = new THREE.MeshBasicMaterial({
      color: config.color,
      transparent: true,
      opacity: config.opacity
    });
    
    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(x, y, 0);
    mesh.scale.set(scaleFactor, scaleFactor, scaleFactor);
    
    return mesh;
  };
  
  /**
   * 创建光晕效果
   * @param {number} x - X坐标
   * @param {number} y - Y坐标
   * @param {number} scaleFactor - 缩放因子
   * @returns {THREE.Mesh} 光晕网格
   */
  const createLightHalo = (x, y, scaleFactor = 1) => {
    // 创建光晕纹理 - 使用单色替代渐变
    const canvas = document.createElement('canvas');
    canvas.width = 256;
    canvas.height = 256;
    const ctx = canvas.getContext('2d');
    
    // 绘制圆形光晕，中心实色，边缘透明
    ctx.fillStyle = 'rgba(0, 255, 255, 0.6)';
    ctx.beginPath();
    ctx.arc(128, 128, 64, 0, Math.PI * 2);
    ctx.fill();
    
    // 外圈较淡的圆
    ctx.fillStyle = 'rgba(0, 255, 255, 0.2)';
    ctx.beginPath();
    ctx.arc(128, 128, 100, 0, Math.PI * 2);
    ctx.fill();
    
    const texture = new THREE.CanvasTexture(canvas);
    
    const geometry = new THREE.PlaneGeometry(0.5, 0.5);
    const material = new THREE.MeshBasicMaterial({
      map: texture,
      transparent: true,
      opacity: 0.6,
      depthTest: false
    });
    
    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(x, y, 0.01);
    mesh.scale.set(scaleFactor, scaleFactor, scaleFactor);
    
    // 添加缩放动画
    const animate = () => {
      new TWEEN.Tween(mesh.scale)
        .to({ x: scaleFactor * 1.5, y: scaleFactor * 1.5, z: scaleFactor * 1.5 }, 2000)
        .easing(TWEEN.Easing.Sinusoidal.InOut)
        .yoyo(true)
        .repeat(Infinity)
        .start();
    };
    
    animate();
    
    return mesh;
  };
  
  /**
   * 创建光柱
   * @param {number} x - X坐标
   * @param {number} y - Y坐标
   * @param {number} heightScaleFactor - 高度缩放因子
   * @returns {THREE.Group} 光柱组
   */
  const createLightPillar = (x, y, heightScaleFactor = 1) => {
    const group = new THREE.Group();
    
    // 创建光柱纹理 - 使用单色替代渐变
    const canvas = document.createElement('canvas');
    canvas.width = 64;
    canvas.height = 256;
    const ctx = canvas.getContext('2d');
    
    // 绘制实色光柱，中部较亮
    ctx.fillStyle = 'rgba(0, 255, 255, 0.8)';
    ctx.fillRect(0, 25, 64, 206); // 中部主体
    
    // 上下边缘稍淡
    ctx.fillStyle = 'rgba(0, 255, 255, 0.4)';
    ctx.fillRect(0, 0, 64, 25);   // 顶部
    ctx.fillRect(0, 231, 64, 25); // 底部
    
    const texture = new THREE.CanvasTexture(canvas);
    
    // 创建两个相交的平面形成光柱
    const height = 2 * heightScaleFactor;
    const width = 0.1;
    
    // 第一个平面
    const geometry1 = new THREE.PlaneGeometry(width, height);
    const material = new THREE.MeshBasicMaterial({
      map: texture,
      transparent: true,
      opacity: 0.8,
      depthTest: false,
      side: THREE.DoubleSide
    });
    
    const plane1 = new THREE.Mesh(geometry1, material);
    plane1.position.set(x, y, height / 2);
    
    // 第二个平面（旋转90度）
    const plane2 = plane1.clone();
    plane2.rotation.z = Math.PI / 2;
    
    // 底部光点
    const bottomMesh = createPointMesh(x, y, config.scaleFactor);
    
    // 光晕效果
    const halo = createLightHalo(x, y, config.scaleFactor);
    
    group.add(plane1);
    group.add(plane2);
    group.add(bottomMesh);
    group.add(halo);
    
    return group;
  };
  
  /**
   * 设置光柱颜色
   * @param {THREE.Group} lightPillar - 光柱组
   * @param {number} color - 颜色值
   */
  const setLightPillarColor = (lightPillar, color) => {
    lightPillar.children.forEach(child => {
      if (child.material) {
        child.material.color.setHex(color);
      }
    });
  };
  
  /**
   * 设置网格四元数（用于球面定位）
   * @param {THREE.Object3D} mesh - 网格对象
   * @param {number} lng - 经度
   * @param {number} lat - 纬度
   * @param {number} radius - 半径
   */
  const setMeshQuaternion = (mesh, lng, lat, radius = 1) => {
    const phi = (90 - lat) * (Math.PI / 180);
    const theta = (lng + 180) * (Math.PI / 180);
    
    const x = -(radius * Math.sin(phi) * Math.cos(theta));
    const z = radius * Math.sin(phi) * Math.sin(theta);
    const y = radius * Math.cos(phi);
    
    mesh.position.set(x, y, z);
    mesh.lookAt(0, 0, 0);
  };
  
  /**
   * 获取射线检测对象
   * @param {THREE.Camera} camera - 相机
   * @param {THREE.Vector2} mouse - 鼠标位置
   * @param {Array} objects - 检测对象数组
   * @returns {Array} 相交对象数组
   */
  const getRaycasterObj = (camera, mouse, objects) => {
    const raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(mouse, camera);
    return raycaster.intersectObjects(objects, true);
  };
  
  /**
   * 选择光柱
   * @param {Event} event - 鼠标事件
   * @param {THREE.Camera} camera - 相机
   * @param {Array} lightPillars - 光柱数组
   * @param {HTMLElement} container - 容器元素
   * @returns {Object|null} 选中的光柱信息
   */
  const chooseLightPillar = (event, camera, lightPillars, container) => {
    const rect = container.getBoundingClientRect();
    const mouse = new THREE.Vector2();
    
    mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
    
    const intersects = getRaycasterObj(camera, mouse, lightPillars);
    
    if (intersects.length > 0) {
      return {
        object: intersects[0].object,
        point: intersects[0].point,
        distance: intersects[0].distance
      };
    }
    
    return null;
  };
  
  return {
    createPointMesh,
    createLightHalo,
    createLightPillar,
    setLightPillarColor,
    setMeshQuaternion,
    getRaycasterObj,
    chooseLightPillar
  };
}