import React, { useEffect, useRef, useState } from 'react';
import { Button, Empty, Image, Input, Space } from 'antd';
import { ReactComponent as SvgLogo } from '@/icons/logo.svg';


import './styles/side-menu.less';
import { SearchOutlined } from '@ant-design/icons';
import ProList from '@ant-design/pro-list';
import { history } from '@@/core/history';
import { useLocation } from '@@/exports';
import { getTeachers } from '@/services/side/SideController';
import { getTeacherCourses } from '@/services/record/RecordController';
import CourseImage from '@/assets/img/course_image.png';


interface SideMenuProps {
    onCollaped: (isExpanded: boolean)=> void,
    initWidth: number
}

function SideMenu  ({
    initWidth = 200,
}: SideMenuProps) {
  const location = useLocation();
  const [isLessionPage, setIsLessionPage] = useState<boolean>(false);
  const [activeKey, setActiveKey] = useState<string>('');
  const [activeCourseKey, setActiveCourseKey] = useState<string>('');
  const [courseTitle, setCourseTitle] = useState<string>('');
  const [teacherName, setTeacherName] = useState<string>('');
  const [teacherData, setTeacherData] = useState<API.Teacher[]>([]);
  const [courseData, setCourseData] = useState<[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);

  async function getTeacherCourseList(current: number) {
    const searchParams = new URLSearchParams(location.search);
    setActiveCourseKey(searchParams.get('courseId') as string)
    setLoading(true);
    try {
      const data = await getTeacherCourses({
        teacherId: searchParams.get('teacherId') as string,
        courseTitle: courseTitle,
        current: current,
        size: 10,
      })
      if (data.code === 200) {
        if (data.data.records.length < 10) {
          setHasMore(false);
        } else {
          setHasMore(true);
        }
        if (current === 1) {
          setCourseData(data.data.records);
        } else {
          setCourseData(prev => [...prev, ...data.data.records] as []);
        }
        setPage(current + 1);
      }
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    if(location.pathname) {
      if(location.pathname.includes('play')) {
        setIsLessionPage(true);
        const onData = async () => {
          await getTeacherCourseList(1);
        }
        onData()
      } else {
        setIsLessionPage(false);
      }
    }
  }, [location.pathname]);

  async function getTeacherList() {
    const data: API.SideRes = await getTeachers({
      teacherName: teacherName,
    })
    if (data.code === 200) {
      setTeacherData(data.data)
      if (data.data.length > 0) {
        const searchParams = new URLSearchParams(location.search);
        if (searchParams.get('teacherId')) {
          setActiveKey(searchParams.get('teacherId') as string);
        } else {
          setActiveKey(data.data[0].teacherId as string)
          localStorage.setItem('teacherName', data.data[0].teacherName as string)
          localStorage.setItem('schoolName', data.data[0].schoolName as string)
          history.push('/record?teacherId=' + data.data[0].teacherId);
        }
      }
    }
  }

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;
      // 距离底部50px触发加载
      if (!loading && hasMore && scrollHeight - (scrollTop + clientHeight) < 50) {
        getTeacherCourseList(page);
      }
    };

    container.addEventListener('scroll', handleScroll);
    return () => container?.removeEventListener('scroll', handleScroll);
  }, [loading, hasMore, page]);

  useEffect(() => {
    const onData = async () => {
      await getTeacherList()
    }
    onData()
  }, []);


  return (
    <div style={{ width: initWidth, height: '100vh' }}>
      <div className="side-header">
        <SvgLogo style={{ fill: 'currentColor' }} className="header-logo" />
        <h3 className="header-title-text">评审管理系统</h3>
      </div>
      <div className="side-search">
        {
          isLessionPage ?
            (
              <div>
                <div style={{  display: 'flex', justifyContent: 'space-between', padding: '20px 10px' }}>
                  <div style={{ color: 'black', fontSize: 16, fontWeight: 'bold', }} >
                    {localStorage.getItem('teacherName')}
                  </div>
                  <div style={{ color: 'black', fontSize: 12 }}>
                    {localStorage.getItem('schoolName')}
                  </div>
                </div>
                <Space direction="horizontal" style={{ padding: '0 10px' }}>
                  <Input
                    value={courseTitle}
                    onChange={(e) => setCourseTitle(e.target.value)}
                    placeholder="输入课程主题搜索"
                    allowClear
                  />
                  <Button
                    icon={<SearchOutlined />}
                    type="primary"
                    onClick={async () => { await getTeacherCourseList(1) }}
                  />
                </Space>
              </div>) :
              (
                <div>
                  <div
                    style={{
                      color: 'black',
                      fontSize: 16,
                      fontWeight: 'bold',
                      margin: '20px 0 20px 10px',
                      textAlign: 'left',
                    }}
                  >
                    参评教师
                  </div>
                  <Space direction="horizontal" style={{ padding: '0 10px' }}>
                    <Input
                      value={teacherName}
                      onChange={(e) => setTeacherName(e.target.value)}
                      placeholder="输入教师姓名搜索"
                      allowClear
                    />
                    <Button
                      icon={<SearchOutlined />}
                      type="primary"
                      onClick={getTeacherList}
                    />
                  </Space>
                </div>
              )
        }
      </div>
      <div className="menu-area">
        {
          isLessionPage ? (
            <ProList<any>
              className={'course-list'}
              pagination={false}
              showActions="hover"
              tableExtraRender={(_: any, list: any) => (
                <div
                  ref={containerRef}
                  style={{ height: 'calc(100vh - 170px)', overflow: 'auto', paddingRight: 30 }}
                >
                  {list.map((item: any) => (
                    <div
                      key={item.id}
                      style={{
                        backgroundColor: '#F8FAFC',
                        cursor: 'pointer',
                        marginBottom: '10px'
                      }}
                      onClick={() => {
                        history.push(`/play?teacherId=${item.teacherId}&courseId=${item.id}`);
                        setActiveCourseKey(item.id);
                      }}
                      className={item.id === activeCourseKey ? 'course-active' : ''}
                    >
                      <Image
                        width={'100%'}
                        style={{ aspectRatio: '16/9', borderRadius: '15px 15px 0 0' }}
                        preview={false}
                        src={CourseImage}
                        // src={item.fullScreenOssUrl + '?x-oss-process=video/snapshot,t_0,f_jpg,w_800,h_450'}
                      />
                      <div className="course-info">
                        <div style={{ fontWeight: 'bold', fontSize: '18px' }}>{item.courseTitle}</div>
                        <div className="info-flex">
                          <div>{item.subjectName}</div>
                          <div>所属年级:{item.periodName}</div>
                        </div>
                        <div style={{ fontSize: '11px' }}>授课时间:{item.courseDate}</div>
                      </div>
                    </div>
                  ))}
                  {loading && <div style={{ textAlign: 'center', padding: '10px' }}>加载中...</div>}
                  {!hasMore && <Empty styles={{ image: { height: 0 } }} description="没有更多数据了" image={false} />}
                </div>
              )}
              metas={{
                actions: {},
              }}
              dataSource={courseData}
            />
            ) : (
            <ProList<any>
              className={'list-box'}
              pagination={false}
              showActions="hover"
              onItem={(record) => {
                return {
                  onClick: () => {
                    setActiveKey(record.teacherId);
                    localStorage.setItem('teacherName', record.teacherName)
                    localStorage.setItem('schoolName', record.schoolName)
                    history.push('/record?teacherId=' + record.teacherId);
                  },
                };
              }}
              rowClassName={(record: { teacherId: string }) =>
                record.teacherId === activeKey ? 'active' : ''
              }
              metas={{
                title: {
                  dataIndex: 'teacherName',
                },
                description: {
                  dataIndex: 'schoolName',
                  render: (text) => <div style={{ textAlign: 'left' }}>{text}</div>,
                },
              }}
              dataSource={teacherData}
            />
          )
        }
      </div>
    </div>
  );
}

export default SideMenu;
