import React, { useCallback, useEffect, useState } from 'react'
import styles from './index.module.scss'
import TopCom from '@/components/TopCom'
import ZFlooBtn from '@/components/ZFlooBtn'
import classNames from 'classnames'
import history from '@/utils/history'
import { A3ListApiType, A3ListType } from './type'
import getWeekList from '@/utils/timeChange'
import { A3timeChageObj } from './data'
import { A3_APIgetInfoByDay, A3_APIgetList } from '@/store/action/all'
import dayjs from 'dayjs'
import { MessageFu } from '@/utils/message'

function A3selectDay() {
  const [list, setList] = useState<A3ListType[]>([])

  const [loding, setLoding] = useState(false)

  // 获取日期信息（过滤掉不可预约日期）
  const getTimeRes = useCallback(async () => {
    const res = await A3_APIgetInfoByDay(dayjs().format('YYYY-MM-DD'))
    if (res.code === 0) {
      let noTime: string = res.data.stopDate
      noTime = noTime.replaceAll('年', '-').replaceAll('月', '-').replaceAll('日', '')
      const noTimeArr = noTime.split(',')

      const res2 = await A3_APIgetList()

      if (res2.code === 0) {
        const baseList: A3ListApiType[] = res2.data

        setLoding(true)

        let arr: A3ListType[] = []

        // const arrTime = getWeekList('YYYY-MM-DD', 8)

        // 暂时去掉 只能看到从今天开始的往后第7天开始算
        const arrTime = getWeekList('YYYY-MM-DD', 1)

        // console.log(123, arrTime)

        // 上午obj
        const AMobj = baseList[0]

        // 下午obj
        const PMobj = baseList[1]

        arrTime.forEach(v => {
          if (!noTimeArr.includes(v.date)) {
            arr.push({
              id: v.timeStamp,
              time: v.date,
              txt: v.name,
              shangNum: Reflect.get(AMobj, Reflect.get(A3timeChageObj, v.name)),
              xiaNum: Reflect.get(PMobj, Reflect.get(A3timeChageObj, v.name))
            })
          }
        })
        // if(dayjs())

        // 当天超时判断，现在不需要
        // const noeXisoShi = Number(dayjs(Date.now()).format('HH'))
        // if (noeXisoShi >= 12) arr[0].shangNum = 2
        // if (noeXisoShi >= 17) arr[0].xiaNum = 2

        arr = arr.filter(v => v.shangNum === 0 || v.xiaNum === 0)

        setList(arr)
      }
    }
  }, [])

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

  const [acObj, setAcObj] = useState({
    id: 0,
    AmPm: ''
  })

  // 点击上午和下午
  const AmPmclick = useCallback(async (idCuo: number, val: 'am' | 'pm') => {
    const time = dayjs(idCuo).format('YYYY-MM-DD')
    const res = await A3_APIgetInfoByDay(time)

    if (res.code === 0) {
      const flag = res.data.time.usable
      if (flag === 0 && res.data.time[val] === 0) setAcObj({ id: idCuo, AmPm: val })
      else MessageFu.info('当前预约时段已满')
    }
  }, [])

  return (
    <div className={styles.A3selectDay}>
      <TopCom txt='选择日期' />

      <div className={classNames('A3main', acObj.id ? '' : 'A3mainNoBtn')}>
        <div className='A3list'>
          {list.length ? (
            <div className='mySorrl'>
              {list.map(item => (
                <div
                  className='A3row'
                  key={item.id}
                  // hidden={item.shangNum !== 0 && item.xiaNum !== 0}
                >
                  <div className='A3R1'>
                    {item.time.substring(5)} {item.txt}
                  </div>
                  <div className='A3R2'>
                    <div
                      onClick={() => AmPmclick(item.id, 'am')}
                      className={classNames(
                        item.id === acObj.id && acObj.AmPm === 'am' ? 'A3ac' : '',
                        item.shangNum !== 0 ? 'myBtnNo' : ''
                      )}
                    >
                      上午
                      {item.shangNum === 1 ? '（已满）' : item.shangNum === 2 ? '（已超时）' : ''}
                    </div>
                    <div
                      onClick={() => AmPmclick(item.id, 'pm')}
                      className={classNames(
                        item.id === acObj.id && acObj.AmPm === 'pm' ? 'A3ac' : '',
                        item.xiaNum !== 0 ? 'myBtnNo' : ''
                      )}
                    >
                      下午{item.xiaNum !== 0 ? '（已满）' : ''}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className='A3listNo' hidden={!loding}>
              暂无可约日期
            </div>
          )}
        </div>
        <ZFlooBtn
          txt={acObj.id ? '下一步' : '请选择日期'}
          clickFu={() => history.push(`/selectCourse/${acObj.id}/${acObj.AmPm}`)}
        />
      </div>
    </div>
  )
}

const MemoA3selectDay = React.memo(A3selectDay)

export default MemoA3selectDay
