import React, { useEffect, useState, useRef } from 'react';
import { useSessionStorage } from 'react-use';
import * as coursesAPI from '../../apis/coursesAPI';
import moment from 'moment';
import { useParams } from 'react-router-dom';

import { message } from 'antd';

const InteractiveArea = ({ h5courseCode }) => {
  const [messagesList, setMessagesList] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [isTourist, setIsTourist] = useState(false);
  const { courseCode, token } = useParams();

  const chatRef = useRef(null);
  const guid = generateGUID();
  if (h5courseCode) {
    sessionStorage.setItem('courseCode', h5courseCode);
  } else {
    sessionStorage.setItem('courseCode', courseCode);
    if (token) {
      sessionStorage.setItem('token', JSON.stringify(token));
    }
  }

  useEffect(() => {
    getUserInfo();
  }, []);

  useEffect(() => {
    const intervalId = setInterval(fetchData, 5000);
    return () => clearInterval(intervalId);
  }, [messagesList, inputValue]);

  function generateGUID() {
    const s4 = () =>
      (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
  }

  const getUserInfo = async () => {
    if (sessionStorage.getItem('token') !== 'null') {
      const userInfo = await coursesAPI.getUserInfo();
      sessionStorage.setItem('userCode', userInfo?.UserCode);
      sessionStorage.setItem('userName', userInfo?.DisplayName);
      sessionStorage.setItem('userAvatar', userInfo?.HeadImageUrl);
    } else {
      sessionStorage.setItem('userCode', guid);
      sessionStorage.setItem('userName', guid.substring(0, 6));
      setIsTourist(true);
    }
    initData();
  };

  /// 初始化消息
  const fetchData = async () => {
    let result;
    if (sessionStorage.getItem('token') !== 'null') {
      result = await coursesAPI.getChatMessagePagesAsync(
        sessionStorage.getItem('courseCode'),
      );
    } else {
      result = await coursesAPI.getChatMessagePagesVisitorAsync(
        sessionStorage.getItem('courseCode'),
      );
    }

    if (result && result.result && result.result.PageData) {
      const newList = result.result.PageData.reduce(
        (list, item) => {
          let exists;
          if (isTourist) {
            exists = messagesList.find(
              (i) =>
                i.code === item.Code ||
                item.Visitor === sessionStorage.getItem('userCode'),
            );
          } else {
            exists = messagesList.find(
              (i) =>
                i.code === item.Code ||
                item.UserCode === sessionStorage.getItem('userCode'),
            );
          }
          if (!exists) {
            list.push({
              isMyMessage: false,
              code: item.Code,
              content: item.Content,
              createTime: utc2Local(item.CreateTime),
              userCode: item.UserCode,
              avage: item.HeadImg,
              name: item.DisplayName,
            });
          }
          return list;
        },
        [...messagesList],
      );
      setMessagesList(newList);
    }
  };

  /// 初始化消息
  const initData = async () => {
    let result;
    if (sessionStorage.getItem('token') !== 'null') {
      result = await coursesAPI.getChatMessagePagesAsync(
        sessionStorage.getItem('courseCode'),
      );
    } else {
      result = await coursesAPI.getChatMessagePagesVisitorAsync(
        sessionStorage.getItem('courseCode'),
      );
    }

    let initList = [];
    if (result && result.result && result.result.PageData) {
      for (let i of result.result.PageData) {
        if (i.UserCode === sessionStorage.getItem('userCode')) {
          initList.unshift({
            isMyMessage: true,
            code: i.Code,
            content: i.Content,
            createTime: utc2Local(i.CreateTime),
            userCode: i.UserCode,
            avage: i.HeadImg,
            name: i.DisplayName,
          });
        } else {
          initList.unshift({
            isMyMessage: false,
            code: i.Code,
            content: i.Content,
            createTime: utc2Local(i.CreateTime),
            userCode: i.UserCode,
            avage: i.HeadImg,
            name: i.DisplayName || i.Visitor.substring(0, 6),
          });
        }
      }
      if (initList.length !== 0) {
        setMessagesList(initList);
      }
    }
  };

  /// 时间转换
  const utc2Local = (startTime) => {
    const dateObj = moment(startTime).local();
    const formattedTime = dateObj.format('YYYY-MM-DD HH:mm:ss');
    return formattedTime;
  };

  /// 输入栏变化
  const onInputChange = (event) => {
    setInputValue(event.target.value);
  };

  /// Local 发送消息
  const sendMessage = async () => {
    if (inputValue.trim()) {
      let lista = messagesList;
      lista.push({
        isMyMessage: true,
        content: inputValue,
        createTime: utc2Local(new Date()),
        userCode: sessionStorage.getItem('userCode'),
        avage: sessionStorage.getItem('userAvatar'),
        name: sessionStorage.getItem('userName'),
      });
      if (isTourist) {
        coursesAPI.sendVisitChatMessageAsync(
          inputValue,
          sessionStorage.getItem('courseCode'),
          sessionStorage.getItem('userCode'),
        );
      } else {
        coursesAPI.sendChatMessageAsync(
          inputValue,
          sessionStorage.getItem('courseCode'),
        );
      }
    } else {
      message.error('发送框不能为空');
    }
    setInputValue('');
    /// 1s 后
    setTimeout(() => {
      scrollToBottom();
    }, 100);
  };

  /// 滚动至底部
  const scrollToBottom = () => {
    if (chatRef.current) {
      chatRef.current.scrollTop = chatRef.current.scrollHeight;
    }
  };

  return (
    <div className='w-full h-full bg-gray-200 p-4 pr-0 flex flex-col'>
      {/* 聊天记录 */}
      <div
        className='flex-grow overflow-y-auto scroll-smooth pr-4'
        id='chat-box'
        ref={chatRef}>
        {/* 接收到的消息 */}
        {messagesList.map((item) =>
          item.isMyMessage ? (
            <div className='flex flex-row flex-grow items-start justify-end mb-4'>
              <div className='flex flex-col text-right flex-grow pl-14'>
                <div className='font-bold pb-2'>
                  {item.name || item.userCode.substring(0, 6)}
                </div>
                <div className='bg-blue-500 rounded-lg px-4 py-2 text-white self-end text-left line-break-anywhere'>
                  {item.content}
                </div>
                <div className='text-gray-600 text-sm mt-1'>
                  {item.createTime}
                </div>
              </div>
              <img
                src={
                  item.avage ||
                  process.env.PUBLIC_URL + '/placeholder_avatar.png'
                }
                alt='Your avatar'
                className='rounded-full w-12 h-12 ml-3'
              />
            </div>
          ) : (
            <div className='flex flex-grow items-start mb-4'>
              <img
                src={
                  item.avage ||
                  process.env.PUBLIC_URL + '/placeholder_avatar.png'
                }
                alt='User avatar'
                className='rounded-full w-12 h-12 mr-3'
              />
              <div className='flex flex-col text-left flex-grow pr-14'>
                <div className='font-bold pb-2'>{item.name}</div>
                <div className='bg-gray-300 rounded-lg px-4 py-2 self-start line-break-anywhere'>
                  {item.content}
                </div>
                <div className='text-gray-600 text-sm mt-1'>
                  {item.createTime}
                </div>
              </div>
            </div>
          ),
        )}
      </div>

      {/* 输入框及发送按钮 */}
      <div className='pt-2 pr-4'>
        <div className='relative flex items-center shadow'>
          <input
            type='text'
            placeholder='发送信息'
            className='flex-grow bg-white rounded-l px-4 py-2 focus:outline-none'
            onChange={onInputChange}
            style={{ width: '100px' }}
            value={inputValue}
          />
          <button
            className='bg-blue-500 text-white font-bold py-2 px-5 rounded-r focus:outline-none'
            onClick={sendMessage}>
            发送
          </button>
        </div>
      </div>
    </div>
  );
};

export default InteractiveArea;
