import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import './index.scss';
import MessageChatListView from '~/pages/messageManage/messageChat/comp/messageChatList';
import { SystemManageAPI } from '~/api';
import { isNull } from 'lodash';
import { InterDataType } from '~/api/interface';
import {
  listUserAndRoleByCompanyIdType,
  selectUserListType,
} from '~/api/interface/systemManageType';
import MessageChatContentView from 'src/pages/messageManage/messageChat/comp/messageChatContent';
import QrcodeView from '~/components/qrcodeView';
import MessageChatSystemView from '~/pages/messageManage/messageChat/comp/messageChatSystem';
import MessageChatRole from '~/pages/messageManage/messageChat/comp/MessageChatRole';

// 消息类型
type MessageType = InterDataType<selectUserListType>;
// 角色列表
type RoleType = InterDataType<listUserAndRoleByCompanyIdType>;

// 定时任务
let intervalTimer: NodeJS.Timer;

const MessageChatPage: React.FC = () => {
  // 登录的用户信息
  const { userInfo } = useSelector((state: any) => state.UserInfo);
  // 用户id
  const [userAccountId, setUserAccountId] = useState<number>();
  // 角色列表
  const [roleList, setRoleList] = useState<RoleType>([]);
  // 获取用户id
  const getUserAccountId = async () => {
    const res = await SystemManageAPI.listUserAndRoleByCompanyId({
      companyInfoId: userInfo?.companyInfoVO?.id,
    });
    if (res && res.code === '200') {
      if (res.result?.[0]?.userAccountId) {
        setRoleList(res.result || []);
        setUserAccountId(res.result?.[0]?.userAccountId);
      } else {
        // message.error('获取用户id失败');
        setIsSystem(true);
      }
      // console.log('获取用户id --->', res);
      // setUserAccountId(3);
    }
  };
  // 当前是否是系统消息
  const [isSystem, setIsSystem] = useState<boolean>(false);
  // 当前选择的消息
  const [currentIndex, setCurrentIndex] = useState<number>(0);
  // 用户消息列表
  const [messageList, setMessageList] = useState<MessageType>([]);
  // 获取用户消息列表
  const getMessageList = async () => {
    const res = await SystemManageAPI.selectUserList({
      userAccountId: userAccountId,
      // userAccountId: 3,
    });
    if (res && res.code === '200') {
      setMessageList(res.result || []);
      if (!res.result?.length) setIsSystem(true);
    }
  };
  // 二维码路由参数
  const qrcodePathQueryList = [
    {
      id: 1,
      path: 'page-product/product-store/index',
      scene: `?id=${messageList[currentIndex]?.companyInfoVO?.backUserId}`,
    },
    {
      id: 3,
      path: 'page-rent/rent-store/index',
      scene: `?id=${messageList[currentIndex]?.companyInfoVO?.backUserId}`,
    },
    {
      id: 4,
      path: 'page-flyer/institution-detail/index',
      scene: `?id=${messageList[currentIndex]?.companyInfoVO?.backUserId}`,
    },
    {
      id: 5,
      path: 'page-service/service-store/index',
      scene: `?id=${messageList[currentIndex]?.companyInfoVO?.id}`,
    },
  ];
  // 获取二维码路由参数
  const getQrcodePathQuery = () => {
    const tagId = userInfo?.companyInfoVO?.cooperationTagId;
    if (!tagId) return;
    return qrcodePathQueryList?.find((i) => i?.id === tagId);
  };
  // 组件挂载
  useEffect(() => {
    // console.log('组件挂载 --->', userInfo);
    if (!userInfo?.appUserAccountId) {
      getUserAccountId().then();
    } else {
      setUserAccountId(userInfo?.appUserAccountId);
    }
  }, []);
  // 用户id副作用
  useEffect(() => {
    if (isNull(userAccountId)) return;
    getMessageList().then();
    intervalTimer = setInterval(() => {
      getMessageList().then();
    }, 10000);
    return () => {
      clearInterval(intervalTimer as any);
    };
  }, [userAccountId]);
  return (
    <div className='message-chat flex-start'>
      {!!userAccountId && (
        <MessageChatRole
          roleList={roleList}
          userAccountId={userAccountId}
          onSelect={(data) => setUserAccountId(data?.userAccountId)}
        />
      )}
      <MessageChatListView
        messageList={messageList}
        current={currentIndex}
        isSystem={isSystem}
        onSelect={(index) => {
          setCurrentIndex(index);
          setIsSystem(false);
        }}
        onSystem={() => setIsSystem(true)}
      />
      <div className='message-chat-content'>
        {messageList?.[currentIndex] && !!userAccountId && !isSystem ? (
          <MessageChatContentView
            currentData={messageList[currentIndex]}
            userAccountId={userAccountId}
          />
        ) : null}
        {isSystem && <MessageChatSystemView />}
      </div>
      {!!getQrcodePathQuery()?.id && (
        <div className='message-chat-qrcode'>
          <div className='qrcode-view'>
            <QrcodeView path={getQrcodePathQuery()?.path} scene={getQrcodePathQuery()?.scene} />
          </div>
          <div className='qrcode-text'>扫码进入小程序店铺</div>
        </div>
      )}
    </div>
  );
};

export default MessageChatPage;
