import React, { useEffect, useState } from 'react'
import { Menu, Dropdown, Button, Popconfirm, Icon, notification } from 'antd'
import Prompt from '@/components/Prompt'
import { fetchList, fetch, apis } from '@/utils/request'

const addNode = fetch(apis.buildingOwnerInfo.addNode)
const updateNode = fetch(apis.buildingOwnerInfo.updateNode)
const deleteNode = fetch(apis.buildingOwnerInfo.deleteNode)

export default props => {
  const [houseVisible, setHouseVisible] = useState(false)
  const [roomInfo, setRoomInfo] = useState({})

  const handleDelete = () => {
    deleteNode({ data: {
      id: roomInfo.id,
      name: roomInfo.name,
      type: 'end',   // 删除房间传 end
      nodeNumber: undefined,
    }}).then(() => {
      if (props.onDelete) {
        props.onDelete(roomInfo)
      }
      notification.success({message: '删除成功'})
    })
  }

  const handleEdit = val => {
    if (!roomInfo.id) {
      addNode({ data: {
        id: roomInfo.levelId,
        name: roomInfo.levelName,
        type: 'roomNo',
        nodeNumber: val,
        communityId: props.community,
      }}).then((res) => {
        if (props.onEdit) {
          props.onEdit(res)
        }
        notification.success({message: '修改成功'})
      })
    } else {
      updateNode({ data: {
        id: roomInfo.id,
        name: val,
        type: 'roomNo',
      }}).then(() => {
        const room = {
          ...roomInfo,
          name: val
        }

        if (props.onEdit) {
          props.onEdit(room)
        }
        notification.success({message: '修改成功'})
      })
    }
    setHouseVisible(false)
  }

  const menu = (
    <Menu>
      <Menu.Item>
        <Button type="link" onClick={() => setHouseVisible(true)}>编辑</Button>
      </Menu.Item>
      {
        roomInfo.id && (
          <Menu.Item>
            <Popconfirm
             title={`确认删除 ${roomInfo.name} ?`}
             onConfirm={handleDelete}
             okText="是"
             cancelText="否"
            >
              <Button type="danger" ghost style={{border: 'none', boxShadow: 'none'}}>删除</Button>
            </Popconfirm>
          </Menu.Item>
        )
      }
    </Menu>
  );

  useEffect(() => {
    setRoomInfo(props.dataSource || {})
  }, [props.dataSource])

  return (
    <span>
      <Dropdown overlay={menu} trigger={['contextMenu']} placement="topCenter">
        <div style={{cursor: 'pointer'}}>{roomInfo.name}</div>
      </Dropdown>
      <Prompt visible={houseVisible} onOk={handleEdit} onCancel={() => setHouseVisible(false)} placeholder="请填写房室名称" />
    </span>
  )
}
