import difftime from "@/utils/difftime";
import { doFetch } from "@/utils/doFetch";
import { Avatar, Box, Stack } from "@mui/material";
import { useModel } from "@umijs/max";
import { useRequest } from "ahooks";
import { Input } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { Scrollbars } from "react-custom-scrollbars";
import "./index.less";

function OnlineChat({ trainId }) {
  const {
    initialState: { menuNum },
    setInitialState,
  } = useModel("@@initialState");
  const currentUserId = localStorage.getItem("ID");

  const [value, setvalue] = useState();
  const scrollRef = useRef();
  useEffect(() => {}, []);

  const handleKeyDown = (e) => {
    if (e.key === "Enter") {
      if (e.ctrlKey) {
        e.target.value += "\n";
        setvalue((s) => (s += "\n"));
      } else {
        e.preventDefault();
        doFetch({
          url: "/trainMessage/sendMessage",
          params: { trainId, messageContent: value },
        }).then((res) => {
          if (res?.code === "0000") {
            refresh();
            setvalue(null);
          }
        });
      }
    }
  };

  const { data, loading, refresh } = useRequest(
    async () => {
      let res = await doFetch({
        url: "/trainMessage/list",
        params: { trainId },
      });
      return res?.data?.dataList;
    },
    {
      onSuccess: (res, params) => {
        setTimeout(() => {
          scrollRef?.current?.scrollToBottom();
        }, 10);
      },
      refreshDeps: [menuNum],
    }
  );

  return (
    <Box
      display={"flex"}
      flexDirection={"column"}
      boxShadow={"0 0 18px #f0f0f0"}
      borderRadius={2}
      padding={2}
      bgcolor={"white"}
      height={"calc(100vh - 240px)"}
    >
      <Box flex={1}>
        <Scrollbars
          thumbMinSize={10}
          autoHide
          style={{
            width: "100%",
            height: "100%",
          }}
          hideTracksWhenNotNeeded
          ref={scrollRef}
        >
          {data?.map?.((it, i) => {
            if (it?.sendUserId == currentUserId) {
              return (
                <Stack direction={"row"} mb={2} justifyContent={"flex-end"}>
                  <Stack direction={"column"} mr={1} pt={0.4}>
                    <Box textAlign={"right"}>
                      <span style={{ fontSize: 12 }}>
                        {" "}
                        {difftime(dayjs(), dayjs(it?.createTime))}
                      </span>
                    </Box>
                    <Box
                      mt={0.8}
                      p={2}
                      bgcolor={"#c8facd"}
                      borderRadius={2}
                      whiteSpace={"pre-wrap"}
                    >
                      {it?.messageContent}
                    </Box>
                  </Stack>
                  <Avatar
                    src={it?.pic?.[0]?.url}
                    sx={{ border: "2px solid rgba(0,0,0,0.2)" }}
                  ></Avatar>
                </Stack>
              );
            }
            return (
              <Stack direction={"row"} mb={2}>
                <Avatar
                  src={it?.pic?.[0]?.url}
                  sx={{ border: "2px solid rgba(0,0,0,0.2)" }}
                ></Avatar>
                <Stack direction={"column"} ml={1} pt={0.4}>
                  <Box textAlign={"left"}>
                    <b>{it?.sendUserName}</b>

                    <span style={{ fontSize: 12 }}>
                      {" "}
                      {difftime(dayjs(), dayjs(it?.createTime))}
                    </span>
                  </Box>
                  <Box
                    mt={0.8}
                    p={2}
                    bgcolor={"#f4f6f7"}
                    borderRadius={2}
                    whiteSpace={"pre-wrap"}
                  >
                    {it?.messageContent}
                  </Box>
                </Stack>
              </Stack>
            );
          })}
        </Scrollbars>
      </Box>
      <Box height={68} bgcolor={"#e0e0e0"} padding={1} borderRadius={2}>
        <Input.TextArea
          placeholder="请输入（按回车键发送，按ctrl+回车键换行）"
          bordered={false}
          style={{ height: "100%", resize: "none", margin: "0 -8px" }}
          onKeyDown={handleKeyDown}
          value={value}
          onChange={(e) => {
            setvalue(e.target.value);
          }}
        ></Input.TextArea>
      </Box>
    </Box>
  );
}

export default OnlineChat;
