import React, { useState, useEffect } from 'react'
import { Button,notification } from 'antd'
import AuthButton from '@/components/AuthButton'
import request from '@/utils/request';
import apis from '@/services/apis';
import Form from './Form'
import List from './List'

export default (props) => {

  const { history } = props;
  const { query } = history.location;
  const { id } = query;

  const [data, setData] = useState({});
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState({visible:false});

  function getList(params) {
    setLoading(true);
    // 网路请求
    request({
      ...apis.building.getSpecialRoomList,

      params: { ...params, buildingId: id },
    })
      .then(res => {
        setLoading(false);
        setData(res);
      })
      .catch(err => {
        setLoading(false);
        notification.error({
          message: err.message,
          description: '',
        });
      });
  }

  useEffect(() => {
    getList({ pageNum: 1, pageSize: 20 });
  }, []);

  const onChangePageNum = pageNumber => {
    getList({ pageNum: pageNumber, pageSize: 20 });
  };

  const onSuccess = () => {
    setVisible({visible:false})
    getList({ pageNum: 1, pageSize: 10 });
  };
  function onDelete(record) {
    request({ ...apis.building.deletebuildingSpecialRoom, urlData: { id: record.specialRoomId } })
      .then(res => {
        notification.success({ message: '删除成功' });
        getList({ pageNum: 1, pageSize: 10 });
      })
      .catch(err => {
        notification.error({
          message: err.message,
        });
      });
  }

  function onEdit(data) {
    setVisible({visible:true,data:data});
  }


  return (
    <div>
      <div>
        <AuthButton name="building.special.add">
          <Button type="primary" onClick={() => setVisible({visible:true})}>新增特价房</Button>
        </AuthButton>
      </div>
      <Form visibleData={visible} buildingId={id} onCancel={() => setVisible({visible:false})} onSuccess={onSuccess}  />
      <List data={data} buildingId={id} loading={loading} onChangePageNum={onChangePageNum} onDelete={onDelete} onEdit={onEdit}/>
    </div>
  )
}
