import React, { useState, useEffect, useRef } from 'react';
import moment from 'moment';
import { useRecoilState } from 'recoil';
import { layerCurrentDateTime } from '../../store/page';
import './index.scss';

export default function DateAndTime(props: DateAndTimeProps) {
  const { options = {} } = props;
  const {
    timePosition,
    showAmorPm,
    dateType, // 日期样式
    timeFormat, // 时间制式
    timeFontSize, // 字体大小
    timeFontFamily, // 字体样式
    timeFontColor, // 字体颜色
    dateOpacity // 透明度
  } = options || {};

  const [currentDateTime, setCurrentDateTime] =
    useRecoilState(layerCurrentDateTime); //记录当前日期时间
  const [timeText, setTimeText] = useState(''); // 当前时间文本
  const timeRef = useRef(currentDateTime); // 时间
  const dateTimeRef = useRef(null); // 时间定时器

  const style = {
    fontSize: timeFontSize + 'px',
    color: timeFontColor,
    fontFamily: timeFontFamily,
    opacity: dateOpacity / 100,
    textAlign: timePosition
  };

  const weekendMap = {
    1: '周一',
    2: '周二',
    3: '周三',
    4: '周四',
    5: '周五',
    6: '周六',
    0: '周日'
  };

  useEffect(() => {
    document.addEventListener('visibilitychange', handleVisibilityChange);
    // 清空定时
    return () => {
      dateTimeRef?.current && clearInterval(dateTimeRef?.current);
      dateTimeRef.current = null;
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  useEffect(() => {
    clearInterval(dateTimeRef?.current);
    dateTimeRef.current = null;
    if (currentDateTime) {
      timeRef.current = currentDateTime;
      getTime();
    }
  }, [currentDateTime]);

  // 监听窗口显隐变化
  const handleVisibilityChange = () => {
    // 页面变为不可见时触发
    let pageVisibility = document.visibilityState;
    if (pageVisibility == 'hidden') {
      dateTimeRef?.current && clearInterval(dateTimeRef?.current);
      dateTimeRef.current = null;
    }
  };

  // 格式化时间文本
  const getTimeFormat = (nowTime) => {
    let timeText = '';
    const m = moment(nowTime);
    const year = m.year();
    const month = m.month() + 1;
    const day = m.date();
    const w = m.days();
    const H = m.hours();
    const M = m.minutes();
    const S = m.seconds();
    const newH = timeFormat === '24' ? H : H > 12 ? H - 12 : H;
    const newM = M < 10 ? '0' + M : M;
    const newS = S < 10 ? '0' + S : S;
    const amorPmText =
      timeFormat === '24' || showAmorPm === 'false'
        ? ''
        : H > 12
        ? '下午 '
        : '上午 ';
 
    switch (dateType) {
      case 'YMD-W-HMS-D':
        timeText = `${year}年${month}月${day}日 ${weekendMap[w]} ${amorPmText}${newH}:${newM}:${newS}`;
        break;
      case 'YMD-HMS-D':
        timeText = `${year}年${month}月${day}日 ${amorPmText}${newH}:${newM}:${newS}`;
        break;
      case 'YMD-D':
        timeText = `${year}年${month}月${day}日`;
        break;
      case 'YMD-W-HMS':
        timeText = `${year}-${month}-${day} ${weekendMap[w]} ${amorPmText}${newH}:${newM}:${newS}`;
        break;
      case 'YMD-HMS':
        timeText = `${year}-${month}-${day} ${amorPmText}${newH}:${newM}:${newS}`;
        break;
      case 'YMD':
        timeText = `${year}-${month}-${day}`;
        break;
      case 'HMS':
        timeText = `${amorPmText}${newH}:${newM}:${newS}`;
        break;
      case 'HM':
        timeText = `${amorPmText}${newH}:${newM}`;
        break;
      default:
        break;
    }
    setTimeText(timeText);
  };

  // 获取时间
  const getTime = () => {
    dateTimeRef.current = setInterval(() => {
      const m = timeRef.current ? moment(timeRef.current) : moment();
      const nowTime = m.add(1, 's').format();
      getTimeFormat(nowTime);
      timeRef.current = nowTime;
      // setTime(nowTime);
    }, 1000);
  };

  return (
    <div className="zl-largeScreen-DateAndTime" style={style}>
      {timeText}
    </div>
  );
}
export interface DateAndTimeProps {
  options: Ioptions;
  isPreviewShow?: boolean;
}

export interface Ioptions {
  timePosition?: any;
  showAmorPm?: string;
  dateType?: string; // 日期样式
  timeFormat?: string; // 时间制式
  timeFontSize?: number; // 字体大小
  timeFontFamily?: string; // 字体样式
  timeFontColor?: string; // 字体颜色
  dateOpacity?: number; // 透明度
}
