import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { useHistory } from 'react-router-dom';
import { Modal, Tabs, Pagination, Spin, notification, Checkbox, Badge } from 'antd';
import { apiGetBussinessMsgList, apiGetBusinessMsgUnReadCount } from '@/services/messageReminder';
import { connect } from 'dva';
import Empty from '../Empty';
import styles from './index.less';
import { CHANNEL_ID } from '@/utils/constants';

const INIT_PAGINATION = {
  pageSize: 20,
  pageNo: 1,
};
const INIT_QUERY_PARAMS = {
  type: '0',
  readStatus: '',
};

const MessageItem = props => {
  const { item, onMark, viewDetail } = props;
  /**
   * type: 0订单消息，1售后消息
   * readStatus: 0未读，1已读
   */
  const { readStatus, type } = item;
  let message = {};
  try {
    message = JSON.parse(item.sendContent || '{}');
  } catch (e) {
    console.error('消息数据格式错误');
  }

  const goodList = message.items.map((good, index) => (
    <div className={styles.good} key={String(index)}>
      <span className={styles.good__name}>{good.skuName}</span>
      <span className={styles.good__count}>x{good.quantity}</span>
    </div>
  ));
  return (
    <div className={styles['complex-list__item']}>
      <div className={styles['complex-list__item--header']}>
        <span className={styles['order-number']}> 订单编号：{message.orderNo}</span>
        <span className={styles.time}>订单时间：{message.time}</span>
        <span className={styles['read-status']}>
          {readStatus === 0 ? (
            <a className={styles['read-status--un-read']} onClick={() => onMark([item.id])}>
              标记为已读
            </a>
          ) : (
            <span className={styles['read-status--read']}>已读</span>
          )}
        </span>
      </div>
      <div className={styles['complex-list__item--body']}>{goodList}</div>
      <div className={styles['complex-list__item--footer']}>
        <div className={styles.actions}>
          <a
            onClick={() => viewDetail(message)}
            className={[styles.notice, readStatus === 0 ? styles['un-read'] : ''].join(' ')}
          >
            {message.title}，请查看
          </a>
        </div>
      </div>
    </div>
  );
};

const Complex = props => {
  const { dispatch, refInstance } = props;
  const history = useHistory();
  const [visible, setVisible] = useState(false);
  const [dataTotal, setDataTotal] = useState(10);
  const [loading, setLoading] = useState(false);
  // 消息列表数据
  const [messageData, setMessageData] = useState([]);
  // 未读消息
  const [orderUnReadCount, setOrderUnReadCount] = useState(0);
  const [afterUnReadCount, setAfterUnReadCount] = useState(0);
  // 消息列表参数
  const [queryParams, setQueryParams] = useState({ ...INIT_QUERY_PARAMS, ...INIT_PAGINATION });

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

  // 获取信息列表
  const getMsgList = async () => {
    const params = {
      pageSize: queryParams.pageSize,
      pageNo: queryParams.pageNo,
    };
    const data = {
      channelId: CHANNEL_ID,
      bussinessId: userInfo.supplierCode,
      ...queryParams,
    };
    delete data.pageSize;
    delete data.pageNo;
    setLoading(true);
    const res = await apiGetBussinessMsgList(data, params);
    setLoading(false);
    if (!res) return;
    if (res.code !== '0000') {
      notification.error(res.msg);
      return;
    }
    const { content, totalElements } = res.data;

    setMessageData(content);
    setDataTotal(totalElements);
  };

  // 获取未读数量
  const getMsgReadCount = async () => {
    const data = {
      channelId: CHANNEL_ID,
      bussinessId: userInfo.supplierCode,
    };
    const res = await apiGetBusinessMsgUnReadCount(data);
    if (res.code !== '0000') {
      notification.error(res.msg);
      return;
    }
    const { afterSalesUnRead, orderUnRead } = res.data;
    setOrderUnReadCount(orderUnRead);
    setAfterUnReadCount(afterSalesUnRead);
  };

  // 分页操作
  const onPageChange = (page, size) => {
    const current = queryParams.pageSize !== size ? 1 : page;
    setQueryParams({
      ...queryParams,
      pageNo: current,
      pageSize: size,
    });
  };

  // 筛选未读/已读
  const onReadStatusChange = e => {
    let { value } = e.target;
    if (queryParams.readStatus === e.target.value) {
      value = '';
    }
    setQueryParams({
      ...queryParams,
      readStatus: value,
    });
  };

  // 过滤参数,获取当前页未读消息数据的id
  const onFilterMessageParams = msgList =>
    msgList.filter(message => message.readStatus === 0).map(item => item.id);

  const open = () => {
    setVisible(true);
    getMsgReadCount();
  };

  const close = () => {
    setMessageData([]);
    setVisible(false);
  };

  //

  /**
   * 跳转到详情
   * type
   * 1-待发货订单
   * 2-超时发货
   * 3-仅退款（未发货）申请单
   * 4-仅退款申请单
   * 5-退货退款申请单
   * 6-退货入库待审核
   */
  const viewDetail = message => {
    const { orderNo, type } = message;

    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 },
      });
    }
    close();
  };

  // 切换消息类型
  const onTabChange = index => {
    setQueryParams({
      ...queryParams,
      ...INIT_PAGINATION,
      type: index,
    });
  };

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

  // 展开初始化
  useEffect(() => {
    if (visible) {
      getMsgList();
    }
  }, [visible, queryParams]);

  useEffect(() => {
    if (!visible) {
      setQueryParams({ ...INIT_QUERY_PARAMS, ...INIT_PAGINATION });
    }
  }, [visible]);

  useImperativeHandle(refInstance, () => ({
    open,
  }));

  const modalProps = {
    bodyStyle: {
      display: 'flex',
      flexWrap: 'wrap',
      padding: 0,
      backgroundColor: '#f7f8f9',
    },
    wrapClassName: 'complex-modal',
    width: '880px',
    height: '650px',
    visible,
    title: <span className="title-icon">消息提醒</span>,
    footer: null,
    onCancel: close,
  };

  const TabRender = tabProps => {
    const { title, count = 0 } = tabProps;
    return (
      <span className={styles['tab-render']}>
        {title}
        <Badge overflowCount={999} count={count} />
      </span>
    );
  };

  const FilterRender = filterProps => (
    <div className={styles['filter-box']}>
      <div className={styles['filter-box__content']}>
        <Checkbox checked={queryParams.readStatus === '0'} value="0" onChange={onReadStatusChange}>
          未读
        </Checkbox>
        <Checkbox checked={queryParams.readStatus === '1'} value="1" onChange={onReadStatusChange}>
          已读
        </Checkbox>
      </div>
      <div className={styles['filter-box__actions']}>
        <a onClick={() => onMark(onFilterMessageParams(messageData))}>全部标记为已读</a>
      </div>
    </div>
  );

  return (
    <Modal {...modalProps}>
      <Tabs
        className={styles.tabs}
        activeKey={queryParams.type}
        tabBarStyle={{
          width: '150px',
        }}
        tabPosition="left"
        tabBarGutter={0}
        onChange={onTabChange}
      >
        <Tabs.TabPane tab={<TabRender title="订单消息" count={orderUnReadCount} />} key="0" />
        <Tabs.TabPane tab={<TabRender title="售后消息" count={afterUnReadCount} />} key="1" />
      </Tabs>

      <div className={styles['tab-pane']}>
        <Spin spinning={loading}>
          <FilterRender />
          <div className={styles['complex-list']}>
            {visible && messageData.length ? (
              messageData.map((item, index) => (
                <MessageItem
                  key={String(index)}
                  item={item}
                  onMark={onMark}
                  viewDetail={viewDetail}
                />
              ))
            ) : (
              <Empty text="暂无数据" />
            )}
          </div>
        </Spin>
        {dataTotal > 0 ? (
          <div className={styles.pagination}>
            <Pagination
              onChange={onPageChange}
              total={dataTotal}
              showTotal={(total, range) => `第${range[0]}-${range[1]}条 /总共${total}条`}
              showSizeChanger
              pageSize={queryParams.pageSize}
              current={queryParams.pageNo}
            />
          </div>
        ) : (
          ''
        )}
      </div>
    </Modal>
  );
};

const MiddleComponent = connect(({ messageReminder }) => ({
  unReadCount: messageReminder.unReadCount,
  unReadData: messageReminder.unReadData,
}))(Complex);

// 注意：这里不要在Component上使用ref;换个属性名字比如refInstance；不然会导致覆盖

export default forwardRef((props, ref) => <MiddleComponent {...props} refInstance={ref} />);
