import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Table } from 'antd'
import {
  A2_APIedit,
  A2_APIgeiList,
  A2_APIgetConfig,
  A2_APIsetConfig
} from '@/store/action/A2orderSet'
import { A2listType, A2NolistType } from './type'
import { A2tyleDataRes } from './data'
import A2timeFlag, { A2TcanType } from './A2timeFlag'
import { MessageFu } from '@/utils/message'
import A2NoTime from './A2NoTime'
import A2EMail from './A2EMail'
import A2xuZhi from './A2xuZhi'
import A2template from './A2template'

function A2orderSet() {
  // 1111111-------------第一个表格相关--------开始
  const [list, setList] = useState<A2listType[]>([
    { id: 1, time: 'am' } as A2listType,
    { id: 2 } as A2listType
  ])

  const getList = useCallback(async () => {
    const res = await A2_APIgeiList()
    if (res.code === 0) setList(res.data)
  }, [])

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

  const columns = useMemo(() => {
    let arr: any = [
      {
        title: '时段',
        render: (item: A2listType) => (item.time === 'am' ? '上午' : '下午')
      }
    ]

    A2tyleDataRes.forEach(v => {
      arr.push({
        title: v.name,
        width: 200,
        render: (item: A2listType) => (
          <span
            onClick={() => {
              keTimeRef.current = { ...item, myKey: v.key }
              setKeTime({
                time: `${v.name} - ${item.time === 'am' ? '上午' : '下午'}`,
                num: item[v.key as 'monday']
              })
            }}
            className='A2tabCli'
          >
            {item[v.key as 'monday'] === 1
              ? '不可预约'
              : item[v.key as 'monday'] === 0
              ? '可预约'
              : ''}
          </span>
        )
      })
    })
    return arr
  }, [])

  const [keTime, setKeTime] = useState<A2TcanType>({
    time: '',
    num: null
  })

  const keTimeRef = useRef({} as A2listType)

  // 可预约-不可预约设置
  const changeTimeFlagFu = useCallback(
    async (val: 0 | 1 | null) => {
      if (val !== null) {
        const res = await A2_APIedit({
          ...keTimeRef.current,
          [keTimeRef.current.myKey]: val
        })

        if (res.code === 0) {
          MessageFu.success('修改成功!')
          getList()
        }
      }
      setKeTime({ time: '', num: null })
    },
    [getList]
  )

  // 11111111-1------------第一个表格相关----结束

  // 222222222-------------第二个表格---------开始
  const [noList, setNoList] = useState<A2NolistType[]>([{ id: '1', time: '' }])

  const getNoListFu = useCallback(async () => {
    const res = await A2_APIgetConfig('cms/book/config/get', 10)
    if (res.code === 0) {
      setNoList([{ id: '不可预约id', time: res.data.rtf }])
    }
  }, [])

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

  const noColumns = useMemo(() => {
    return [
      {
        title: '不可预约日期',
        render: (item: A2NolistType) =>
          item.time ? item.time.replaceAll(',', ' , ') : ' - '
      },
      {
        title: '操作',
        width: 200,
        render: (item: A2NolistType) => (
          <span className='A2tabCli' onClick={() => setNoTxt(item.time || '空')}>
            设置
          </span>
        )
      }
    ]
  }, [])

  const [noTxt, setNoTxt] = useState('')

  // 点击提交或者取消
  const A2NoBtn = useCallback(
    async (val: string[] | null) => {
      let str = ''

      if (val) {
        const arr = val.map(v => v.replace('-', '年').replace('-', '月') + '日')
        str = arr.join(',')
      }

      const res = await A2_APIsetConfig('cms/book/config/edit', { id: 10, rtf: str })
      if (res.code === 0) {
        MessageFu.success('设置不可预约日期成功!')
        getNoListFu()
        setNoTxt('')
      }
    },
    [getNoListFu]
  )

  // 222222222-------------第二个表格---------结束

  // 3333333333------------- 邮箱地址---------开始E-Mail
  const [emShow, setEmShow] = useState(false)
  // 3333333333------------- 邮箱地址---------结束E-Mail

  // 444444444------------- 预约须知---------开始
  // 11:预约须知
  const [configId, setConfigId] = useState(0)
  // 444444444------------- 预约须知---------结束

  // 555555555------------- 预约单模板设置---------开始
  const [template, setTemplate] = useState(false)
  // 555555555------------- 预约单模板设置---------结束

  return (
    <div className={styles.A2orderSet}>
      <div className='pageTitle'>课程预约设置</div>

      <div className='A2top'>
        <Button type='primary' onClick={() => setEmShow(true)} hidden>
          邮箱设置
        </Button>
        &emsp;
        <Button type='primary' onClick={() => setConfigId(11)}>
          预约须知设置
        </Button>
        &emsp;
        <Button type='primary' onClick={() => setTemplate(true)}>
          预约单模板设置
        </Button>
      </div>

      <div className='A2main'>
        <Table dataSource={list} columns={columns} rowKey='id' pagination={false} />
        <div className='A2split'></div>
        <Table dataSource={noList} columns={noColumns} rowKey='id' pagination={false} />
      </div>

      {/* 可预约-不可预约设置 */}
      {keTime.time ? (
        <A2timeFlag info={keTime} closeFu={val => changeTimeFlagFu(val)} />
      ) : null}

      {/* 不可预约日期设置 */}
      {noTxt ? (
        <A2NoTime
          num={50}
          baseTime={noTxt}
          editFu={val => A2NoBtn(val)}
          closeFu={() => setNoTxt('')}
        />
      ) : null}

      {/* 邮箱设置 */}
      {emShow ? <A2EMail closeFu={() => setEmShow(false)} /> : null}

      {/*预约须知 */}
      {configId ? (
        <A2xuZhi
          setSrc='cms/book/config/edit'
          getSrc='cms/book/config/get'
          sId={configId as 11}
          closeFu={() => setConfigId(0)}
        />
      ) : null}

      {/*预约单模板设置 */}
      {template ? (
        <A2template closeFu={() => setTemplate(false)} type='课程预约' />
      ) : null}
    </div>
  )
}

const MemoA2orderSet = React.memo(A2orderSet)

export default MemoA2orderSet
