import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Modal, Table, TimePicker, Select } from 'antd'
import dayjs from 'dayjs'
import { DeleteOutlined } from '@ant-design/icons'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { C1eTableDataKeyType, C1tableType } from '@/types'
import { C1eTableData } from '../data'
import { C1_APIdel, C1_APIsave } from '@/store/action/C1reserveOpt'

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

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

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

function C1edit({ list, closeFu, editTableFu }: Props) {
  // 表格数据
  const [listRes, setListRes] = useState<C1tableType[]>([])
  // 当前时段，1是上午，2是下午
  const [currentTime, setCurrentTime] = useState(1)

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

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

  // 时段点击确定
  const timeBtnOk = useCallback(async () => {
    // 冲突校验逻辑
    if (time.value) {
      // 解析新时段时间
      const [newStart, newEnd] = time.value
      const newStartMin = parseInt(newStart.split(':')[0]) * 60 + parseInt(newStart.split(':')[1])
      const newEndMin = parseInt(newEnd.split(':')[0]) * 60 + parseInt(newEnd.split(':')[1])

      // 检查与现有时段的冲突（排除自己）
      const hasTimeConflict = listRes.some(item => {
        if (time.txt === '编辑' && item.id === time.id) return false
        const [existStart, existEnd] = item.time.split('-')
        const existStartMin =
          parseInt(existStart.split(':')[0]) * 60 + parseInt(existStart.split(':')[1])
        const existEndMin = parseInt(existEnd.split(':')[0]) * 60 + parseInt(existEnd.split(':')[1])
        return newStartMin < existEndMin && newEndMin > existStartMin
      })
      if (hasTimeConflict) {
        return MessageFu.warning('时间段与其他时段存在时间冲突，请重新设置！')
      }

      // 类型互斥校验
      const getTimeType = (timeStr: string) => {
        // 判断时段类型（1=上午，2=下午）
        const startHour = parseInt(timeStr.split('-')[0].split(':')[0])
        return startHour < 15 ? 1 : 2
      }

      const currentType = getTimeType(time.value.join('-')) // 当前操作的时段类型
      const otherTypes = listRes
        .filter(item => (time.txt === '编辑' ? item.id !== time.id : true)) // 编辑时排除自己
        .map(item => getTimeType(item.time))

      if (otherTypes.includes(currentType)) {
        return MessageFu.warning(
          `已有${currentType === 1 ? '上午' : '下午'}时段，只能设置${
            currentType === 1 ? '下午' : '上午'
          }时段！`
        )
      }
    }

    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
        }))
      )
    }

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

  // 时间段改变
  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: C1tableType) => (
          <div className='C1ett1'>
            <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='C1ett'
              onClick={() => {
                const startHour = parseInt(item.time.split('-')[0].split(':')[0])
                setCurrentTime(startHour < 15 ? 1 : 2)
                setTime({
                  show: true,
                  value: item.time.split('-'),
                  txt: '编辑',
                  id: item.id
                })
              }}
            >
              {item.time}
            </span>
          </div>
        )
      }
    ]

    C1eTableData.forEach(v => {
      arr.push({
        title: v.title,
        render: (item: C1tableType) => (
          <span
            className='C1ett'
            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) === -1 ? '闭馆' : Reflect.get(item, v.key)}
          </span>
        )
      })
    })
    return arr
  }, [listRes])

  // 星期的数字
  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 < 1 ? 1 : txtNum
      txtNum = txtNum > 9999 ? 9999 : txtNum
      setNum({ ...num, value: txtNum })
    },
    [num]
  )

  // 提交
  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) delIds.current.forEach(v => C1_APIdel(v))

    const arr = listRes.map(v => ({
      monday: v.monday,
      tuesday: v.tuesday,
      wednesday: v.wednesday,
      thursday: v.thursday,
      friday: v.friday,
      saturday: v.saturday,
      sunday: v.sunday,
      time: v.time,
      id: v.id.includes('新') ? null : Number(v.id)
    }))
    const res = await C1_APIsave(arr)
    if (res.code === 0) {
      MessageFu.success('编辑成功!')
      editTableFu()
      closeFu()
    }
  }, [closeFu, editTableFu, listRes])

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

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

      {/* 时间选择 */}
      <Modal
        wrapClassName={styles.C1eMBox}
        open={time.show}
        title={`${time.txt}时段`}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <div className='C1eMmain'>
          <Select
            value={currentTime}
            options={[
              {
                label: '上午',
                value: 1
              },
              {
                label: '下午',
                value: 2
              }
            ]}
            onChange={v => {
              setCurrentTime(v)
              time.value = null
            }}
          />
          <TimePicker.RangePicker
            format='HH:mm'
            value={
              time.value ? [dayjs(time.value[0], 'HH:mm'), dayjs(time.value[1], 'HH:mm')] : null
            }
            disabledTime={() => {
              return {
                disabledHours: () => {
                  if (currentTime === 1) {
                    // 第一个时段限制8-14点
                    return [0, 1, 2, 3, 4, 5, 6, 7, 15, 16, 17, 18, 19, 20, 21, 22, 23]
                  } else {
                    // 第二个时段限制15-20点
                    return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 21, 22, 23]
                  }
                }
              }
            }}
            onChange={(_, value) => timeChangeFu(value)}
          />
        </div>
        <div className='C1eMbtn'>
          <Button onClick={() => setTime({} as TimeType)}>取消</Button>&emsp;
          <Button type='primary' disabled={!time.value} onClick={timeBtnOk}>
            提交
          </Button>
        </div>
      </Modal>

      {/* 星期的数字改变 */}
      <Modal
        wrapClassName={styles.C1eMBox}
        open={num.show}
        title={`${num.title} / 可预约人数`}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <div className='C1eMmain'>
          <Input
            size='large'
            style={{ width: 208 }}
            // placeholder="请输入0~9999整数"
            value={num.value === -1 ? '闭馆' : num.value}
            onChange={e => inputChange(e)}
            min={1}
            max={9999}
          />
        </div>
        <div className='C1eMbtn'>
          <Button onClick={() => setNum({} as NumType)}>取消</Button>&emsp;
          <Button type='primary' onClick={numBtnOk}>
            提交
          </Button>
          &emsp;
          <Button onClick={() => setNum({ ...num, value: -1 })}>闭馆</Button>
        </div>
      </Modal>
    </div>
  )
}

const MemoC1edit = React.memo(C1edit)

export default MemoC1edit
