import React, { useCallback, useEffect, 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 } from '@/store/action/all'
import { B3TimeArrType } from './type'
import { useParams } from 'react-router-dom'

function B3start() {
  // 获取路由参数key，1:个人/2:团体
  const urlObjTemp: any = useParams()

  const [list, setList] = useState<B3TimeArrType[]>([])

  const [loding, setLoding] = useState(false)

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

    if (res.code === 0) {
      let noTime: string = res.data.stopDate
      let noTimeArr = noTime
        .replaceAll('年', '.')
        .replaceAll('月', '.')
        .replaceAll('日', '')
        .split(',')
      // noTimeArr = noTimeArr.map(v => dayjs().format('YYYY') + '.' + v)

      // 过了晚上8点 之后 列表显示8个
      const nowXiaoShi = dayjs().hour()
      let xiaoShi8 = nowXiaoShi >= 20 ? 8 : 7

      const arr = getWeekList(undefined, undefined, xiaoShi8)

      let arrRes: TimeChageResType[] = []
      arr.forEach(v => {
        if (!noTimeArr.includes(v.date)) {
          arrRes.push(v)
          // 只有周六日可以约
          // const num = dayjs(v.timeStamp).day()
          // if ([6, 0].includes(num)) arrRes.push(v)
        }
      })

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

      // 设置顶部数组
      setZhouArr(arrRes)

      setLoding(true)

      // 设置入馆时间数组
      setList(res.data.time)
    }
  }, [])

  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 [acInd, setAcInd] = useState(-1)

  // 判断当天时间是否已经超时
  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]
  )

  // 点击顶部的切换日期
  const cutTopFu = useCallback(async (val: string) => {
    const varRes = val.replaceAll('.', '-')

    const res = await B1_APIgetInfoByDay(varRes)

    if (res.code === 0) {
      // 切换顶部选中
      setNowTime(val)
      // 清空底部索引选中
      setAcInd(-1)
      // 设置入馆时间数组
      setList(res.data.time)
    }
  }, [])

  return (
    <div className={styles.B3start}>
      <div className='B3main'>
        <div className='B3tit'>选择日期（{urlObjTemp.key === '1' ? '个人预约' : '团队预约'}）</div>
        <div className='B3nowTime'>{nowTime}</div>

        {zhouArr.length ? (
          <div className='B3selDay'>
            {zhouArr.map(item => (
              <div
                key={item.name + item.date}
                className={classNames('B3dayRow', nowTime === item.date ? 'B3dayRowAc' : '')}
                onClick={() => cutTopFu(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>

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

const MemoB3start = React.memo(B3start)

export default MemoB3start
