import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader.js";
import {
  Box3,
  BoxGeometry,
  Group,
  Mesh,
  MeshBasicMaterial,
  Object3D,
  Object3DEventMap,
  Vector3,
} from "three";
import { getImg } from "@/utils";
import { modelMaterial } from "./material";
import { CSS3DSprite } from "three/examples/jsm/renderers/CSS3DRenderer.js";
import { initModelsLight } from "./vfx";
// import { initModelsLight } from "./vfx";

const modelGroup = new Group();
modelGroup.name = "模型组";

//获取模型
function getBoxObject(mesh: Object3D<Object3DEventMap>) {
  const box = new Box3().setFromObject(mesh);
  // const boxSize = box.getSize(new Vector3()).length();
  const boxCenter = box.getCenter(new Vector3());
  return [box, boxCenter];
}

function tag3D(name: string) {
  // 创建div元素(作为标签)
  let div = document.createElement("div");
  div.innerHTML = name;
  // div.style.color = "#ffffff";
  // div.classList.add("tag");
  //div元素包装为CSS3模型对象CSS3DObject
  let label = new CSS3DSprite(div);
  div.style.pointerEvents = "none"; //避免HTML标签遮挡三维场景的鼠标事件
  // 设置HTML元素标签在three.js世界坐标中位置
  // label.position.set(x, y, z);
  //缩放CSS3DObject模型对象
  label.scale.set(0.02, 0.02, 0.02); //根据相机渲染范围控制HTML 3D标签尺寸
  label.rotateY(Math.PI / 2); //控制HTML标签CSS3对象姿态角度
  // label.rotateX(-Math.PI/2);
  return label; //返回CSS3模型标签
}

function dialog(html: string) {
  //div元素包装为CSS3模型对象CSS3DSprite
  const element = document.createElement("div");
  element.className = "tag";
  element.innerHTML = html;
  const dialog = new CSS3DSprite(element);
  element.style.pointerEvents = "none"; //避免HTML标签遮挡三维场景的鼠标事件
  // 设置HTML元素标签在three.js世界坐标中位置
  // label.position.set(x, y, z);
  //缩放CSS3DSprite模型对象
  dialog.scale.set(0.01, 0.01, 0.01); //根据相机渲染范围控制HTML 3D标签尺寸
  dialog.rotateY(Math.PI / 2); //控制HTML标签CSS3对象姿态角度
  // dialog.rotateX(-Math.PI/2);
  return dialog; //返回CSS3模型标签
}

//加载楼宇模型
async function loadBuilding() {
  const model = await loadModels({
    url: "./models/lou.fbx",
    isBlending: false,
  });
  const [box] = getBoxObject(model);
  model.scale.set(0.005, 0.005, 0.005);
  //@ts-ignore
  model.position.set(0, -box.min.y, -8);
  // console.log(model, -box.min.y);
  const label3D = tag3D("负荷"); //设置标签名称
  let dialog3D = dialog(`
      <div class="w-[341px] h-[190px] bg-sky-900/50 border-2 border-cyan-200/80" id="load">
        <div class="font-bold ml-4 border-l-4 border-sky-200 my-3 pl-2">负荷</div>
        <div class="grid grid-cols-2 gap-2 px-3 text-sm [&>div]:bg-sky-900/60 [&>div]:whitespace-nowrap [&>div]:py-2 [&>div]:pl-1">
          <div>
            <span>用电负荷：</span>
            <span class="value">461kW·h</span>
          </div>
          <div>
            <span>总用电量：</span>
            <span class="value">1465kW·h</span>
          </div>
          <div>
            <span>自发自用：</span>
            <span class="value">245kW·h</span>
          </div>
          <div>
            <span>空调风速：</span>
            <span class="value">0M/s</span>
          </div>
          <div>
            <span>空调温度：</span>
            <span class="value">0℃</span>
          </div>
          <div>
            <span>灯光亮度：</span>
            <span class="value">100%</span>
          </div>
        </div>
      </div>
      `);
  // dialog3D.position.copy(model.position);
  dialog3D.scale.set(2, 2, 2);
  dialog3D.position.y += 400;
  // label3D.position.copy(model.position);
  label3D.scale.set(4, 4, 4);
  label3D.position.y += 150;
  label3D.position.x += 100;

  const geometry = new BoxGeometry(1.5, 1, 1);
  const matarial = new MeshBasicMaterial({
    color: "#ffa94d",
    blending: 2,
    opacity: 1,
    // side: 2,
    // transparent: true,
    // opacity: 0.5,
  });

  const mesh = new Mesh(geometry, matarial);
  mesh.rotateY(Math.PI / 2);
  mesh.scale.set(235, 180, 215);
  //@ts-ignore
  mesh.position.y = -65;
  mesh.name = "负荷外光";

  model.name = "负荷";
  model.add(dialog3D, label3D, mesh);

  modelGroup.add(model);
}

//给风力添加叶子旋转动画
function addWindPowerAnimate(model: Object3D) {
  const mesh = model.getObjectByName("yezi");
  if (!mesh) return;
  const group = new Group();
  // mesh.position.x = -1000;
  group.position.set(0, 1080, 0);
  mesh.position.set(0, -1080, 0);
  group.add(mesh);
  model.add(group);
  //@ts-ignore
  group.animate = function () {
    //@ts-ignore
    group.rotateZ(0.03);
    //@ts-ignore
    group.animateIndex = requestAnimationFrame(group.animate);
  };

  // @ts-ignore
  group.animate();
}

//加载光伏模型
async function loadPhotovoltaic() {
  const gfModel = await loadModels({
    url: "./models/guangfu.fbx",
  });
  const flModel = await loadModels({
    url: "./models/fengli.fbx",
    scale: 0.0005,
  });

  addWindPowerAnimate(flModel);
  console.log(flModel);
  const obj = new Object3D();
  gfModel.rotateY(Math.PI / 2);
  flModel.rotateY(Math.PI / 2);
  // const [box] = getBoxObject(gfModel);
  const [box2] = getBoxObject(flModel);
  // console.log(box);
  // @ts-ignore
  obj.position.set(-8, -box2.min.y, 0);
  // @ts-ignore
  gfModel.position.set(0, -0.65, -0.5);

  const label3D = tag3D("光伏"); //设置标签名称
  label3D.position.copy(gfModel.position);
  label3D.position.y += 0.85;
  label3D.position.x += 0;

  const gllabel3D = tag3D("风力"); //设置标签名称
  gllabel3D.position.copy(flModel.position);
  gllabel3D.position.y += 1.1;
  gllabel3D.position.x += 0;

  let dialog3D = dialog(`
  <div class="w-[420px] h-[240px] bg-sky-900/50 border-2 border-cyan-200/80">
    <div class="font-bold ml-4 border-l-4 border-sky-200 my-3 pl-2">风力/光伏</div>
    <div class="grid grid-cols-2 gap-2 px-3 text-sm [&>div]:bg-sky-900/60 [&>div]:whitespace-nowrap [&>div]:py-2 [&>div]:pl-1">
      <div>
        <span>风力装机容量：</span>
        <span class="value">1.31kW·h</span>
      </div>
      <div>
        <span>风力发电量：</span>
        <span class="value">245kW·h</span>
      </div>
      <div>
        <span>风力发电功率：</span>
        <span class="value">127.51kW·h</span>
      </div>
      <div>
        <span>光伏上网功率：</span>
        <span class="value">1140kW·h</span>
      </div>
      <div>
        <span>光伏装机容量：</span>
        <span class="value">1.31kW·h</span>
      </div>
      <div>
        <span>光伏发电量：</span>
        <span class="value">245kW·h</span>
      </div>
      <div>
        <span>光伏发电功率：</span>
        <span class="value">127.51kW·h</span>
      </div>
      <div>
        <span>光伏上网功率：</span>
        <span class="value">1140kW·h</span>
      </div>
    </div>
  </div>
  `);
  dialog3D.position.copy(flModel.position);
  dialog3D.position.y += 2.7;

  obj.name = "风力/光伏";
  obj.add(gfModel, flModel, label3D, gllabel3D, dialog3D);

  modelGroup.add(obj);
}

//能源路由器
//   function loadEnergyRouter() {
//     const loader = new FBXLoader();
//     loader.load("./models/server.fbx", function (model) {
//       const material = new MeshStandardMaterial({
//         color: "#18c5f4",
//         transparent: true,
//         opacity: 0.5,
//         blending: 1,
//       });
//       // const material = getBuildingsMaterial(
//       //   "#ffffff", // 设置模型的颜色
//       //   getImg("models/dl01.png"),
//       //   0.8, // 设置透明度为50%
//       //   1
//       // );
//       model.traverse((child: any) => {
//         if (child.isMesh) {
//           child.material = material;
//           var edges = new EdgesGeometry(child.geometry);
//           var line = new LineSegments(edges, otherlineMaterial);
//           child.add(line);
//         }
//       });
//       model.rotateY(Math.PI / 2);
//       model.scale.set(0.005, 0.005, 0.005);
//       const [box] = getBoxObject(model);
//       // console.log(box);
//       // @ts-ignore
//       model.position.set(0, -box.min.y, -4);
//       const model1 = model.clone();
//       model1.traverse((child: any) => {
//         if (child.isMesh) {
//           child.material = new MeshStandardMaterial({
//             color: "#18c5f4",
//             transparent: true,
//             opacity: 0.5,
//             blending: 2,
//           });
//         }
//       });
//       modelGroup.add(model);
//       modelGroup.add(model1);
//     });
//   }

//加载储存能源模型
async function loadStoredEnergy() {
  const model = await loadModels({
    url: "./models/chucun.fbx",
  });

  model.rotateY(Math.PI + 1.2);
  model.scale.set(0.008, 0.008, 0.008);
  const [box] = getBoxObject(model);
  // console.log(box);
  // @ts-ignore
  model.position.set(-8, -box.min.y, -8);
  const label3D = tag3D("储能"); //设置标签名称

  let dialog3D = dialog(`
  <div class="w-[341px] h-[140px] bg-sky-900/50 border-2 border-cyan-200/80">
    <div class="font-bold ml-4 border-l-4 border-sky-200 my-3 pl-2">储能</div>
    <div class="grid grid-cols-2 gap-2 px-3 text-sm [&>div]:bg-sky-900/60 [&>div]:whitespace-nowrap [&>div]:py-2 [&>div]:pl-1">
      <div>
        <span>电池容量：</span>
        <span class="value">200kW·h</span>
      </div>
      <div>
        <span>电池电量：</span>
        <span class="value">17kW·h</span>
      </div>
      <div>
        <span>有功功率：</span>
        <span class="value">0.00kW·h</span>
      </div>
      <div>
        <span>储能soc：</span>
        <span class="value">9%</span>
      </div>
    </div>
  </div>
  `);

  dialog3D.scale.set(1.4, 1.4, 1.4);
  dialog3D.position.y += 280;
  label3D.scale.set(2.7, 2.7, 2.7);
  label3D.position.y += 130;
  label3D.position.x += 0;

  model.name = "储能";
  model.add(label3D, dialog3D);

  modelGroup.add(model);
}

//加载电站模型
//   function loadPowerStation() {
//     const loader = new FBXLoader();
//     loader.load("./models/dianzhan.fbx", function (model) {
//       const material = getBuildingsMaterial(
//         "#ffffff", // 设置模型的颜色
//         getImg("models/dl01.png"),
//         0.8, // 设置透明度为50%
//         1
//       );
//       model.traverse((child: any) => {
//         if (child.isMesh) {
//           child.material = material;
//           // var edges = new EdgesGeometry(child.geometry);
//           // var line = new LineSegments(edges, otherlineMaterial);
//           // child.add(line);
//         }
//       });
//       model.scale.set(0.005, 0.005, 0.005);
//       const [box] = getBoxObject(model);
//       // console.log(box);
//       // @ts-ignore
//       model.position.set(-5.2, -box.min.y, -3.5);
//       modelGroup.add(model);
//     });
//   }

//电网
async function loadElectricPole() {
  const model = await loadModels({
    url: "./models/dianxiangan.fbx",
  });
  const model1 = await loadModels({
    url: "./models/dianzhan.fbx",
  });
  const obj = new Object3D();
  model.rotateY(Math.PI / 2);
  model.scale.set(0.008, 0.008, 0.008);
  // const [box] = getBoxObject(model);
  const [box1] = getBoxObject(model1);
  model1.rotateY(Math.PI / 2);
  // @ts-ignore
  obj.position.set(0, -box1.min.y, 0);
  // console.log(box);
  //@ts-ignore
  model.position.set(-1, -box1.min.y + 0.06, 0);
  // @ts-ignore
  // model1.position.set(0, -box1.min.y, 0);
  const label3D = tag3D("电网"); //设置标签名称
  label3D.position.copy(model.position);
  label3D.position.y += 1.3;
  label3D.position.x += 0;

  let dialog3D = dialog(`
  <div class="w-[360px] h-[99px] bg-sky-900/50 border-2 border-cyan-200/80">
    <div class="font-bold ml-4 border-l-4 border-sky-200 my-3 pl-2">电网</div>
    <div class="grid grid-cols-2 gap-2 px-3 text-sm [&>div]:bg-sky-900/60 [&>div]:whitespace-nowrap [&>div]:py-2 [&>div]:pl-1">
      <div>
        <span>进线负荷：</span>
        <span class="value">293.55kW·h</span>
      </div>
      <div>
        <span>购电电费：</span>
        <span class="value">965.02元</span>
      </div>
    </div>
  </div>
  `);
  dialog3D.position.copy(model.position);
  dialog3D.position.y += 2.15;

  obj.name = "电网";
  obj.add(model1, model, label3D, dialog3D);

  modelGroup.add(obj);
}

// //加载风力模型
// function loadWindPower() {
//   return new Promise((resolve) => {
//     const loader = new FBXLoader();
//     loader.load("./models/fengli.fbx", function (model) {
//       // const material = new MeshStandardMaterial({
//       //   color: "#18c5f4",
//       //   transparent: true,
//       //   opacity: 0.5,
//       // });

//       const material = getBuildingsMaterial(
//         "#ffffff", // 设置模型的颜色
//         getImg("models/dl01.png"),
//         0.8, // 设置透明度为50%
//         1
//       );
//       model.traverse((child: any) => {
//         if (child.isMesh) {
//           child.material = material; // 允许透明度
//         }
//       });
//       model.rotateY(Math.PI / 2);
//       model.scale.set(0.005, 0.005, 0.005);
//       const [box] = getBoxObject(model);
//       // console.log(box);
//       // @ts-ignore
//       model.position.set(-8, -box.min.y, 0);
//       const label3D = tag3D("风力"); //设置标签名称
//       label3D.position.copy(model.position);
//       label3D.position.y += 1;
//       label3D.position.x += 0;
//       let dialog3D = dialog(`
//       <div class="w-[341px] h-[99px] bg-[url('assets/images/models/dialog.png')]">
//         <div class="font-bold ml-4">风力/光伏</div>
//         <div class="grid grid-cols-2 gap-2 p-3 text-sm">
//           <div>
//             <span>装机容量：</span>
//             <span class="value">1.31kW·h</span>
//           </div>
//           <div>
//             <span>发电量：</span>
//             <span class="value">245kW·h</span>
//           </div>
//           <div>
//             <span>发电功率：</span>
//             <span class="value">127.51kW·h</span>
//           </div>
//           <div>
//             <span>上网功率：</span>
//             <span class="value">0.00kW·h</span>
//           </div>
//         </div>
//       </div>
//       `);
//       dialog3D.position.copy(model.position);
//       dialog3D.position.y += 2;
//       model.name = "风力";
//       const model2 = model.clone();
//       const texture = new TextureLoader().load(getImg("models/dl01.png"));
//       texture.needsUpdate = true; //使用贴图时进行更新
//       texture.wrapS = texture.wrapT = RepeatWrapping;
//       const material2 = new MeshStandardMaterial({
//         color: "#ffffff",
//         transparent: false,
//         opacity: 0.7,
//         map: texture,
//       });
//       model2.traverse((child: any) => {
//         if (child.isMesh) {
//           child.material = material2;
//         }
//       });
//       modelGroup.add(model, model2, label3D, dialog3D);
//       resolve(model);
//     });
//   });
// }

//加载模型
type ModelType = {
  url: string;
  scale?: number;
  isBlending?: boolean;
};
function loadModels({
  url,
  scale = 0.005,
  isBlending = true,
}: ModelType): Promise<Object3D> {
  const loader = new FBXLoader();
  return new Promise((resolve) => {
    // const { url, scale } = content;
    loader.load(url, function (model) {
      // const [box] = getBoxObject(model);
      // @ts-ignore
      // model.position.set(x || 0, -box.min.y, z || 0);
      model.scale.set(scale, scale, scale);
      const params = {
        img: getImg("models/dl01.png"),
        color: "#ffffff", // 设置模型的颜色
        // opacity: 0.8, // 设置透明度为50%
        // blending: 2,
        // alphaTest: 0.8,
        // side: 2,
        opacity: isBlending ? 0.8 : 1, // 设置透明度为50%
        blending: isBlending ? 2 : 0,
        side: isBlending ? 2 : 0,
        alphaTest: isBlending ? 0.8 : 0,
        repeat: 1,
        // depthWrite: false,
        // depthTest: false,
      };
      // console.log(params);

      const material = modelMaterial(params);
      model.traverse((child: any) => {
        if (child.isMesh) {
          child.material = material;
          // var edges = new EdgesGeometry(child.geometry);
          // var line = new LineSegments(edges, otherlineMaterial);
          // child.add(line);
        }
      });

      // const model2 = model.clone();
      // const material2 = modelMaterial({
      //   img: getImg("models/dl01.png"),
      //   color: "#ffffff",
      //   transparent: false,
      //   // opacity: 0.7,
      // });
      // model2.traverse((child: any) => {
      //   if (child.isMesh) {
      //     child.material = material2;
      //   }
      // });
      // model.add(model2);
      resolve(model);
    });
  });
}

async function initModels() {
  console.log("initModels");
  await loadBuilding();
  // await loadWindPower();
  await loadStoredEnergy();
  // loadEnergyRouter();
  await loadElectricPole();
  await loadPhotovoltaic();
  // loadPowerStation();
  //光效
  initModelsLight();
}

export { modelGroup, initModels, getBoxObject };
