import { useEffect, useState, useRef } from 'react';
import * as coursesAPI from '../../apis/coursesAPI';
import moment from 'moment';
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { message } from 'antd';
import placeholderAvatarImageUrl from '../../assets/placeholder_avatar.png';
import PropTypes from 'prop-types';

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

  const chatRef = useRef(null);

  useEffect(() => {
    getUserInfo();

    // 初始时执行一次
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    i18n.changeLanguage(language);
  }, [i18n, language]);

  useEffect(() => {
    /// 刷新消息
    const fetchData = async () => {
      let result;
      if (isGuest) {
        result = await coursesAPI.getChatMessagePagesVisitorAsync(
          sessionStorage.getItem('courseCode'),
        );
      } else {
        result = await coursesAPI.getChatMessagePagesAsync(
          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 intervalId = setInterval(fetchData, 5000);
    return () => clearInterval(intervalId);
  }, [messagesList, inputValue, isGuest, isTourist]);

  const getUserInfo = async () => {
    if (isGuest) {
      setIsTourist(true);
      sessionStorage.setItem('courseCode', h5courseCode);
    } else {
      if (h5courseCode) {
        sessionStorage.setItem('courseCode', h5courseCode);
      } else {
        sessionStorage.setItem('courseCode', courseCode);
        if (token) {
          console.log('%c Line:22 🥤 token', 'color:#42b983', token);
          sessionStorage.setItem('token', JSON.stringify(token));
        } else {
          console.log('%c Line:47 🍩 token', 'color:#e41a6a', '没有传token');
        }
      }
      const userInfo = await coursesAPI.getUserInfo();
      sessionStorage.setItem('userCode', userInfo?.UserCode);
      sessionStorage.setItem('userName', userInfo?.DisplayName);
      sessionStorage.setItem('userAvatar', userInfo?.HeadImageUrl);
    }
    initData();
  };

  /// 初始化消息
  const initData = async () => {
    let result;
    if (isGuest) {
      result = await coursesAPI.getChatMessagePagesVisitorAsync(
        sessionStorage.getItem('courseCode'),
      );
    } else {
      result = await coursesAPI.getChatMessagePagesAsync(
        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) {
        initList.sort((a, b) => b.createTime - a.createTime);
        setMessagesList(initList);
      }
    }
  };

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

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

  /// 整个页面滚动至底部
  const windowScrollToBottom = () => {
    // 1s 后
    setTimeout(() => {
      window.scrollTo(0, document.body.scrollHeight);
    }, 300);
  };

  /// Local 发送消息
  const sendMessage = async () => {
    if (inputValue.trim()) {
      let lista = messagesList;
      let result;
      let message = {
        code: 'new message ' + utc2Local(new Date()), // 给组件设置临时唯一的 key
        isMyMessage: true,
        content: inputValue,
        // createTime: utc2Local(new Date('1999-01-01')),   //暂时不设置时间
        userCode: sessionStorage.getItem('userCode'),
        avage: sessionStorage.getItem('userAvatar'),
        name: sessionStorage.getItem('userName'),
      };
      lista.push(message);
      if (isTourist) {
        result = await coursesAPI.sendVisitChatMessageAsync(
          inputValue,
          sessionStorage.getItem('courseCode'),
          sessionStorage.getItem('userCode'),
          sessionStorage.getItem('userName'),
        );
      } else {
        result = await coursesAPI.sendChatMessageAsync(
          inputValue,
          sessionStorage.getItem('courseCode'),
        );
      }
      message.createTime = utc2Local(result.result.CreateTime); //取server返回的createTime
    } else {
      message.error(t('发送框不能为空'));
    }
    setInputValue('');
    /// 1s 后
    setTimeout(() => {
      scrollToBottom();
    }, 100);
  };

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

  /// 回车发送消息
  function onKeyDown(event) {
    if (event.keyCode === 13) {
      // 发送消息
      sendMessage();
    }
  }

  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-3'
              key={item.code}>
              <div className='flex flex-col text-right flex-grow pl-14'>
                <div className='font-bold pb-1'>
                  {item.name || item.userCode.substring(0, 6)}
                </div>
                <div className='bg-blue-500 rounded-lg px-2 py-1 text-white self-end text-left line-break-anywhere'>
                  {item.content}
                </div>
                <div className='text-gray-600 text-xs mt-1'>
                  {item.createTime}
                </div>
              </div>
              {/* <img
                src={item.avage || placeholderAvatarImageUrl}
                alt='Your avatar'
                className='rounded-full w-12 h-12 ml-3'
              /> */}
            </div>
          ) : (
            <div className='flex flex-grow items-start mb-3' key={item.code}>
              {/* <img
                src={item.avage || placeholderAvatarImageUrl}
                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-1'>{item.name}</div>
                <div className='bg-gray-300 rounded-lg px-2 py-1 self-start line-break-anywhere'>
                  {item.content}
                </div>
                <div className='text-gray-600 text-xs 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={t('发送信息')}
            className='flex-grow bg-white rounded-l px-4 py-2 focus:outline-none'
            onChange={onInputChange}
            onFocus={windowScrollToBottom}
            onKeyDown={onKeyDown}
            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}>
            {t('发送')}
          </button>
        </div>
      </div>
    </div>
  );
};

/// 类型校验
InteractiveArea.propTypes = {
  h5courseCode: PropTypes.string,
  isGuest: PropTypes.bool,
};

export default InteractiveArea;
