/* eslint-disable array-callback-return */
/* eslint-disable no-unused-vars */
import * as THREE from "three";
import {
  Canvas,
  useFrame,
  extend,
  useLoader,
  useThree,
  axesHelper,
} from "react-three-fiber";
import { useRef, Suspense, useState, useEffect } from "react";
import { OrbitControls } from "@react-three/drei";
import {
  useWebSocket,
  useFullscreen,
  useThrottle,
  useRequest,
  useAsyncEffect,
} from "ahooks";
import {
  ShrinkOutlined,
  CloseCircleFilled,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import { Tooltip, notification } from "antd";
import Model from "./models/gltf";
import Robot from "./models";
import Jixiebi from "./models/jiqiebi";
import { doFetch } from "../utils/doFetch";
import {
  Selection,
  EffectComposer,
  Outline,
} from "@react-three/postprocessing";

let infos = {
  device_5: "能耗1(1-12设备)",
  device_6: "能耗2(13-24设备)",
  device_1: "数控车床T360-2",
  device_2: "数控车床T360-1",
  device_3: "立式智能加工中心M850b",
  device_4: "立式智能加工中心M850",
};

const modelconfig = [
  {
    name: "0",
    position: [-24, 0, 24],
    status: 1,
    modelname: "cqg",
    scale: 0.035,
  },
  {
    name: "1",
    position: [-21.5, 0, 24],
    status: 1,
    modelname: "kyj",
  },
  {
    name: "2",
    position: [-21.5, 0, 25.5],
    status: 1,
    modelname: "lgj",
    scale: 0.06,
  },
  {
    name: "3",
    position: [-19, 0, 15],
    status: 1,
    modelname: "ptwymc",
    rotation: [0, 1.6, 0],
  },
  {
    name: "4",
    position: [-21, 0, 6.5],
    status: 1,
    modelname: "pmmc",
    scale: 0.06,
  },
  {
    name: "5",
    position: [-21, 0, -12],
    status: 1,
    modelname: "M1.4",
  },
  {
    name: "6",
    position: [-21, 0, -4],
    status: 1,
    modelname: "M1.4",
  },
  {
    name: "7",
    position: [-21, 0, -22],
    status: 1,
    modelname: "M8",
    rotation: [0, 1.6, 0],
  },
  {
    name: "8",
    position: [-6, 0, -22],
    status: 1,
    modelname: "M8",
    rotation: [0, 1.6, 0],
  },
  {
    name: "9",
    position: [3, 0, -22],
    status: 1,
    modelname: "M8",
    rotation: [0, 1.6, 0],
  },
  {
    name: "10",
    position: [12, 0, -22],
    status: 1,
    modelname: "M8",
    rotation: [0, 1.6, 0],
  },
  {
    name: "11",
    position: [21, 0, -22],
    status: 1,
    modelname: "M8",
    rotation: [0, 1.6, 0],
  },
  {
    name: "12",
    position: [18, 0, -20.5],
    status: 1,
    modelname: "T360",
    scale: 0.75,
  },
  {
    name: "13",
    position: [5.7, 0, -7],
    status: 1,
    modelname: "T360",
    scale: 0.75,
    rotation: [0, 1.6, 0],
  },
  {
    name: "14",
    position: [19.8, 0, 8],
    status: 1,
    modelname: "M850",
    scale: 0.052,
    rotation: [0, 1.58, 0],
  },
  {
    name: "15",
    position: [18, 0, 17],
    status: 1,
    modelname: "M8",
  },
  {
    name: "16",
    position: [18, 0, 25],
    status: 1,
    modelname: "M8",
  },
  {
    name: "17",
    position: [11, 0, 26],
    status: 1,
    modelname: "M1.4",
  },
  {
    name: "18",
    position: [16.5, 0, 18.5],
    status: 1,
    modelname: "T360",
    scale: 0.75,
    rotation: [0, -1.58, 0],
  },
  {
    name: "19",
    position: [11, 0, 8],
    status: 1,
    modelname: "M850",
    scale: 0.052,
    rotation: [0, -1.58, 0],
  },
  {
    name: "20",
    position: [-2, 0, 9.2],
    status: 1,
    modelname: "T3.4",
    scale: 0.23,
    rotation: [0, 1.58, 0],
  },
  {
    name: "21",
    position: [-0.5, 0, 26],
    status: 1,
    modelname: "M1.4",
  },
  {
    name: "22",
    position: [-9, 0, 24.5],
    status: 1,
    modelname: "CAK5085",
    rotation: [0, -1.58, 0],
    scale: 0.04,
  },
  {
    name: "23",
    position: [-9, 0, 16.6],
    status: 1,
    modelname: "wyjmmc",
    rotation: [0, -1.58, 0],
    scale: 0.055,
  },
  {
    name: "24",
    position: [-8.79, 0, 8],
    status: 1,
    modelname: "nymc",
    rotation: [0, -1.58, 0],
    scale: 0.055,
  },
];
const statusbar = {
  1: {
    color: "#6AE49B",
    name: "运行",
  },
  2: {
    color: "#4887E0",
    name: "待机",
  },
  3: {
    color: "#8D8D8D",
    name: "关机",
  },
  4: {
    color: "#F31A1A",
    name: "故障",
  },
};
const Floor = (props) => {
  return (
    <>
      <mesh position={props.position} receiveShadow>
        <boxBufferGeometry args={[60, 0.1, 60]} />
        <meshPhysicalMaterial color={"#12284A"} />
      </mesh>
    </>
  );
};

const Bulb = (props) => {
  return (
    <mesh {...props}>
      <pointLight castShadow></pointLight>
      <ambientLight color={"#999999"}></ambientLight>
      {/* <sphereBufferGeometry args={[0.2, 60, 60]} />
      <meshPhongMaterial emissive={"yellow"} /> */}
    </mesh>
  );
};

function Threedire() {
  const texture = useLoader(THREE.TextureLoader, require("@/assets/floor.png"));
  const [equpmentNo, setequpmentNo] = useState();
  const [config, setconfig] = useState(modelconfig);
  const [info, setinfo] = useState({});
  const [modalprops, setmodalprops] = useState({
    visible: false,
    data: {},
  });
  const [alarm, setalarm] = useState({
    visible: false,
    data: {},
  });
  const { data } = useRequest(
    async () => {
      //format result
      let res = await doFetch({
          url: "/ngic-statistics/deviceStatus/queryEquipmentStatus",
          params: {},
        }),
        result = res?.data?.data ?? {};
      return result;
    },
    {
      refreshDeps: [],
    }
  );

  useEffect(() => {
    if (data) {
      setconfig((s) => {
        let news = JSON.parse(JSON.stringify(s ?? {}));
        news = news.map((it) => {
          it.status = it.name == "0" ? 3 : data[it.name];
          return it;
        });
        return news;
      });
    }
  }, [data]);

  useAsyncEffect(async () => {
    if (equpmentNo) {
      let res = await doFetch({
        url: "/ngic-statistics/deviceStatus/queryEquipmentParam",
        params: { equipmentNo: equpmentNo },
      });

      setmodalprops({
        visible: true,
        data: res?.data?.data,
      });
    } else {
      setmodalprops({
        visible: false,
      });
    }
  }, [equpmentNo]);

  const { sendMessage, lastMessage, readyState } = useWebSocket(
    `ws://192.168.40.50:7910/ws/device/status`,
    {
      onOpen: () => {
        console.log("readyState is ", readyState);
      },
      onClose: () => {
        console.log("连接关闭");
      },
      onError: (e) => {
        console.log(e);
      },
      onMessage: (message) => {
        let uir = JSON.parse(message.data);
        if(Object.values(uir).includes(0)){
          setalarm(s=>({
            ...s,
            visible:true
          }))
        }
        setinfo((s) => {
          return {
            ...s,
            ...uir,
          };
        });
      },
    }
  );

  return (
    <>
      <div
        className="status"
        style={{
          transform: alarm?.visible ? "translateY(-4px)" : `translateY(-800px)`,
          transition: "all 0.4s",
        }}
      >
        <p style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
          <span>离线设备</span>
          <CloseCircleFilled onClick={()=>{
            setalarm(s=>({
              ...s,
              visible:false
            }))
          }}/>
        </p>
        {Object.keys(infos).map((it) => {
          return (
            <div
              key={it}
              style={{ display: info[it] == 1 ? "none" : "block" }}
            >
              <ExclamationCircleFilled style={{ color: "red" }} />
              <span> {infos[it]}</span>
            </div>
          );
        })}
      </div>

      <div
        className="fixder"
        style={{
          transform: modalprops?.visible
            ? "translateY(-4px)"
            : `translateY(-800px)`,
          transition: "all 0.4s",
        }}
      >
        <div className="spread">
          <span>{modalprops?.data?.equipmentName}</span>
          <span style={{ color: statusbar[config[equpmentNo]?.status]?.color }}>
            {statusbar[config[equpmentNo]?.status]?.name}
          </span>
        </div>

        <div
          style={{
            maxHeight: 300,
            overflow: "auto",
            borderBottom: "2px solid rgba(255,255,255,0.5)",
            paddingBottom: 12,
            marginBottom: 12,
          }}
        >
          {modalprops?.data?.paramList?.map?.((it) => {
            return (
              <div className="spreaditem">
                <span>参数:{it.name}</span>
                <span>{it.value ?? "-"}</span>
              </div>
            );
          })}
        </div>
        <div style={{ color: "rgba(255,255,255,0.6)" }}>
          <span>告警信息: </span>
          <span> {modalprops?.data?.alarm}</span>
        </div>
      </div>
      <Canvas
        shadows
        camera={{
          position: [0, 30, 20],
        }}
      >
        <Selection>
          <EffectComposer multisampling={8} autoClear={false}>
            <Outline
              blur
              visibleEdgeColor="white"
              edgeStrength={20}
              width={5000}
            />
          </EffectComposer>
          {config?.map((it, i) => {
            return (
              <Model
                key={it.name}
                {...it}
                setequpmentNo={setequpmentNo}
                equpmentNo={equpmentNo}
              />
            );
          })}
        </Selection>

        {/* <Robot /> */}
        <Jixiebi />

        <Floor position={[2, -0.06, 0]} />
        <gridHelper
          args={[60, 15, "#20293A", "#20293A"]}
          position={[2, 0, 0]}
        />
        <Bulb position={[0, 6, 0]} />
        <OrbitControls />
        <>
          <mesh position={[7.5, 0, 1.4]} receiveShadow>
            <boxBufferGeometry args={[45, 0.1, 4]} />
            <meshPhysicalMaterial
              color={"green"}
              roughness={0.5}
              transmission={0.5}
            />
          </mesh>
          <mesh position={[6, 0, 15]} receiveShadow>
            <boxBufferGeometry args={[4, 0.1, 30]} />
            <meshPhysicalMaterial
              color={"green"}
              roughness={0.5}
              transmission={0.5}
            />
          </mesh>
          <mesh position={[-15, 0, 0]} receiveShadow>
            <boxBufferGeometry args={[4, 0.1, 60]} />
            <meshPhysicalMaterial
              color={"green"}
              roughness={0.5}
              transmission={0.5}
            />
          </mesh>
          <mesh position={[28, 0, 0]} receiveShadow>
            <boxBufferGeometry args={[4, 0.1, 60]} />
            <meshPhysicalMaterial
              color={"green"}
              roughness={0.5}
              transmission={0.5}
            />
          </mesh>

          <mesh position={[-7, 0, -6]} receiveShadow>
            <boxBufferGeometry args={[8, 0.1, 8]} />
            <meshPhysicalMaterial color={"grey"} map={texture} roughness={1} />
          </mesh>
          <mesh position={[-7, 0, -15.6]} receiveShadow>
            <boxBufferGeometry args={[8, 0.1, 8]} />
            <meshPhysicalMaterial color={"grey"} map={texture} roughness={1} />
          </mesh>
          <mesh position={[3, 0, -10.75]} receiveShadow>
            <boxBufferGeometry args={[9, 0.1, 17.75]} />
            <meshPhysicalMaterial color={"grey"} map={texture} roughness={1} />
          </mesh>
        </>
      </Canvas>
    </>
  );
}

export default Threedire;
