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 [roomInfo, setRoomInfo] = useState({})
  const [levelVisible, setLevelVisible] = useState(false)
  const [houseVisible, setHouseVisible] = useState(false)

  const handleEdit = val => {
    updateNode({ data: {
      id: roomInfo.levelId,
      name: val,
      type: 'level',
    }}).then(() => {
      const room = {
        ...roomInfo,
        levelName: val
      }
      if (props.onEdit) {
        props.onEdit(room)
      }
      notification.success({message: '修改成功'})
    })
    setLevelVisible(false)
  }

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

  const handleHouseAdd = val => {
    addNode({ data: {
      id: roomInfo.levelId,
      name: roomInfo.levelName,
      type: 'roomNo',
      nodeNumber: val,
      communityId: props.community,
    }}).then((res) => {
      if (props.onHouseAdd) {
        props.onHouseAdd(res)
      }
      notification.success({message: '添加成功'})
    })
    setHouseVisible(false)
  }

  const menu = (
    <Menu>
      <Menu.Item>
        <Button type="link" onClick={() => setHouseVisible(true)}><Icon type="plus" />房</Button>
      </Menu.Item>
      <Menu.Item>
        <Button type="link" onClick={() => setLevelVisible(true)}>编辑</Button>
      </Menu.Item>
      <Menu.Item>
        <Popconfirm
         title={`确认删除 ${roomInfo.levelName}`}
         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.levelName}</div>
      </Dropdown>
      <Prompt visible={levelVisible} onOk={handleEdit} onCancel={() => setLevelVisible(false)} placeholder="请填写楼层名称" />
      <Prompt visible={houseVisible} onOk={handleHouseAdd} onCancel={() => setHouseVisible(false)} placeholder="请填写房室名称" />
    </span>
  )
}
