import * as THREE from "three";
import TextLabel from "./object/TextLabel";
import ImgLabel from "./object/ImgLabel";
import ImgLabelBox from "./object/ImgLabelBox";
import SimpleLabel from "./object/SimpleLabel";
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";

export default class VerticalBox extends THREE.Group {
  constructor(manager, data, index, total) {
    super();
    this.manager = manager;
    this.total = total;
    this.name = "vertical_box";
    this.getStyle();
    this.load(data, index);
  }
  getStyle() {
    this.width = 2;
    this.height = (2 * 710) / 500;
    this.color = 0xffffff;
  }

  load(data, index) {
    //box
    const geometry = new THREE.PlaneGeometry(1, 1);
    geometry.rotateX(-Math.PI / 2);

    const bm = new THREE.MeshBasicMaterial({
      color: this.color,
    });

    const box = new THREE.Mesh(geometry, bm);
    box.scale.set(this.width, 1, this.height);

    this.add(box);
    this.position.x = (this.width + 0.125) * index - 1.8;

    const matLine = new LineMaterial({
      color: 0xe44d54,
      linewidth: 4, // in world units with size attenuation, pixels otherwise
      dashed: false,
      alphaToCoverage: true,
    });
    matLine.resolution = new THREE.Vector2(
      this.manager.scene.width,
      this.manager.scene.height
    );
    //content
    data.forEach((i, j) => {
      //img
      let img;
      this.manager.loader.load(i.imgUrl, (texture) => {
        let imgRatio = texture.image.width / texture.image.height;
        let planeRatio = 1.5 / 2;
        texture.matrixAutoUpdate = false;
        //放开所有uv的比例
        if (planeRatio > imgRatio) {
          // texture.matrix.setUvTransform(
          //   0,
          //   0,
          //   planeRatio / imgRatio,
          //   1,
          //   0,
          //   0.5,
          //   0.5
          // );
        } else {
          // debugger
          // texture.matrix.setUvTransform(
          //   0,
          //   0,
          //   1,
          //   imgRatio / planeRatio,
          //   0,
          //   0.5,
          //   0.5
          // );
        }

        texture.colorSpace = THREE.SRGBColorSpace;

        // texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
        // texture.repeat.set(2, 2); // 纹理平铺两次
        // texture.offset.set(0.5, 0.5); // 纹理偏移到中心
        img = new ImgLabelBox(texture, matLine, false);

        img.userData = i.id;
        img.position.y += 1;
        img.position.z -= 0.2;
        this.add(img);
        this.manager.imgList.push(img);
        const textlabel = new TextLabel(i.imgInfo, true);
        this.add(textlabel);
        textlabel.position.copy(img.position);
        textlabel.position.z += textlabel.scale.z * 0.5 + 0.7;
      });
    });

    //页脚
    const f_txt_label = ` 第 ${index + 1} 页  共 ${this.total} 页`;
    const footlabel = new SimpleLabel(f_txt_label, true);
    footlabel.renderOrder = 100;
    footlabel.position.z += 1.26;

    this.add(footlabel);
  }
}
