import { post } from '@/services/ajax';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { Form, Input, Tabs } from 'antd';
import Spin from 'antd/lib/spin';
import { stringify } from 'qs';
import React, { useEffect, useRef, useState } from 'react';
import { IChat, ICustFollow, IStaffsItem } from './ChatLogsType';
import { ChatBar } from './components/ChatBar';
import { ChatTime } from './components/ChatTime';
import styles from './index.module.scss';

const ChatLogs: React.FC = () => {
  const [param] = useState({
    curr_page: 1,
    page_count: 20,
    msg_from: '',
    msg_to_list: '',
  });
  const tabKeyRef = useRef('0');

  const [selectStaff, setSelectStaff] = useState<IStaffsItem>();
  const selectStaffRef = useRef<IStaffsItem>();
  const [staffsList, setStaffsList] = useState<IStaffsItem[]>([]);
  const [custFollowsList, setCustFollowsList] = useState<ICustFollow[]>([]);

  const [selectCustFollow, setCustFollow] = useState<ICustFollow>();
  const selectCustFollowRef = useRef<ICustFollow>();
  const [chatLogs, setChatLogs] = useState<IChat[]>([]);

  const [tabs] = useState([
    {
      key: '0',
      label: '内部联系人',
      children: '',
    },
    {
      key: '1',
      label: '外部联系人',
      children: '',
    },
    {
      key: '2',
      label: '客户群聊',
      children: '',
    },
  ]);

  const [flolowsBoxShow, setFlolowsBox] = useState(false);
  const timeDiffRef = useRef('');
  const timeShowRef = useRef(false);
  const chatBoxRef = useRef<any>();
  const isAllChatRef = useRef(false);
  const chatLogLoadingRef = useRef(false);
  const [chatLogLoading, setChatLogLoading] = useState(false);

  function show() {
    setFlolowsBox(false);
  }

  const callback = function (mutationsList: any) {
    // Use traditional 'for loops' for IE 11
    for (let mutation of mutationsList) {
      if (mutation.type === 'childList') {
        document.querySelector('.curr_page' + param.curr_page)?.scrollIntoView(true);
      } else if (mutation.type === 'attributes') {
        console.log('The ' + mutation.attributeName + ' attribute was modified.');
      }
    }
  };
  const observer = new MutationObserver(callback);

  useEffect(() => {
    document.addEventListener('click', show, false);
    getStaffsList();

    observer.observe(chatBoxRef.current, { childList: true });
    return () => {
      document.removeEventListener('click', show, false);
      observer.disconnect();
    };
  }, []);

  // 获取员工
  const getStaffsList = () => {
    post({ url: '/Staffs/Data' }).then((res) => {
      if (res.err_code == 0) {
        if (Array.isArray(res.data)) {
          // setSelectStaff(res.data[0]);
          //     selectStaffRef.current = res.data[0];
          res.data.forEach((element: IStaffsItem) => {
            if (element.user_id == 'yangxb') {
              setSelectStaff(element);
              selectStaffRef.current = element;
            }
          });
          setStaffsList(res.data);
          getCustFollowsList();
        }
      }
    });
  };

  const page = (curr: number) => {
    param.curr_page = curr;
    param.msg_from = selectStaffRef.current?.user_id + '';
    param.msg_to_list = selectCustFollowRef.current?.cust_id + '';
    timeDiffRef.current = '';
    timeShowRef.current = false;
    getChatLogsList();
  };

  const getChatLogsList = () => {
    chatLogLoadingRef.current = true;
    setChatLogLoading(true);
    post({
      url: '/ChatLogs/List',
      data: stringify(param),
    }).then((res) => {
      const count = res.count || 0;
      chatLogLoadingRef.current = false;
      setChatLogLoading(false);
      isAllChatRef.current = count < param.page_count * param.curr_page;
      if (res.err_code == 0) {
        if (Array.isArray(res.data)) {
          if (param.curr_page == 1) {
            setChatLogs([...res.data.reverse(), { curr_page: param.curr_page }]);
          } else {
            setChatLogs([...res.data.reverse(), { curr_page: param.curr_page }, ...chatLogs]);
          }
        }
      }
    });
  };

  const getCustFollowsList = () => {
    post({
      url: '/CustFollows/List',
      data: stringify({ user_id: selectStaffRef.current?.user_id }),
    }).then((res) => {
      if (res.err_code == 0) {
        if (Array.isArray(res.data)) {
          setCustFollowsList(res.data);
          if (res.data.length) {
            setCustFollow(res.data[0]);
            selectCustFollowRef.current = res.data[0];
            page(1);
          }
        }
      }
    });
  };

  // const { notification } = App.useApp();

  return (
    <PageContainer>
      <div className={styles.box}>
        <div className={styles.personnelBox}>
          <div className={`${styles.flolowsBox} ${flolowsBoxShow ? styles.show : ''}`}>
            {staffsList.map((item) => {
              return (
                <div
                  key={item.user_id}
                  className={styles.chatB}
                  onClick={(e) => {
                    setSelectStaff({ ...item });
                    selectStaffRef.current = { ...item };
                    setFlolowsBox(false);
                    getCustFollowsList();
                  }}
                >
                  <div className={styles.avatar}>{item.name[0]}</div>
                  <div className={styles.chatAMsg}>
                    <div className={styles.chatAName} title={item.name}>
                      {item.name}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
          <div
            className={`${styles.chatA}`}
            onClick={(e) => {
              e.stopPropagation();
              setFlolowsBox(!flolowsBoxShow);
            }}
          >
            {selectStaff ? (
              <>
                <div className={styles.avatar}>{selectStaff.name[0]}</div>
                <div className={styles.chatAMsg}>
                  <div className={styles.chatAName} title={selectStaff.name}>
                    {selectStaff.name}
                  </div>
                </div>
                {flolowsBoxShow ? <UpOutlined /> : <DownOutlined />}
              </>
            ) : null}
          </div>
          <Form autoComplete="off">
            <Input
              style={{ margin: '0 12px', width: 'calc(100% - 24px)' }}
              autoComplete="off"
            ></Input>
          </Form>
          <Tabs items={tabs} size="small" style={{ padding: '0 12px' }} tabBarGutter={12}></Tabs>
          <div className={styles.chatBBox}>
            {custFollowsList.map((item) => {
              return (
                <div
                  key={item.cust_id}
                  className={`${styles.chatB} ${
                    selectCustFollow?.cust_id == item.cust_id ? styles.active : ''
                  }`}
                  onClick={() => {
                    setCustFollow(item);
                    selectCustFollowRef.current = item;
                    page(1);
                  }}
                >
                  <div className={styles.avatar}>
                    <img
                      src={item.cust_info.avatar}
                      alt=""
                      style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'cover' }}
                    />
                  </div>
                  <div className={styles.chatAMsg}>
                    <div className={styles.chatAName} title={item.cust_info.name}>
                      {item.cust_info.name}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ flex: 1 }}>
          <div className={styles.logTop}>
            <div>{selectCustFollowRef.current?.cust_info.name}</div>
          </div>
          <Spin spinning={chatLogLoading} style={{ display: 'block' }}>
            <div
              className={styles.chatLogBox}
              ref={chatBoxRef}
              onScroll={(e) => {
                if (
                  e.target.scrollTop == 0 &&
                  !isAllChatRef.current &&
                  !chatLogLoadingRef.current
                ) {
                  page(param.curr_page + 1);
                }
              }}
            >
              {isAllChatRef.current ? (
                <div style={{ marginBottom: 12, textAlign: 'center', color: '#999' }}>
                  没有更多聊天记录了
                </div>
              ) : null}
              {chatLogs.map((item, i) => {
                if (item.curr_page) {
                  return (
                    <div
                      key={item.curr_page}
                      className={`curr_page${param.curr_page}`}
                      style={{ height: 0 }}
                    ></div>
                  );
                } else {
                  // if (timeDiffRef.current == '') {
                  //   timeDiffRef.current = item.msg_time;
                  //   timeShowRef.current = false;
                  // } else {
                  //   if (
                  //     new Date(item.msg_time).getTime() - new Date(timeDiffRef.current).getTime() >
                  //     5 * 60 * 1000
                  //   ) {
                  //     timeDiffRef.current = item.msg_time;
                  //     timeShowRef.current = true;
                  //   } else {
                  //     timeShowRef.current = false;
                  //   }
                  // }

                  // if (i == 0) {
                  //   timeShowRef.current = true;
                  // }

                  return (
                    <div key={item.msg_id}>
                      <ChatTime msgtime={item.msg_time}></ChatTime>
                      <ChatBar from={selectStaff} to={selectCustFollow} chat={item}></ChatBar>
                    </div>
                  );
                }
              })}
            </div>
          </Spin>
        </div>
      </div>
    </PageContainer>
  );
};

export default ChatLogs;
