import React, { useState, useEffect } from 'react';
import { Badge, notification, Spin } from 'antd';
import { CloseOutlined, DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { useHistory } from 'react-router-dom';
// import copy from 'copy-to-clipboard';
import { connect } from 'umi';
import { apiGetBussinessMsgList } from '@/services/messageReminder';
import Empty from '../Empty';
import styles from './index.less';

import { CHANNEL_ID } from '@/utils/constants';

const Horn = props => {
  const { count, toggle, animationClass, stowClass, onStow } = props;
  return (
    <div
      className={classNames(styles.horn, styles[animationClass], styles[stowClass])}
      onClick={toggle}
    >
      <span className={styles['horn--btn']} onClick={e => onStow(e)}>
        {stowClass ? <DoubleLeftOutlined /> : <DoubleRightOutlined />}
      </span>
      <Badge count={count}>
        <div className={styles['horn--num']}>消息提醒</div>
      </Badge>
    </div>
  );
};

const Message = props => {
  const {
    toggle,
    animationClass,
    messageData,
    openComplex,
    onMark,
    loading,
    viewDetail,
    onStow,
    stowClass,
  } = props;

  const ReminderItem = args => {
    const { item } = args;
    let message = {};
    try {
      message = JSON.parse(item.sendContent || '{}');
    } catch (e) {
      console.error('消息数据格式错误');
    }

    return (
      <div className={styles.item}>
        <div className={styles.info}>
          <span className={styles['order-number']}>{message.orderNo}</span>
          <span className={styles['mark-read']} onClick={() => onMark([item.id])}>
            标记为已读
          </span>
        </div>
        <div className={styles.time}>
          <span>{message.time}</span>
        </div>
        <div className={styles.notice}>
          <a onClick={() => viewDetail(message)}>{message.title}，请查看</a>
        </div>
      </div>
    );
  };

  return (
    <div className={classNames(styles['message-reminder'], styles[animationClass])}>
      <div className={styles['message-reminder__header']}>
        <div className={styles['message-reminder__header--title']}>
          消息提醒
          <span className={styles.close} onClick={toggle}>
            <CloseOutlined />
          </span>
        </div>
      </div>
      <div className={styles['message-reminder__body']}>
        <Spin spinning={loading}>
          <div className={styles['message-reminder__body--list']}>
            {messageData.length ? (
              messageData
                .filter((e, i) => i < 10)
                .map(item => <ReminderItem key={item.id} item={item} />)
            ) : (
              <Empty text="暂无数据" />
            )}
          </div>
        </Spin>
      </div>
      <div className={styles['message-reminder__footer']}>
        <div className={styles['message-reminder__footer--actions']}>
          <div className={styles.more} onClick={openComplex}>
            查看更多
          </div>
          <div
            className={styles['mark-all']}
            onClick={() => {
              onMark(messageData.filter((e, i) => i < 10).map(item => item.id));
            }}
          >
            全部标记为已读
          </div>
        </div>
      </div>
    </div>
  );
};

const Simple = props => {
  const { dispatch, unReadCount, complexRef, unReadData } = props;
  const history = useHistory();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [count, setCount] = useState(0);
  const [hornClass, setHornClass] = useState('');
  const [messageClass, setMessageClass] = useState('');
  const [stowClass, setStowClass] = useState('');

  const [messageData, setMessageData] = useState([]);

  let userInfo = JSON.parse(localStorage.getItem('user') || '{}');

  const toggle = () => {
    setVisible(!visible);
  };

  // 初始化获取数据
  const getMsgList = async () => {
    if (!userInfo.supplierCode) {
      userInfo = JSON.parse(localStorage.getItem('user') || '{}');
      setTimeout(() => {
        getMsgList();
      }, 1000);
      return;
    }
    const params = {
      pageNo: 1,
      pageSize: 200,
    };
    const data = {
      channelId: CHANNEL_ID,
      bussinessId: userInfo.supplierCode,
      readStatus: 0,
    };
    setLoading(true);
    const res = await apiGetBussinessMsgList(data, params);
    setLoading(false);
    if (!res) return;
    if (res.code !== '0000') {
      notification.error(res.msg);
      return;
    }
    const { content } = res.data;
    setVisible(!!content.length);
    dispatch({
      type: 'messageReminder/setUnReadData',
      payload: content,
      options: {
        unReadCount: content.length,
      },
    });
  };

  const viewDetail = message => {
    const { orderNo, type } = message;
    console.log(type);

    if ([1, 2].includes(type)) {
      history.push({
        pathname: '/orderManage/pendingDeliveryOrder',
        query: { orderNo },
      });
    }

    if ([3, 4, 5, 6].includes(type)) {
      history.push({
        pathname: '/afterSaleManage',
        query: { orderNo },
      });
    }
    toggle();
  };

  // 打开消息提醒弹框
  const openComplex = () => {
    complexRef.current.open();
    toggle();
  };

  const onStow = e => {
    e.preventDefault();
    e.stopPropagation();
    if (stowClass) {
      setStowClass('');
    } else {
      setStowClass('stow');
    }
  };

  // 标记已读信息
  const onMark = idsList => {
    if (!idsList.length) {
      return;
    }
    const payload = {
      channelId: CHANNEL_ID,
      bussinessId: userInfo.supplierCode,
      idsList,
    };
    dispatch({
      type: 'messageReminder/setMarkRead',
      payload,
      options: {
        setLoading,
      },
    });
  };

  useEffect(() => {
    setCount(unReadCount);
  }, [unReadCount]);

  useEffect(() => {
    setHornClass(visible ? 'hide' : 'show');
    setMessageClass(visible ? 'show' : 'hide');
  }, [visible]);

  useEffect(() => {
    getMsgList();
  }, []);

  useEffect(() => {
    setMessageData(unReadData);
  }, [unReadData]);

  const hornProps = {
    animationClass: hornClass,
    stowClass,
    toggle,
    count,
    onStow,
  };

  const messageProps = {
    animationClass: messageClass,
    toggle,
    messageData,
    openComplex,
    onMark,
    loading,
    viewDetail,
  };

  // 隐藏消息提醒
  return (
    <>
      <Horn {...hornProps} />
      <Message {...messageProps} />
    </>
  );
};

export default connect(({ messageReminder }) => ({
  unReadCount: messageReminder.unReadCount,
  unReadData: messageReminder.unReadData,
}))(Simple);
