import React, { memo } from 'react';
import { connect } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Dropdown, Button } from '@easyv/antd';
import { selectComponentWithId } from 'models/create-app';
import styles from './Notification.less';
import { InformationLightColored } from '@easyv/react-icons';
import classNames from 'classnames';

function NotificationContainer({ componentsById = {}, dispatch, lock = false }) {
  const history = useHistory();
  const notices = Object.keys(componentsById)
    .map((d) => componentsById[d])
    .filter((d) => d.errorMessage);

  const menu = notices.length ? (
    <ul className={styles.container}>
      {notices.map((d) => (
        <li className={styles.inform} key={d.id}>
          <div className={styles.icon}>
            <ExclamationCircleOutlined />
          </div>
          <div className={styles.detail}>
            <h4 className={styles.message}>数据获取失败</h4>
            <p className={styles.name}>
              {d.name}_{d.id}
              {'  '}
              {d.errorMessage}
            </p>
            <Button type="primary" onClick={() => dispatch(selectComponentWithId(d.id, history))}>
              查看组件
            </Button>
          </div>
        </li>
      ))}
    </ul>
  ) : (
    <div className={`${styles.container} ${styles.nodata}`}>未检测到任何异常</div>
  );

  return (
    <Dropdown overlay={menu} trigger={['click']} placement="bottomCenter">
      <span
        className={classNames(styles.item, {
          [styles.lock]: lock,
        })}>
        <InformationLightColored className={styles.icon} />
        <span className={styles.text}>通知</span>
        {notices.length ? <i className={styles.circle} /> : null}
      </span>
    </Dropdown>
  );
}

const mapStateToProps = ({ componentsById }) => {
  return { componentsById };
};

export default connect(mapStateToProps)(memo(NotificationContainer));
