import React, { useState, useCallback, useEffect, useRef } from 'react';

import FPlatformEnum from '../utils/enum';

import { useParams } from 'react-router-dom';
import CourseInformation from '../components/courses/CourseInformation';
import * as coursesAPI from '../apis/coursesAPI';
import * as configAPI from '../apis/configAPI';
import InteractiveArea from '../components/public/InteractiveArea';
import NomalTabs from '../components/public/NomalTabs';
import LiveNodePlayer from '../components/public/LiveNodePlayer';
import PlyrPlayer from '../components/public/PlyrPlayer';
import PdfPlayer from '../components/public/PdfPlayer';
import { Modal, Input, message } from 'antd';
import { useTranslation } from 'react-i18next';

const GuestCoursePlayerPage = () => {
  /// 游客先用默认 token 等 denny 改为接口不验证 token
  // JSON.stringify('637f02a065ad47fbbe01b956919419c2'),
  localStorage.setItem('token', '');
  sessionStorage.setItem('token', '');
  const { courseCode, language } = useParams();
  const [courseData, setcourseData] = useState(null);
  const [courseFileUrl, setCourseFileUrl] = useState('');
  const [isShowPdf, setShowPdf] = useState(true);
  const [courseItems, setCourseItems] = useState([]);
  const { t, i18n } = useTranslation();
  const [currentTab, setCurrentTab] = useState(t('简介'));
  const [tabsList, setTabsList] = useState([t('简介')]);
  // const [tabsList, setTabsList] = useState([t('简介'), t('资料')]); /// 暂时屏蔽资料
  const [userName, setUserName] = useState('');
  const [heartBeatInterval, setHeartBeatInterval] = useState(30); // 心跳间隔，单位秒
  const [messageApi, contextHolder] = message.useMessage();
  const [isGuestNameModalOpen, setIsGuestNameModalOpen] = useState(
    !localStorage.getItem('userName'),
  );

  const myVideoPlayerRef = useRef(null);
  const golbalTimer = useRef(null);

  const [plyrProps, setPlyrProps] = useState({
    source: {
      type: 'video',
      title: 'Example Video',
      sources: [
        {
          src: courseFileUrl,
          type: 'video/mp4',
          size: 720,
        },
      ],
    }, // https://github.com/sampotts/plyr#the-source-setter
    options: {
      playsinline: false,
      i18n: {
        speed: t('播放速度'),
        normal: t('正常'),
      },
    }, // https://github.com/sampotts/plyr#options
  });
  //   const [courseCatalogData, setCourseCatalogData] = useState(null);

  // 常量

  // 数据获取：课程数据
  const getCourseDeatil = useCallback(async () => {
    const data = await coursesAPI.fetchCourseDetail(courseCode, 'course');
    setcourseData(data);
    console.log('%c Line:58 🎂 data', 'color:#ed9ec7', data);
    if (data.CourseType === 1) {
      setCourseFileUrl(data.CourseChannel.HttpPullUrl);
    } else {
      setCourseFileUrl(data.DefaultVideoToken);
    }
    setCourseItems(data.CourseMaterials ?? []);
  }, [courseCode]);

  // 初始化时记录播放次数
  const addCoursePlayCountOnInit = useCallback(async () => {
    await coursesAPI.addCoursePlayCountAsync(courseCode);
  }, [courseCode]);

  /// 发送一次心跳
  const sendHeartBeat = useCallback(async () => {
    const userCode = localStorage.getItem('userCode');
    // const userName = localStorage.getItem('userName');
    const data = await coursesAPI.visitorHeartRateAsync(courseCode, userCode);
  }, [courseCode]);

  /// 获取服务器配置然后写入心跳间隔
  useEffect(() => {
    const fetchConfig = async () => {
      let heartBeatSeconds = 30;
      try {
        await configAPI.getServerSettingAsync().then((response) => {
          setHeartBeatInterval(
            response.result.ServerConfigList.CourseVisitorHeartRateSeconds,
          );
          heartBeatSeconds =
            response.result.ServerConfigList.CourseVisitorHeartRateSeconds;
        });
        return heartBeatSeconds;
      } catch (error) {
        console.log('%c Line:106 🧀 error', 'color:#fca650', error);
        return heartBeatSeconds;
      }
    };
    /// 先获取配置，然后再发送心跳
    fetchConfig().then(async (heartBeatSeconds) => {
      let cacheUserName = localStorage.getItem('userName');
      let cacheUserCode = localStorage.getItem('userCode');
      /// 如果已经填写过姓名，就开始发送心跳
      if (cacheUserName) {
        let response = await coursesAPI.saveCourseBrowsedRecordAsync(
          courseCode,
          cacheUserName,
          cacheUserCode,
        );
        if (response.result.ErrorCode == 7085) {
          //如果缓存用户名已被占用则弹出姓名输入框，重新输入一个名字
          // messageApi.open({
          //   type: 'error',
          //   content: t('该用户名已被使用，换一个试试吧'),
          // });
          setIsGuestNameModalOpen(true);
          return;
        }
        let newUserCode = response.result.UserCode;
        localStorage.setItem('userCode', newUserCode);
        sessionStorage.setItem('userCode', newUserCode);
        sessionStorage.setItem('userName', cacheUserName);
        heartBeatSeconds = checkInterval(heartBeatSeconds, 30);
        sendHeartBeat();
        console.log(' 🥛 开始发心跳 heartBeatSeconds', heartBeatSeconds);
        clearTimeout(golbalTimer.current);
        golbalTimer.current = setInterval(() => {
          sendHeartBeat();
        }, heartBeatSeconds * 1000);
      } else {
        /// 如果未填写就弹出输入框
        setIsGuestNameModalOpen(true);
      }
    });
    return () => clearTimeout(golbalTimer.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /// 校验心跳间隔，如果不符合则返回默认值，如果是 string 则尝试转换为 number，如果是 number 则判断大小
  const checkInterval = (i, min) => {
    if (typeof i === 'string') {
      i = parseInt(i);
    }
    if (typeof i !== 'number') {
      i = min;
    }
    if (i < min) {
      i = min;
    }
    return i;
  };

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

  useEffect(() => {
    addCoursePlayCountOnInit();
    getCourseDeatil();
    if (isMobileDevice()) {
      setTabsList([t('简介'), t('互动区')]);
    }
  }, [getCourseDeatil, courseCode]);

  useEffect(() => {
    setShowPdf(courseFileUrl.endsWith('.pdf'));
    setPlyrProps({
      source: {
        type: 'video',
        title: 'Example Video',
        sources: [
          {
            src: courseFileUrl,
            type: 'video/mp4',
            size: 720,
          },
        ],
      },
      options: {
        autoplay: true,
      },
    });
  }, [courseFileUrl]);

  // 交互事件
  // 切换 Tab
  const handleTabChange = (index) => {
    setCurrentTab(tabsList[index]);
  };
  const handleChildData = (data) => {
    setCourseFileUrl(data);
  };

  // 【课程列表】与【简介】Tab
  const buildTopTabs = () => {
    return (
      <NomalTabs
        className='w-100'
        tabs={tabsList}
        initTab={currentTab}
        onChangeTab={handleTabChange}></NomalTabs>
    );
  };

  const isMobileDevice = () => {
    return (
      typeof window.orientation !== 'undefined' ||
      navigator.userAgent.indexOf('IEMobile') !== -1
    );
  };

  const inputChange = (e) => {
    console.log('%c Line:146 🍐 e.target', 'color:#fca650', e.target);
    setUserName(e.target.value.trim());
  };
  // 游客进入课程
  const enterCourse = async () => {
    console.log('%c Line:152 🌰 userName', 'color:#e41a6a', userName);

    if (userName !== '') {
      let response = await coursesAPI.saveCourseBrowsedRecordAsync(
        courseCode,
        userName,
      );
      if (response.result.ErrorCode == 7085) {
        messageApi.open({
          type: 'error',
          content: t('该用户名已被使用，换一个试试吧'),
        });
        return;
      }

      if (response.error && response.error.code === 7088) {
        messageApi.open({
          type: 'error',
          content: t('用户名不能为空'),
        });
        return;
      }
      console.log('%c Line:143 🍯 response', 'color:#93c0a4', response);
      let newUserCode = response.result.UserCode;
      localStorage.setItem('userCode', newUserCode);
      localStorage.setItem('userName', userName);
      sessionStorage.setItem('userCode', newUserCode);
      sessionStorage.setItem('userName', userName);
      setIsGuestNameModalOpen(false);
      let heartBeatSeconds = checkInterval(heartBeatInterval, 30);
      sendHeartBeat();
      console.log(' 🥛 开始发心跳 heartBeatSeconds', heartBeatSeconds);
      clearTimeout(golbalTimer.current);
      golbalTimer.current = setInterval(() => {
        sendHeartBeat();
      }, heartBeatSeconds * 1000);
    } else {
      messageApi.open({
        type: 'error',
        content: t('请输入用户姓名'),
      });
    }
  };

  // 内容主题区域，显示【课程列表】或【简介】
  const buildContentArea = () => {
    if (currentTab === t('简介')) {
      return (
        <div className='flex-grow flex flex-col  bg-gray-50 rounded p-5'>
          {/* <div className='text-xl mb-2'>{t('课程简介')} </div> */}
          <div className='text-sm text-gray-600 whitespace-pre-wrap'>
            {courseData == null || courseData.CourseIntro == null
              ? t('暂无简介')
              : courseData.CourseIntro}
          </div>
        </div>
      );
    } else if (currentTab === t('互动区')) {
      return (
        <div className='h-[60vh]'>
          <InteractiveArea h5courseCode={courseCode} isGuest={true} />
        </div>
      );
    }
    return (
      <div className='flex flex-col  bg-gray-50 rounded'>
        <CourseInformation
          courseItems={courseItems}
          onChildData={handleChildData}
        />
      </div>
    );
  };

  return (
    <main className='flex min-h-screen flex-col p-5 h-full'>
      {contextHolder}
      <div className='flex-grow flex h-full '>
        {/* 视频播放器与PDF显示器 */}
        <div className={`h-full ${isMobileDevice() ? 'w-full' : 'w-3/4'}`}>
          {(courseData === null || courseData.CourseType !== 1) && (
            <div>
              {isShowPdf && (
                <div className={`h-[70vh]`}>
                  <PdfPlayer courseFileUrl={courseFileUrl} isShellWeb={false} />
                </div>
              )}
              {!isShowPdf && (
                <div className='border plyr-wrapper'>
                  <PlyrPlayer plyrProps={plyrProps} />
                </div>
              )}
            </div>
          )}

          {courseData != null && courseData.CourseType === 1 && (
            <div className='relative'>
              <LiveNodePlayer
                url={courseFileUrl}
                ref={myVideoPlayerRef}
                courseCode={courseData.Code}
                isAssistant={courseData.IsAssistant}
                isShellWeb={false}
                isMobile={isMobileDevice()}
                isIOS={false}
              />
            </div>
          )}
          {/* 课程简介 */}
          <div
            className={`mt-2 flex flex-col flex-grow ${
              isMobileDevice() ? 'w-[90vw]' : ''
            }`}>
            {buildTopTabs()}
            {buildContentArea()}
          </div>
        </div>

        {/* 互动交流区 暂时屏蔽*/}

        {!isMobileDevice() &&
        courseData != null &&
        courseData.CourseType === 1 ? (
          <div className='w-1/4 ml-5 border rounded h-[80vh]'>
            <InteractiveArea h5courseCode={courseCode} isGuest={true} />
          </div>
        ) : (
          !isMobileDevice() && (
            <div className='w-1/4 ml-5 flex flex-col'>
              <div className='border rounded bg-gray-50 h-full text-xl flex flex-grow items-center justify-center'>
                <div className='text-lg text-gray-400'>
                  {t('互动区暂未开放')}
                </div>
              </div>
            </div>
          )
        )}
      </div>
      <Modal
        title={t('请输入姓名')}
        open={isGuestNameModalOpen}
        centered
        maskClosable={false}
        mask={true}
        closable={false}
        destroyOnClose={true}
        footer={null}
        styles={{ width: '100%' }}>
        <div className='w-full max-w-md p-6 bg-white rounded-lg '>
          <form>
            <div className='mb-8 '>
              <Input placeholder={t('请输入姓名')} onChange={inputChange} />
            </div>
            <div className='flex justify-center items-center w-full'>
              <button
                className='bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline'
                type='button'
                onClick={enterCourse}>
                {t('进入课程')}
              </button>
            </div>
          </form>
        </div>
      </Modal>
    </main>
  );
};

export default GuestCoursePlayerPage;
