import React, { useState, useEffect } from 'react';
import { getLocale, setLocale } from 'umi';

import './Language.less'

const Language: React.FC = (props) => {
  const [currentLocale, setCurrentLocale] = useState(getLocale());
  const [languageList, setLanguageList] = useState([
    {
      label: '中',
      value: 'zh-CN',
    },
    {
      label: 'EN',
      value: 'en-US',
    },
  ]);

  // 处理语言切换
  const handleChangeLanguage = (value: string) => {
    setLocale(value, false);
    setCurrentLocale(value);
  };

  // 组件挂载时确保当前语言状态正确
  useEffect(() => {
    const locale = getLocale();
    setCurrentLocale(locale);
  }, []);

  return (
    <div className="language">
      {languageList.map((item) => (
        <span
          onClick={() => handleChangeLanguage(item.value)}
          className={item.value === currentLocale ? 'active' : ''}
          key={item.value}
        >
          {item.label}
        </span>
      ))}
    </div>
  );
};

export default Language;
