import React, { useEffect, useState, useRef } from 'react'
import { Button, message } from 'antd'
import { fetch, apis } from '@/utils/request'
import AuthButton from '@/components/AuthButton'
import Form from './Form'
import List from './List'

const fetchList = fetch(apis.building.buildingApartment)
const deleteData = fetch(apis.building.buildingApartmentDelete)

export default (props) => {
  const { history } = props;
  const { query } = history.location;
  const { id } = query;

  const [visible, setVisible] = useState(false)
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const apartmentRef = useRef()

  const getList = () => {
    const urlData = { id }
    const params = { apartmentType: 'apart' }

    setLoading(true)
    fetchList({ urlData, params }).then((res) => {
      setList(res || [])
      setLoading(false)
    }).catch((err) => {
      console.error(err.message || err)
      setLoading(false)
    })
  }

  const handleEdit = (record) => {
    apartmentRef.current = record
    setVisible(true)
  }

  const handleDelete = (record) => {
    const urlData = { id: record.apartmentId }

    setLoading(true)
    deleteData({ urlData }).then(() => {
      getList()
      message.success('删除成功')
      setLoading(false)
    }).catch((err) => {
      console.error(err.message || err)
      setLoading(false)
    })
  }

  const handleSuccess = () => {
    getList()
    setVisible(false)
  }

  useEffect(() => {
    getList()
  }, [id])

  return (
    <div>
      <div>
        <AuthButton name="building.houseType.add">
          <Button type="primary" onClick={() => handleEdit()}>新增户型</Button>
        </AuthButton>
      </div>
      <Form buildingId={id} visible={visible} onCancel={() => setVisible(false)} formData={apartmentRef.current} onSuccess={handleSuccess} />
      <List loading={loading} dataSource={list} onEdit={handleEdit} onDelete={handleDelete} />
    </div>
  )
}
