import {FC, useCallback, useEffect, useState} from "react";
import {View} from "@tarojs/components";
import {Meeting, meetingAPi} from "@/api";
import styles from './meetings.module.scss'
import Taro, {useReachBottom} from "@tarojs/taro";
import Empty from "@/components/empty/empty";
import {formatDate} from "@/utils/time";

const MeetingsConfig: FC = () => {
  const [page, setPage] = useState(1)
  const [meeting, setMeeting] = useState<Meeting[]>([])
  const [total, setTotal] = useState(0)

  const getData = useCallback(async () => {
    try {
      const res = await meetingAPi.setList(1, 10)
      setTotal(res.total)
      setMeeting([
        ...(meeting || []),
        ...res.data
      ])
    } catch (e) {
    }
  }, [page])

  function del(id: number, index: number) {
    try {
      Taro.showModal({
        title: '确定删除',
        async success({confirm}) {
          if (confirm) {
            await meetingAPi.del(id)

            const oldMeeting: Meeting[] = JSON.parse(JSON.stringify(meeting))
            oldMeeting.splice(index, 1)
            setMeeting(oldMeeting)
          }
        }
      })
    } catch (e) {
    }
  }

  function jumpInfo(item: Meeting) {
    if (Date.now() > item.estimate_end_time || item.status > 0) {
      return
    }
    Taro.navigateTo({url: `/pages/manage/spotMeeting/spotMeeting?id=${item.id}`})
  }

  useReachBottom(useCallback(() => {
    if (meeting?.length < total) {
      setPage(page + 1)
    }
  }, [total, meeting]))

  useEffect(() => {
    getData()
  }, [page])

  return (
    <View className='p-2'>

      {
        meeting.length ?
          meeting.map((d, index) => <View className={styles.meeting} key={d.id}>
            <View className={styles.title} onClick={() => jumpInfo(d)}>
              <View className='font-weight mb-1'>{d.name}</View>
              <View>{formatDate(new Date(d.estimate_start_time), "MM-dd")} 至 {formatDate(new Date(d.estimate_start_time), "MM-dd")}</View>
              {
                (Date.now() > d.estimate_end_time || d.status > 1) && <View className={styles.overdue}>
                  {d.status > 1 ? '已结束' : "已过期"}
                </View>
              }
            </View>
            <View className={styles.del} onClick={() => del(d.id, index)}>删除</View>
          </View>)
          : <Empty name='无历史记录'/>
      }
    </View>
  )
}

export default MeetingsConfig
