import React, { useRef } from 'react'
import { Button, message, Form } from 'antd'
import { ModalForm, ProFormDependency, ProFormRadio, ProFormSelect, ProFormText } from '@ant-design/pro-form'
import type { ProFormColumnsType } from '@ant-design/pro-form'
import ProTable from '@ant-design/pro-table'
import type { ActionType } from '@ant-design/pro-table'
import ShowTitleMenu from '../Attendance/components/ShowTitleMenu'
import { useRequest } from '@umijs/max'
import { queryNoticeList, sendNotice } from '@/services/user/api'
import consts from '@/utils/consts'
import { PlusOutlined } from '@ant-design/icons'
import useWebSocketFn, { cmdType } from '@/hooks/core/useWebSocketFn'
import RighEditor from './components/RighEditor'
import { PageContainer } from '@ant-design/pro-layout'

export enum msgTypeEnum {
  Notification = 'notification',
  Message = 'message'
}
export enum mediaType {
  VersionUpdate = 1,
  HolidayNotice = 2
}

const Notification: React.FC = () => {
  const tRef = useRef<ActionType>(null)
  const { sendMsg } = useWebSocketFn()

  const columns: ProFormColumnsType<API.NoticeItem>[] = [
    {
      title: '标题',
      dataIndex: 'title',
      width: '30%'
    },
    {
      title: '内容',
      dataIndex: 'content',
      width: '50%'
    },
    {
      title: '推送时间',
      dataIndex: 'createTime',
      valueType: 'dateTime'
    }
  ]

  const { run: trySendNotice } = useRequest(sendNotice, {
    manual: true,
    onSuccess: result => {
      tRef.current?.reload()
      sendMsg(cmdType.Notice, result)
    },
    onError: e => {
      message.error(e.message)
    }
  })

  const handleFormValues = values => {
    const newValues = { ...values }
    switch (values.msgType) {
      case msgTypeEnum.Notification:
        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 (
    <PageContainer title={false} breadcrumb={false}>
      <div className="h-full w-full flex flex-row">
        <ShowTitleMenu options={[{ label: '通知', value: 1 }]} defaultValue={1} />
        <div className="w-max-3/4">
          <div className="ml-8 bg-white shadow-md shadow-hex-3e2c5a relative">
            {/* <div className="pb-3 border-b border-b-black border-opacity-8 mb-3 flex items-center justify-between">
            <div>通知推送</div>
          </div> */}
            <ProTable
              isKeyPressSubmit
              actionRef={tRef}
              columns={columns}
              params={{ msgType: 'notification' }}
              search={false}
              toolbar={{
                title: '通知推送',
                actions: [
                  <ModalForm
                    isKeyPressSubmit={false}
                    key="modalForm"
                    trigger={
                      <Button type="primary">
                        <PlusOutlined />
                        新建通知
                      </Button>
                    }
                    initialValues={{ msgType: 'notification', refresh: 0 }}
                    onFinish={async values => {
                      try {
                        const nValues = handleFormValues(values)
                        await trySendNotice(nValues)
                        message.success('添加成功')
                        return true
                      } catch (error) {
                        return false
                      }
                    }}>
                    <ProFormText
                      label="标题"
                      name="title"
                      rules={[{ required: true, message: '请输入标题' }]}
                    />
                    {/* <ProFormTextArea label="内容" name="content" required /> */}
                    <Form.Item
                      label="内容"
                      name="content"
                      rules={[{ required: true, message: '请输入通知内容' }]}>
                      <RighEditor />
                    </Form.Item>
                    <ProFormRadio.Group
                      label="类型"
                      name="msgType"
                      required
                      options={[
                        { label: '通知', value: msgTypeEnum.Notification },
                        { label: '消息', value: msgTypeEnum.Message }
                      ]}
                    />
                    <ProFormDependency name={['msgType']}>
                      {({ msgType }) =>
                        msgType === msgTypeEnum.Notification ? (
                          <ProFormSelect
                            name="media"
                            label="通知类型"
                            rules={[{ required: true, message: '请选择类型' }]}
                            options={[
                              { label: '版本更新', value: mediaType.VersionUpdate },
                              { label: '节假通知', value: mediaType.HolidayNotice }
                            ]}
                          />
                        ) : null
                      }
                    </ProFormDependency>
                    <ProFormDependency name={['msgType', 'media']}>
                      {({ msgType, media }) =>
                        msgType === msgTypeEnum.Notification && media === mediaType.VersionUpdate ? (
                          <ProFormRadio.Group
                            name="refresh"
                            rules={[{ required: true, message: '请选择刷新机制' }]}
                            options={[
                              { label: '手动刷新', value: 0 },
                              { label: '强制刷新', value: 1 }
                            ]}
                          />
                        ) : null
                      }
                    </ProFormDependency>
                  </ModalForm>
                ]
              }}
              request={async (params, sort, filter) => {
                const { code = -1, data = {} } = await queryNoticeList({
                  ...params,
                  ...sort,
                  ...filter
                })
                const { message: notices = [], total = 0 } = data
                return {
                  data: notices,
                  success: code === consts.RET_CODE.SUCCESS,
                  total
                }
              }}
              bordered
              pagination={{ defaultPageSize: 10 }}
              rowKey={row => row.id}
            />
          </div>
        </div>
      </div>
    </PageContainer>
  )
}

export default Notification
