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 } from '@/store/action/all'
import dayjs from 'dayjs'
import { MessageFu } from '@/utils/message'

// 待完善后端接口没有（还应该在 当该时间段存在已通过/待审核的申请 把num变成0）
const baseList: A3ListApiType[] = [
  {
    createTime: '2024-04-16 17:02:48',
    creatorId: 1,
    creatorName: '',
    friday: 1,
    id: 1,
    monday: 1,
    saturday: 1,
    sunday: 1,
    thursday: 1,
    time: 'am',
    tuesday: 1,
    updateTime: '2024-12-14 16:22:25',
    wednesday: 0
  },
  {
    createTime: '2024-04-16 18:07:02',
    creatorId: 1,
    creatorName: '',
    friday: 0,
    id: 2,
    monday: 0,
    saturday: 1,
    sunday: 1,
    thursday: 0,
    time: 'pm',
    tuesday: 1,
    updateTime: '2024-12-14 17:40:03',
    wednesday: 0
  }
]
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('日', '')
      const noTimeArr = noTime.split(',')

      setTimeout(() => {
        setLoding(true)

        const arr: A3ListType[] = []

        const arrTime = getWeekList('MM-DD')

        // 上午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 = -1
        if (noeXisoShi >= 17) arr[0].xiaNum = -1

        setList(arr)
      }, 100)
    }
  }, [])

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

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

  // 点击上午和下午
  // 待完善 接口返回的 usable字段 含义不明确
  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) 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} {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 < 0 ? '上午已超时' : '上午'}
                      {item.shangNum ? '' : '（已满）'}
                    </div>
                    <div
                      onClick={() => AmPmclick(item.id, 'pm')}
                      className={classNames(
                        item.id === acObj.id && acObj.AmPm === 'pm' ? 'A3ac' : '',
                        item.xiaNum > 0 ? '' : 'myBtnNo'
                      )}
                    >
                      下午{item.xiaNum ? '' : '（已满）'}
                    </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
