import React, { useRef } from 'react'
import { Button, Form, message } from 'antd'
import {
  ModalForm,
  ProFormDependency,
  ProFormRadio,
  ProFormSelect,
  ProFormText
} from '@ant-design/pro-form'
import RighEditor from './RighEditor'
import { Plus } from '@icon-park/react'

export const msgTypeEnum = {
  NotificationOne: 'notification',
  Message: 'message'
}
export const mediaType = {
  VersionUpdate: 1,
  HolidayNotice: 2
}

const AddMessage = props => {
  const { onConfirm } = props
  const formRef = useRef(null)
  const handleFormValues = values => {
    const newValues = { ...values }
    switch (values.msgType) {
      case msgTypeEnum.NotificationOne:
        switch (values.media) {
          case mediaType.VersionUpdate:
            newValues.avatar = 'https://zhcld.com/resource/notice_email.png'
            break
          case mediaType.HolidayNotice:
            newValues.avatar = 'https://zhcld.com/resource/notice_airplane.png'
            break
          default:
            break
        }
        break

      default:
        break
    }
    return newValues
  }
  return (
    <div>
      <ModalForm
        isKeyPressSubmit={false}
        key="modalForm"
        formRef={formRef}
        trigger={
          <Button type="primary">
            <Plus className="mr-1" />
            新建通知
          </Button>
        }
        initialValues={{ msgType: 'notification', refresh: 0 }}
        onFinish={async values => {
          try {
            const nValues = handleFormValues(values)
            await onConfirm(nValues)
            formRef.current?.resetFields()
            message.success('添加成功')
            return true
          } catch (error) {
            return false
          }
        }}>
        <ProFormText
          name="title"
          label="标题"
          placeholder="请输入标题"
          rules={[{ required: true, message: '请输入标题' }]}
        />
        <Form.Item
          label="内容"
          name="content"
          rules={[{ required: true, message: '请输入通知内容' }]}>
          <RighEditor />
        </Form.Item>
        <ProFormRadio.Group
          label="类型"
          name="msgType"
          required
          options={[
            { label: '通知', value: msgTypeEnum.NotificationOne },
            { label: '消息', value: msgTypeEnum.Message }
          ]}
        />
        <ProFormDependency name={['msgType']}>
          {({ msgType }) =>
            msgType === msgTypeEnum.NotificationOne ? (
              <ProFormSelect
                name="media"
                label="通知类型"
                rules={[{ required: true, message: '请选择类型' }]}
                options={[
                  { label: '版本更新', value: mediaType.VersionUpdate },
                  { label: '节假通知', value: mediaType.HolidayNotice }
                ]}
              />
            ) : null
          }
        </ProFormDependency>
      </ModalForm>
    </div>
  )
}

export default AddMessage
