import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import ZexhiBtn from '@/components/ZexhiBtn'
import dayjs from 'dayjs'
import getWeekList, { TimeChageResType } from '@/utils/timeChange'
import classNames from 'classnames'
import history from '@/utils/history'
import { B1_APIgetInfoByDay, B3_APIgetList } from '@/store/action/all'
import { B3ListApiType, B3TimeArrType } from './type'

function B3start() {
  const [list, setList] = useState<B3ListApiType[]>([])

  const [loding, setLoding] = useState(false)

  // 获取日期信息（过滤掉不可预约日期）
  const getTimeRes = useCallback(async () => {
    const res = await B1_APIgetInfoByDay(dayjs().format('YYYY-MM-DD'))

    if (res.code === 0) {
      const res2 = await B3_APIgetList()
      if (res2.code === 0) {
        let noTime: string = res.data.stopDate
        let noTimeArr = noTime.replaceAll('月', '.').replaceAll('日', '').split(',')
        noTimeArr = noTimeArr.map(v => dayjs().format('YYYY') + '.' + v)
        const arr = getWeekList()
        let arrRes: TimeChageResType[] = []
        arr.forEach(v => {
          if (!noTimeArr.includes(v.date)) arrRes.push(v)
        })

        if (arrRes && arrRes.length) setNowTime(arrRes[0].date)

        setZhouArr(arrRes)

        setLoding(true)
        setList(res2.data)
      }
    }
  }, [])

  useEffect(() => {
    getTimeRes()
  }, [getTimeRes])

  useEffect(() => {
    setTimeout(() => {
      const dom: HTMLDivElement = document.querySelector('.B3selDay')!
      if (dom) {
        dom.scrollTo({
          left: 1000,
          behavior: 'smooth'
        })
        setTimeout(() => {
          dom.scrollTo({
            left: 0,
            behavior: 'smooth'
          })
        }, 500)
      }
    }, 500)
  }, [])

  // 获取当前时间
  const [nowTime, setNowTime] = useState('')

  // 当天往后延申的一共七天日期
  const [zhouArr, setZhouArr] = useState<TimeChageResType[]>([])

  // 当前选中时间 返回 周几(用索引表示)
  const indexRes = useMemo(() => {
    let num = -1
    const obj = zhouArr.find(v => v.date === nowTime)
    if (obj) {
      num = dayjs(obj.timeStamp).day()
      if (num === 0) num = 6
      else num -= 1
    }
    return num
  }, [nowTime, zhouArr])

  // 一周的所有 时段 数字 合集
  const zhouObj = useMemo(() => {
    const obj: { [key: string]: B3TimeArrType[] } = {
      0: [],
      1: [],
      2: [],
      3: [],
      4: [],
      5: [],
      6: []
    }

    list.forEach(v => {
      obj[0].push({ id: v.id, name: v.time, num: v.monday })
      obj[1].push({ id: v.id, name: v.time, num: v.tuesday })
      obj[2].push({ id: v.id, name: v.time, num: v.wednesday })
      obj[3].push({ id: v.id, name: v.time, num: v.thursday })
      obj[4].push({ id: v.id, name: v.time, num: v.friday })
      obj[5].push({ id: v.id, name: v.time, num: v.saturday })
      obj[6].push({ id: v.id, name: v.time, num: v.sunday })
    })

    return obj
  }, [list])

  // 返回的数据
  const numRes = useMemo(() => {
    let arr: B3TimeArrType[] = []

    if (indexRes > -1) arr = zhouObj[indexRes]
    // console.log(123, arr)

    return arr
    // const index = nowTime.
  }, [indexRes, zhouObj])

  const [acInd, setAcInd] = useState({
    index: -1,
    id: 0
  })

  const pageInd = useMemo(() => {
    let num = 0
    if (numRes[acInd.index] && numRes[acInd.index].num) num = numRes[acInd.index].num
    return num
  }, [acInd, numRes])

  // 判断当天时间是否已经超时
  const nowDayFlag = useCallback(
    (time: string) => {
      // true 表示当前时间已经超过了可预约时间
      let flag = true
      // 不是当天 直接为 false（表示全部可选择）
      if (nowTime !== dayjs().format('YYYY.MM.DD')) flag = false
      else {
        const lastTime = Number(time.split('-')[1].split(':')[0])
        const noeXisoShi = Number(dayjs(Date.now()).format('HH'))
        if (lastTime > noeXisoShi) flag = false
        // console.log(123, lastTime, noeXisoShi)
      }

      return flag
    },
    [nowTime]
  )

  //

  return (
    <div className={styles.B3start}>
      <div className='B3main'>
        <div className='B3tit'>选择日期</div>
        <div className='B3nowTime'>{nowTime}</div>

        {zhouArr.length ? (
          <div className='B3selDay'>
            {zhouArr.map(item => (
              <div
                key={item.name}
                className={classNames('B3dayRow', nowTime === item.date ? 'B3dayRowAc' : '')}
                onClick={() => setNowTime(item.date)}
              >
                <div>{item.name}</div>
                <div>{item.date.slice(-2)}</div>
              </div>
            ))}
          </div>
        ) : (
          <div hidden={!loding} style={{ fontSize: '20px', marginBottom: '30px' }}>
            无可预约日期
          </div>
        )}

        <div className='B3tit'>入馆时间</div>

        {numRes.length ? (
          <div className='B3time'>
            {numRes.map((item, index) => (
              <div
                key={item.name}
                onClick={() => setAcInd({ index, id: item.id })}
                className={classNames(
                  'B3timeRow',
                  acInd.index === index ? 'B3timeRowAc' : '',
                  item.num <= 0 || nowDayFlag(item.name) ? 'myBtnNo' : ''
                )}
              >
                {item.name}
                {item.num <= 0 ? <p>预约已满</p> : ''}
              </div>
            ))}
          </div>
        ) : (
          <span hidden={!loding} style={{ fontSize: '20px' }}>
            请先选择日期
          </span>
        )}
      </div>
      <ZexhiBtn
        nextOk={!!pageInd}
        nextFu={() => history.push(`/exhiForm/${nowTime.replaceAll('.', '_')}/${acInd.index}`)}
      />
    </div>
  )
}

const MemoB3start = React.memo(B3start)

export default MemoB3start
