import React, { useEffect, useState } from 'react'
import { Tabs, Spin, Button, Icon, Modal, notification } from 'antd'
import { fetch, fetchList, apis } from '@/utils/request'
import Prompt from '@/components/Prompt'
import BuildingUnit from './BuildingUnit'

const fetchBuildingList = fetch(apis.buildingOwnerInfo.getBuildingList)
const addNode = fetch(apis.buildingOwnerInfo.addNode)
const deleteNode = fetch(apis.buildingOwnerInfo.deleteNode)

export default props => {
  const [loading, setLoading] = useState(false)
  const [buildingVisible, setBuildingVisible] = useState(false)
  const [buildingList, setBuildingList] = useState([])

  const handleAddBuilding = v => {
    addNode({ data: {
      id: props.phase.id,
      name: props.phase.name,
      type: 'building',
      nodeNumber: v,
      communityId: props.community,
    }}).then((res) => {
      notification.success({message: '添加成功'})
      setBuildingList(buildingList.concat(res))
    })
    setBuildingVisible(false)
  }

  const handleDeleteBuilding = building => {
    Modal.confirm({
      title: `确认删除 ${building.name} 数据?`,
      content: '谨慎操作, 数据不可恢复',
      onOk: () => {
        deleteNode({ data: {
          id: building.id,
          name: building.name,
          type: 'unit', // 删除的时候, type 是 unit 。这个接口比较诡异
          nodeNumber: building.name,
        }}).then(() => {
          notification.success({message: '删除成功'})
          setBuildingList(buildingList.filter(x => x.id !== building.id))
        })

      }
    })
  }

  useEffect(() => {
    if (props.phase && props.phase.id) {
      setLoading(true)
      fetchBuildingList({params: {phaseId: props.phase.id}}).then(res => {
        setBuildingList(res)
        setLoading(false)
      }).catch(() => setLoading(false))
    }
  }, [props.phase])

  return (
    <div style={{marginTop: 8}}>
      <Spin spinning={loading}>
        <Tabs
          defaultActiveKey="0"
          type="line"
          tabPosition="left"
          tabBarExtraContent={<Button type="link" onClick={() => setBuildingVisible(true)}><Icon type="plus" />栋</Button>}
        >
        {
          buildingList.map((building, index) => {
            return (
              <Tabs.TabPane
                key={`${index}`}
                tab={<span>{building.name} <Icon type="close" style={{fontSize: '0.8em', color: '#888', marginLeft: 8}} onClick={() => handleDeleteBuilding(building)} /></span>}
              >
                <BuildingUnit building={building} phase={props.phase} community={props.community} />
              </Tabs.TabPane>
            )
          })
        }
        </Tabs>
      </Spin>
      <Prompt visible={buildingVisible} onOk={handleAddBuilding} onCancel={() => setBuildingVisible(false)} placeholder="请填写楼栋名称" />
    </div>
  )
}
