import React, { useEffect, useState } from 'react'
import { Card, Carousel, Row, Col } from 'antd'
import moment from 'moment'
import { orderBy } from 'lodash'
import { fetch, apis } from '@/utils/request'

const getDynamic = fetch(apis.dashboard.dynamic)

const Item = props => (
  <Row gutter={16} type="flex" align="middle" style={{ marginTop: 8, marginBottom: 8 }}>
    <Col span={8}>{props.dataSource.createDate}</Col>
    <Col span={16}>{`${props.dataSource.nickname} ${props.dataSource.desc}`}</Col>
  </Row>
)

const showMax = 10

export default props => {
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const [showSlides, setShowSlides] = useState(0)

  useEffect(() => {
    if (props.communityId) {
      const today = moment()
      // 取最近 15 天的记录
      const endDate = today.format('YYYY-MM-DD')
      today.subtract(15, 'days')
      const startDate = today.format('YYYY-MM-DD')
  
      setLoading(true)
      getDynamic({params: {startDate, endDate, communityId: props.communityId}}).then(res => {
        const { ticketList, propList, billList } = res
  
        // 组合list
        const compList = [
          ...(ticketList || []).map(x => ({...x, createDate: moment(x.createDate).format('MM-DD HH:mm'), desc: '提了一个工单'})),
          ...(propList || []).map(x => ({...x, createDate: moment(x.createDate).format('MM-DD HH:mm'), desc: '申请了一个业主认证'})),
          ...(billList || []).map(x => ({...x, createDate: moment(x.createDate).format('MM-DD HH:mm'), desc: '缴了一笔费用'})),
        ]
        
        if (compList.length === 0) {
          setShowSlides(0)
        } else {
          setShowSlides(compList.length > showMax ? showMax : compList.length - 1)
        }
  
        // 按照时间倒叙
        const newList = orderBy(compList, ['createDate'], ['desc'])
        setList(newList)
  
        setLoading(false)
      }).catch(e => console.error(e) || setLoading(false))

    }
  }, [props.communityId])

  return (
    <Card title="最新动态" loading={loading}>
      <Carousel
        dots={false}
        autoplay={true}
        lazyLoad={true}
        infinite={true}
        speed={500}
        slidesToShow={showSlides}
        slidesToScroll={1}
        dotPosition="right"
      >
        {
          list.map(x => <Item key={x.createDate} dataSource={x} />)
        }
      </Carousel>
    </Card>
  )
}
