import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Modal } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A2NlistType } from '../type'
import { A2N_APIgetList, A2N_APIsave } from '@/store/action/A2orderSetNew'
import dayjs, { Dayjs } from 'dayjs'
import { processDates } from '../data'
import { MessageFu } from '@/utils/message'

type Props = {
  closeFu: () => void
  succFU: () => void
}

function A2Ncan({ closeFu, succFU }: Props) {
  // 所有日期
  const listAll = useRef<A2NlistType[]>([])

  const [timeList, setTimeList] = useState<string[]>([])

  const getListFu = useCallback(async () => {
    const res = await A2N_APIgetList()
    if (res.code === 0) {
      const today = dayjs().startOf('day') // 当天 00:00:00

      const listRes: A2NlistType[] = res.data || []
      listAll.current = listRes

      const validData: string[] = []

      listRes.forEach(v => {
        const itemDate = dayjs(v.date)
        if (itemDate.isSame(today) || itemDate.isAfter(today)) {
          validData.push(v.date)
        }
      })

      setTimeList(validData)
    }
  }, [])

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

  // 时间选择器的改变
  const timeOnChange = useCallback((e: dayjs.Dayjs[], e2: string[]) => {
    if (e && e2.length) {
      setTimeList(e2)
    } else {
      // 点击了清空
      setTimeList([])
    }
  }, [])

  // 禁用今天之前的日期逻辑
  const disabledDate = useCallback((current: Dayjs) => {
    const today = dayjs().startOf('day') // 获取当天零点时间
    return current.isBefore(today, 'day') // 严格早于今天则禁用
  }, [])

  const btnOk = useCallback(async () => {
    const obj = processDates(listAll.current, timeList)
    const res = await A2N_APIsave(obj)
    if (res.code === 0) {
      MessageFu.success('设置成功')
      succFU()
      closeFu()
    }
    // console.log(123456, obj)
  }, [closeFu, succFU, timeList])

  return (
    <Modal
      wrapClassName={styles.A2Ncan}
      open={true}
      title='可预约日期设置(提交的时候会自动删除今天之前的日期)'
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <DatePicker
        multiple
        maxTagCount='responsive'
        onChange={(e, e2) => timeOnChange(e, e2 as string[])}
        value={timeList.map(v => dayjs(v))}
        size='large'
        format='YYYY-MM-DD'
        disabledDate={disabledDate}
      />

      <div className='A2Nbtn'>
        <MyPopconfirm txtK='取消' onConfirm={closeFu} />
        &emsp;
        <Button type='primary' onClick={btnOk}>
          提交
        </Button>
      </div>
    </Modal>
  )
}

const MemoA2Ncan = React.memo(A2Ncan)

export default MemoA2Ncan
