import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, InputNumber, Modal, TimePicker } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A2NlistType } from '../type'
import dayjs from 'dayjs'
import { A2N_APIsavePeriod } from '@/store/action/A2orderSetNew'
import { MessageFu } from '@/utils/message'

type Props = {
  closeFu: () => void
  succFu: () => void
  info: A2NlistType
}

function A2Nperiod({ closeFu, succFu, info }: Props) {
  const [list, setList] = useState<A2NlistType[]>([])

  useEffect(() => {
    if (info.times && info.times.length) setList(info.times)
  }, [info.times])

  // 有id，被删除的id集合
  const deelIds = useRef<number[]>([])

  // 点击新增
  const addFu = useCallback(() => {
    const obj = {
      id: Date.now(),
      isNew: true,
      pcs: 1,
      subjectBookId: info.id,
      timeStart: '',
      timeEnd: ''
    } as A2NlistType

    setList([...list, obj])
  }, [info.id, list])

  //  点击删除
  const delFu = useCallback(
    (item: A2NlistType) => {
      if (!item.isNew) deelIds.current.push(item.id)
      setList(list.filter(v => v.id !== item.id))
    },
    [list]
  )

  const inputNoOk = useMemo(() => {
    let flag = false
    if (list.some(v => !v.timeStart || !v.pcs)) flag = true
    return flag
  }, [list])

  // 点击提交
  const btnOk = useCallback(async () => {
    const obj = {
      removeIds: deelIds.current,
      times: list.map(v => ({
        ...v,
        id: v.isNew ? null : v.id
      }))
    }
    const res = await A2N_APIsavePeriod(obj)
    if (res.code === 0) {
      MessageFu.success('设置成功')
      succFu()
      closeFu()
    }
  }, [closeFu, list, succFu])

  return (
    <Modal
      wrapClassName={styles.A2Nperiod}
      open={true}
      title={
        <div className='A2NPtit'>
          <span>可预约时段</span>
          <Button
            type='primary'
            disabled={list.length >= 10 || inputNoOk}
            onClick={addFu}
          >
            新增时段
          </Button>
        </div>
      }
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='A2NPmain'>
        {list.map(item => (
          <div className='A2NProw' key={item.id}>
            <TimePicker.RangePicker
              format='HH:mm'
              value={
                item.timeStart
                  ? [dayjs(item.timeStart, 'HH:mm'), dayjs(item.timeEnd, 'HH:mm')]
                  : null
              }
              onChange={(_, value) => {
                const flag = _ && value.length
                setList(
                  list.map(v => ({
                    ...v,
                    timeStart: v.id === item.id ? (flag ? value[0] : '') : v.timeStart,
                    timeEnd: v.id === item.id ? (flag ? value[1] : '') : v.timeEnd
                  }))
                )
              }}
            />

            <div>
              最多可申请人数：
              <InputNumber
                style={{ width: 200 }}
                min={1}
                max={999}
                precision={0}
                placeholder='请输入1~999的整数'
                value={item.pcs}
                onChange={e =>
                  setList(
                    list.map(v => ({
                      ...v,
                      pcs: item.id === v.id ? e : v.pcs
                    }))
                  )
                }
              />
            </div>

            <MyPopconfirm
              txtK='删除'
              onConfirm={() => delFu(item)}
              Dom={<Button danger>删除</Button>}
            />
          </div>
        ))}
      </div>

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

const MemoA2Nperiod = React.memo(A2Nperiod)

export default MemoA2Nperiod
