/*
 * @Author: wuhao930406 1148547900@qq.com
 * @Date: 2023-08-03 11:31:00
 * @LastEditors: wuhao930406 1148547900@qq.com
 * @LastEditTime: 2023-08-24 14:27:24
 * @FilePath: /editor-plus/src/pages/components/GlftBlock/index.jsx
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
import { Gltf, OrbitControls, Stage } from "@react-three/drei";
import { Canvas, useLoader } from "@react-three/fiber";
import { memo } from "react";
import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader";
import "./index.less";

const ModelLoader = memo(({ url = "./glb/camera.obj" }) => {
  let loader,
    urlsplit = url.split(".");

  const modelType = urlsplit[urlsplit.length - 1];

  if (modelType === "gltf" || modelType === "glb") {
    return (
      <Gltf
        src={url}
        receiveShadow
        castShadow
        position={[0, 0, 0]}
        scale={20}
        inject={
          <meshPhysicalMaterial
            color="white"
            metalness={1} // 控制金属感，1 表示完全金属
            roughness={0} // 控制光滑度，0 表示非常光滑
          />
        }
      />
    );
  } else if (modelType === "obj") {
    loader = useLoader(OBJLoader, url);
    return (
      <mesh receiveShadow castShadow scale={20}>
        <primitive
          object={loader.clone()}
          receiveShadow
          castShadow
          position={[0, 0, 0]}
        />
        <meshPhysicalMaterial
          color="white"
          metalness={1} // 控制金属感，1 表示完全金属
          roughness={0} // 控制光滑度，0 表示非常光滑
        />
      </mesh>
    );
  } else if (modelType === "fbx") {
    loader = useLoader(FBXLoader, url);
    return (
      <mesh receiveShadow castShadow scale={20}>
        <primitive
          object={loader.scene.clone()}
          receiveShadow
          castShadow
          position={[0, 0, 0]}
        />
        <meshPhysicalMaterial
          color="white"
          metalness={1} // 控制金属感，1 表示完全金属
          roughness={0} // 控制光滑度，0 表示非常光滑
        />
      </mesh>
    );
  }
});

function ThreeViewer({ url }) {
  return (
    <div className="bar-block-component">
      <Canvas style={{ height: "600px", width: "100%" }} id={"sada"}>
        <color attach="background" args={["white"]} />
        <OrbitControls></OrbitControls>
        <Stage
          intensity={0.5}
          preset="rembrandt"
          shadows={"contact"}
          adjustCamera={1}
          environment={{
            path: "/",
            files: "env.hdr",
          }}
        >
          <ModelLoader url={url} />
        </Stage>
      </Canvas>
    </div>
  );
}

export default ThreeViewer;
