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, B3_APIgetList } from '@/store/action/all'
import { B3ListApiType, 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 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)
    }
  }, [])

  // 获取日期信息（过滤掉不可预约日期）
  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

      // 取消晚上8点，按晚上12点来
      let xiaoShi8 = nowXiaoShi >= 20 ? 7 : 7

      const arr1 = getWeekList(undefined, undefined, xiaoShi8)

      let arrRes: TimeChageResType[] = []

      // 过滤掉 日期没有名额的-----------
      const res2 = await B3_APIgetList()
      if (res2.code === 0) {
        const listAll: B3ListApiType[] = res2.data

        const obj: { [key: string]: B3TimeArrType[] } = {
          0: [],
          1: [],
          2: [],
          3: [],
          4: [],
          5: [],
          6: []
        }

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

        arr1.forEach((v, i) => {
          if (!noTimeArr.includes(v.date)) {
            const num = dayjs(v.timeStamp).day()
            const acArr = obj[num]
            if (acArr.some(c => c.pcs)) {
              arrRes.push(v)
            }

            // 只有周六日可以约
            // if ([6, 0].includes(num)) {
            //   arrRes.push(v)
            // }
          }
        })
        if (arrRes && arrRes.length) setNowTime(arrRes[0].date)

        // 设置顶部数组
        setZhouArr(arrRes)
        setLoding(true)
      }
    }
  }, [])

  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[]>([])

  // 初始进入页面 设置 第一个日期的 入馆时间 数组
  useEffect(() => {
    if (zhouArr && zhouArr.length) {
      cutTopFu(zhouArr[0].date)
    }
  }, [cutTopFu, zhouArr])

  // 选中的顶部索引
  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]
  )

  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
