import React, { useEffect, useState } from 'react'
import { Button, Input, Menu, Dropdown, Select, Modal, Icon } from 'antd'
import { fetch, apis } from '@/utils/request'

export default props => {
  const [isInDB, setIsInDB] = useState(false)
  const [typeInfo, setTypeInfo] = useState({})
  const [dataSource, setDataSource] = useState({})
  const [typeDict, setTypeDict] = useState([
    {typeCode: 'birthday', typeName: '生日'},
    {typeCode: 'festival', typeName: '节日'},
    {typeCode: 'ticket', typeName: '工单'},
  ])

  const handleChange = e => {
    const templateCode = e.target.value
    setDataSource({
      ...dataSource,
      templateCode
    })
  }

  const handleTypeChange = e => {
    const val = typeDict.filter(x => x.typeCode === e)[0] || {}
    setTypeInfo(val)
  }

  const handleSubmit = () => {
    if (props.onChange) {
      props.onChange({
        ...dataSource,
        ...typeInfo,
      })
    }
  }

  const handleOverMenuClick = e => {
    if (e.key === 'delete') {
      if (!isInDB) {
        if (props.onDelete) {
          props.onDelete(dataSource)
        }
      } else {
        if (props.onDelete) {
          Modal.confirm({
            title: '确认删除当前记录?',
            okType: 'danger',
            onOk: () => {
              props.onDelete(dataSource)
            }
          })
        }
      }
    }
  }

  const OverMenu = (
    <Menu onClick={handleOverMenuClick}>
      <Menu.Item key="delete">删除</Menu.Item>
    </Menu>
  )

  useEffect(() => {
    const val = props.value || {}
    setDataSource({...val})
    setTypeInfo({
      typeCode: val.typeCode,
      typeName: val.typeName,
    })
    setIsInDB(val.serialNo && `${val.serialNo}`.indexOf('tmp') === -1)
  }, [props.value])

  return (
    <Input.Group compact size="large">
      <Select
        size="large"
        disabled={isInDB}
        value={typeInfo.typeCode}
        onChange={handleTypeChange}
        style={{width: '15%'}}
        placeholder="请选择分类"
      >
        {
          typeDict.map(typ => (<Select.Option key={typ.typeCode} value={typ.typeCode}>{typ.typeName}</Select.Option>))
        }
      </Select>
      <Input
        value={dataSource.templateCode}
        onChange={handleChange}
        style={{width: '70%'}}
        placeholder="请填写消息模板ID"
        readOnly={true}
        />
      {/* <Dropdown.Button
         size="large"
        overlay={OverMenu}
        onClick={handleSubmit}
        icon={<Icon type="down" />}
        style={{width: '15%'}}
      >
        提交
      </Dropdown.Button> */}
    </Input.Group>
  )
}
