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

import request from '@/utils/request';
import apis from '@/services/apis';

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.getTrendList,

      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: 10 });
  }, []);

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

  const onSuccess = () => {
    setVisible({visible:false})
    getList({ pageNum: 1, pageSize: 10 });
  };

  function onDelete(record) {
    request({ ...apis.building.deleteTrend, urlData: { id: record.trendId } })
      .then(res => {
        notification.success({ message: '删除成功' });
        getList();
      })
      .catch(err => {
        notification.error({
          message: err.message,
        });
      });
  }

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

  

  return (
    <div>
      <div>
        <AuthButton name="building.dynamic.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>
  );
};
