import React, {useCallback, useEffect, useRef, useState} from "react";
import io from "../utils/socket.io";

export const useSocket = (
    {
        socketEmit = "timePerformanceGoodProduct",
        socketScreenType,
        workCenterCode,
        operationCode,
        date
    } = {},
    loaclData
) => {
    const [data, setData] = useState();
    const socket = useRef();

    // 发送自定义事件
    const reload = useCallback(() => {
        if (loaclData) {
            // console.log("loaclData", loaclData);
            setData(loaclData);
        } else {
            if (!workCenterCode) return;
            let query = {
                operationCode: operationCode,
                workCenterCode: workCenterCode,
                screenType: socketScreenType,
                date: date
            };
            // console.log("fetch", socketEmit, {query});
            socket.current?.emit(socketEmit, "channel", {query});
        }
    }, [workCenterCode, socketScreenType, socketEmit, loaclData]);

    useEffect(() => {
        if (loaclData) {
            reload();
        } else {
            let {ioSocketUrl, ioSocketPath} = window.config || {};
            socket.current = io.connect(ioSocketUrl, {path: ioSocketPath, transports: ['websocket']});
            socket.current.on("disconnect", function () {
                console.log("连接断开！");
            });
            socket.current.on("connect_error", function (e) {
                console.log("连接失败！", e);
            });
            socket.current.on("connect", function () {
                console.log("连接成功！");
                reload();
            });
            // 接收自定义事件
            socket.current.on(socketEmit, function (res) {
                try {
                    res = JSON.parse(res);
                    console.log(res, "res");
                    if (res.data) {
                        // console.log("res.data", res.data)
                        setData(res.data);
                    }
                } catch (e) {
                    console.log(e);
                }
            });
        }
    }, [reload, socketEmit]);

    return [data, reload];
};
