import React, { useCallback, useEffect, useState, useRef } from "react";
import { message } from "antd";
import { request, getQueryVariable } from "../utils";

export const isDev = false;

let rules = (function () {
  let data = [];
  let callback = () => {};
  let setData = (res) => {
    setData = () => {};
    data = res;
    callback({ success: true, data: res });
  };
  return {
    setData,
    getData: () => data,
    loaded: new Promise((resolve, reject) => {
      callback = resolve;
    }),
  };
})();

let getRule = () => {
  getRule = () => rules.loaded;
  return request({
    method: "get",
    url: `${window.config.mesUrl}/console/getpermissions`,
  });
};

export const useRule = (code) => {
  const [ruleList, setRuleList] = useState(rules.getData());
  useEffect(() => {
    getRule().then(({ success, data } = {}) => {
      if (success) {
        setRuleList(data);
        rules.setData(data);
      }
    });
  }, []);

  if (code) return ruleList.includes(code);
  return true;
};

export const useUser = () => {
  const [data, setData] = useState();
  const getUser = useCallback(() => { 
    // let user = localStorage.getItem("userInfo");
    // try { 
    //   user = JSON.parse(user)
    // } catch (e) { 
    //   console.log(e);
    //   user = {};
    // }
    // console.log("user", user, localStorage.getItem("userInfo"))
    // setData(user);
    request({
      method: "get",
      url: `${window.config.mesUrl}/console/currentinfo`,
    }).then(({ success, data } = {}) => {
      if (success) {
        setData(data);
      } else setData();
    });
  }, [])
  // useEffect(() => {
  //   getUser();
  // }, [getUser]);
  return [data, getUser];
};

export const useEquipKey = () => {
  const [equipKey, setEquipKey] = useState();
  const getEquipKey = useCallback(() => {
    let ip = getQueryVariable("ip");
    console.log("ip", ip);
    if (!ip || ip === "null") {
      message.error("获取 ip 失败！");
    } else {
      setEquipKey(ip);
    }
  }, []);
  useEffect(() => {
    getEquipKey();
  }, [getEquipKey]);
  return { equipKey, getEquipKey };
};

export const useSetting = (equipKey) => {
  const [settingData, setSettingData] = useState({});

  const getSettingData = useCallback(() => {
    if (equipKey) {
      request({
        method: "post",
        url: `${window.config.mesUrl}/prodexec/prodexec/packageEquipment/getPackInfoByKey?equipKey=${equipKey}`,
      }).then(({ success, data } = {}) => {
        if (success) setSettingData(data || {});
      });
    } else setSettingData({});
  }, [equipKey]);

  useEffect(() => {
    getSettingData();
  }, [getSettingData]);
  return { settingData, getSettingData };
};

export const useMetaInfo = (equipCode) => {
  const [data, setData] = useState({}); // bagNo outBagNo
  const timmerRef = useRef();
  const getData = useCallback(() => {
    if (timmerRef.current) { 
      clearTimeout(timmerRef.current);
      timmerRef.current = undefined;
    }
    if (equipCode) {
      request({
        method: "post",
        url: `${window.config.mesUrl}/prodexec/prodexec/packageEquipment/getEquipRecord?equipCode=${equipCode}`,
      }).then(({ success, data, message: msg } = {}) => {
        if (success) {
          let { status } = data || {};
          // 没有数据，或者数据为中断状态，尝试定时重复请求
          if (!data || status === "INTERRUPT") {
            if (!data) { 
              data = { status: "no_job" };
              message.error("请先分配任务！");
            }
            let { reloadTime } = window.config.packagingOperaConfig || {};
            if (reloadTime !== undefined) {
              timmerRef.current = setTimeout(getData, reloadTime);
            }
          }
          setData(data);
        } else {
          message.error(msg);
        }
      });
    } else setData({});
  }, [equipCode]);

  useEffect(() => {
    getData();
  }, [getData]);
  return [data, getData];
};

export const useWsInfo = (equipCode, isEdit) => {
  const [data, setData] = useState({});
  useEffect(() => {
    if (equipCode) {
      let url = window.config.edgewsUrl;
      if (isDev) {
        url = "ws://120.202.38.15:8081/rongtong-edge-application-ws/";
      }
      if (!isEdit) {
        console.log("link: ", url);
        let ws = new WebSocket(url);
        ws.onmessage = (evt) => {
          let res = evt.data;
          // if (isDev) {
          //   res = {
          //     czzl: 1.11,
          //     fczl: 2.22,
          //   }
          // }
          if (typeof res === "string") {
            try {
              res = JSON.parse(res);
            } catch (e) {
              console.log("ws", res);
              res = {};
            }
          }
          console.log("ws res:", res);
          setData(res);
        };
        ws.onopen = () => {
          if (isDev) {
            // 01 02 03
            equipCode = "L5-BZ-02";
          }
          console.log("Connection open ... send:", equipCode);
          ws.send(equipCode);
        };
      }
      return () => {
        if (!isEdit) {
          console.log("ws close:", equipCode);
          ws.close();
        }
      };
    }
  }, [equipCode, isEdit]);
  return [data];
};
