import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Modal, Table, TimePicker } from 'antd'
import dayjs from 'dayjs'
import { DeleteOutlined } from '@ant-design/icons'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { B1eTableDataKeyType, B1tableType } from '../type'
import { B1eTableData } from '../data'
import { B1_APIdel, B1_APIsave } from '@/store/action/B1exhibit'

type TimeType = {
  id: string
  show: boolean
  value: string[] | null
  txt: '新增' | '编辑'
}

type NumType = {
  id: string
  show: boolean
  value: number
  title: string
  key: B1eTableDataKeyType
}

type Props = {
  list: B1tableType[]
  closeFu: () => void
  editTableFu: () => void
}

function B1edit({ list, closeFu, editTableFu }: Props) {
  // 表格数据
  const [listRes, setListRes] = useState<B1tableType[]>([])

  useEffect(() => {
    setListRes(
      list.map(v => ({
        ...v,
        id: v.id + ''
      }))
    )
  }, [list])

  // 1---------时段
  const [time, setTime] = useState({} as TimeType)

  // 1---------时段点击确定
  const timeBtnOk = useCallback(async () => {
    if (time.txt === '新增') {
      setListRes([
        ...listRes,
        {
          id: time.id,
          time: time.value!.join('-'),
          monday: 100,
          tuesday: 100,
          wednesday: 100,
          thursday: 100,
          friday: 100,
          saturday: 100,
          sunday: 100
        }
      ])
    } else {
      setListRes(
        listRes.map(v => ({
          ...v,
          time: v.id === time.id ? time.value!.join('-') : v.time
        }))
      )
    }

    MessageFu.success(time.txt + '时段成功!')

    setTime({} as TimeType)
  }, [listRes, time])

  // 1---------时间段改变
  const timeChangeFu = useCallback(
    (value: string[]) => {
      const valueRes = value[0] && value[1] ? value : null
      setTime({ ...time, value: valueRes })
    },
    [time]
  )

  // 从后台拿的数据，id里面没有’新‘。删除的时候需要记录下来。最后点击提交的时候一起删除
  const delIds = useRef<string[]>([])

  // 表格
  const columns = useMemo(() => {
    const arr: any = [
      {
        title: '时段',
        render: (item: B1tableType) => (
          <div className='B1ett1'>
            <MyPopconfirm
              txtK='删除'
              onConfirm={() => {
                if (listRes.length <= 1) return MessageFu.warning('至少需要一个时段!')
                setListRes(listRes.filter(v => v.id !== item.id))
                if (!item.id.includes('新')) {
                  delIds.current.push(item.id)
                }
              }}
              Dom={<DeleteOutlined />}
            />

            <span
              className='B1ett'
              onClick={() =>
                setTime({
                  show: true,
                  value: item.time.split('-'),
                  txt: '编辑',
                  id: item.id
                })
              }
            >
              {item.time}
            </span>
          </div>
        )
      }
    ]

    B1eTableData.forEach(v => {
      arr.push({
        title: v.title,
        render: (item: B1tableType) => (
          <span
            className='B1ett'
            onClick={() =>
              setNum({
                id: item.id,
                show: true,
                value: Reflect.get(item, v.key),
                title: `${item.time} / ${v.title}`,
                key: v.key
              })
            }
          >
            {Reflect.get(item, v.key)}
          </span>
        )
      })
    })
    return arr
  }, [listRes])

  // 2---------星期的数字
  const [num, setNum] = useState({} as NumType)

  const inputChange = useCallback(
    (val: React.ChangeEvent<HTMLInputElement>) => {
      let txt = val.target.value.replace(/^(0+)|[^\d]+/g, '')
      let txtNum = Number(txt)
      txtNum = txtNum > 9999 ? 9999 : txtNum
      setNum({ ...num, value: txtNum })
    },
    [num]
  )

  // 2---------提交
  const numBtnOk = useCallback(() => {
    setListRes(
      listRes.map(v => ({
        ...v,
        [num.key]: v.id === num.id ? Number(num.value) : Reflect.get(v, num.key)
      }))
    )
    MessageFu.success('编辑可预约人数成功!')
    setNum({} as NumType)
  }, [listRes, num])

  // 最后点击提交
  const btnLastOk = useCallback(async () => {
    if (delIds.current.length) B1_APIdel(delIds.current.join(','))

    const arr = listRes.map(v => ({
      ...v,
      id: v.id.includes('新') ? null : Number(v.id)
    }))
    const res = await B1_APIsave(arr)
    if (res.code === 0) {
      MessageFu.success('编辑成功!')
      editTableFu()
      closeFu()
    }
  }, [closeFu, editTableFu, listRes])

  return (
    <div className={styles.B1edit}>
      <div className='B1ell'>
        <Button
          type='primary'
          onClick={() => {
            if (listRes.length >= 10) return MessageFu.warning('最多10个时段!')
            setTime({
              show: true,
              value: null,
              txt: '新增',
              id: Date.now() + '新'
            })
          }}
        >
          新增时段
        </Button>
      </div>
      <div className='B1err'>
        <Table
          rowKey='id'
          size='middle'
          columns={columns}
          dataSource={listRes}
          pagination={false}
        />
      </div>

      <div className='B1eBtn'>
        <Button type='primary' onClick={btnLastOk}>
          提交
        </Button>
        <br />
        <br />
        <MyPopconfirm txtK='取消' onConfirm={closeFu} />
      </div>

      {/* 时间选择 */}
      <Modal
        wrapClassName={styles.B1eMBox}
        open={time.show}
        title={`${time.txt}时段`}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <div className='B1eMmain'>
          <TimePicker.RangePicker
            format='HH:mm'
            value={
              time.value ? [dayjs(time.value[0], 'HH:mm'), dayjs(time.value[1], 'HH:mm')] : null
            }
            onChange={(_, value) => timeChangeFu(value)}
          />
        </div>
        <div className='B1eMbtn'>
          <Button onClick={() => setTime({} as TimeType)}>取消</Button>&emsp;
          <Button type='primary' disabled={!time.value} onClick={timeBtnOk}>
            提交
          </Button>
        </div>
      </Modal>

      {/* 星期的数字改变 */}
      <Modal
        wrapClassName={styles.B1eMBox}
        open={num.show}
        title={`${num.title} / 可预约人数`}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <div className='B1eMmain'>
          <Input
            style={{ width: 208 }}
            // placeholder="请输入0~9999整数"
            value={num.value}
            onChange={e => inputChange(e)}
          />
          <div className='B1eMmainTit'>&nbsp;&nbsp;为0时，则该时段不可预约（闭馆）</div>
        </div>
        <div className='B1eMbtn'>
          <Button onClick={() => setNum({} as NumType)}>取消</Button>&emsp;
          <Button type='primary' onClick={numBtnOk}>
            提交
          </Button>
        </div>
      </Modal>
    </div>
  )
}

const MemoB1edit = React.memo(B1edit)

export default MemoB1edit
