import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { Button, Form, FormInstance, Modal } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import TextArea from 'antd/es/input/TextArea'
import { A2_APIgetConfig, A2_APIsetConfig } from '@/store/action/A2orderSet'
import { MessageFu } from '@/utils/message'

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

function A2EMail({ closeFu }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 获取设置
  const getEMfu = useCallback(async () => {
    const res = await A2_APIgetConfig('cms/book/config/get', 12)
    if (res.code === 0) {
      FormBoxRef.current?.setFieldsValue({ rtf: res.data.rtf })
    }
  }, [])

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

  // 没有通过校验
  const onFinishFailed = useCallback(() => {}, [])

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: { rtf: string }) => {
      const res = await A2_APIsetConfig('cms/book/config/edit', { id: 12, rtf: values.rtf || '' })
      if (res.code === 0) {
        MessageFu.success('设置邮箱地址成功!')
        closeFu()
      }
    },
    [closeFu]
  )

  return (
    <Modal
      wrapClassName={styles.A2EMail}
      open={true}
      title=''
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <Form
        ref={FormBoxRef}
        name='basic'
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete='off'
        scrollToFirstError
      >
        <Form.Item
          label='邮箱地址'
          name='rtf'
          rules={[
            {
              pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
              message: '请输入正确格式的邮箱!'
            }
          ]}
          getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
        >
          <TextArea maxLength={50} showCount placeholder='请输入内容' />
        </Form.Item>

        {/* 确定和取消按钮 */}
        <Form.Item className='A2Ebtn'>
          <MyPopconfirm txtK='取消' onConfirm={closeFu} /> &emsp;
          <Button type='primary' htmlType='submit'>
            提交
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  )
}

const MemoA2EMail = React.memo(A2EMail)

export default MemoA2EMail
