import React, { useEffect, useState } from 'react';
import { useLocalStorage } from 'components/easyUse';
import rocketImg from 'images/modal_title_rocket.png';
import styles from './index.less';
import { getContentByVersion, Feature } from 'services/notice';

const version = VERSION.split('.').slice(0, 2).join('.');

export default function VersionNotice() {
  const [state, setState] = useLocalStorage('noticeVersion');
  const [visible, setVisible] = useState(false);
  const [notice, setNotice] = useState<Feature[]>([]);
  const [detailUrl, setDetailUrl] = useState<string>();

  useEffect(() => {
    if ((!state || state !== version) && !window.appConfig.LOCAL) {
      const initFeatures = async () => {
        let _features;
        try {
          _features = await getContentByVersion(version);
        } catch (err) {
          console.log(err);
        }
        if (_features && Array.isArray(_features?.list) && _features.list.length) {
          setNotice(_features.list);
          setDetailUrl(_features.detailUrl);
          setVisible(true);
        }
      };
      initFeatures();
    }
  }, [state, version]);

  const handleClose = () => {
    setVisible(false);
    setState(version);
  };
  const tip = notice.find((d) => d?.type === 'tip');
  return visible ? (
    <div className={styles.mask} onClick={handleClose}>
      <div className={styles.container} onClick={(e) => e.stopPropagation()}>
        <div className={styles.header}>
          <h2 className={styles.title}>最近更新提示</h2>
          {/* {version && <span className={styles.version}>v{version}</span>} */}
          <i className={`icon iconfont icon-btn_close ${styles.close}`} onClick={handleClose} />
          <img src={rocketImg} className={styles.img} />
        </div>
        <div className={styles.content}>
          {tip ? (
            <div className={styles.feature}>
              <p style={{ paddingLeft: 0 }} className={styles.detail}>
                {tip.desc}
              </p>
            </div>
          ) : null}
          {notice
            .filter((d) => d.title)
            .map((d, i) => (
              <div key={i} className={styles.feature}>
                <h3 className={styles.name}>
                  {i + 1}、{d.title}
                </h3>
                <p className={styles.detail} dangerouslySetInnerHTML={{ __html: d.desc }}></p>
              </div>
            ))}
        </div>
        {detailUrl && (
          <div className={styles.footer}>
            <a className={styles.btn} href={detailUrl} target="_blank">
              查看详情
            </a>
          </div>
        )}
      </div>
    </div>
  ) : null;
}
