import React, { useState } from 'react'
import { Input, Checkbox, Table } from 'antd'
import { fetch, apis } from '@/utils/request'
import moment from 'moment'

const getRooms = fetch(apis.activity.livingRooms)

const roomStatus = [
  '预约中',
  '直播中',
  '已结束',
  '已过期',
  '已取消',
]

export default (props) => {
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const [livingId, setLivingId] = useState()
  
  const handleCheck = (e, room) => {
    const checked = e.target.checked
    const livingId = checked ? room.livingid : undefined
    setLivingId(livingId)

    if (props.onChange) {
      props.onChange(checked ? room : undefined)
    }
  }

  const columns = [
    {
      title: '#',
      key: '#',
      render: (_, room) => <Checkbox checked={room.livingid === livingId} onChange={(e) => handleCheck(e, room)} />
    },
    {
      title: '房间',
      dataIndex: 'theme',
      key: 'theme',
      render: t => t || '[直播间无名称]'
    },
    {
      title: '开播时间',
      dataIndex: 'living_start',
      key: 'living_start',
      render: (_, room) => moment((room.living_start || room.reserve_start)*1000).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: t =>  roomStatus[t]
    },
  ]

  const handleSearch = (phone) => {
    setLoading(true)
    getRooms({ params: { phone } }).then((res) => {
      setLoading(false)
      setList(res||[])
    }).catch(() => {
      setLoading(false)
    })
  }

  return (
    <Table
      bordered
      rowKey="livingid"
      loading={loading}
      columns={columns}
      dataSource={list}
      pagination={false}
      title={() => <Input.Search placeholder="请输入主播电话" enterButton="Search" onSearch={handleSearch} />}
    />
  )
}
