import React, { useState, useEffect } from 'react';
import { Button, Table, Pagination, Alert, Icon, Tag } from 'antd'
import router from 'umi/router';
import moment from 'moment';
import Styles from './style.less'
import request from '../../../utils/request';
import apis from '../../../services/apis';

function body() {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [data, setData] = useState([{ records: [] }])

  const columns = [
    {
      title: '编号',
      dataIndex: 'buildingTypeId',
      key: 'buildingTypeId',
    },
    {
      title: '类型名称',
      dataIndex: 'buildingTypeName',
      key: 'buildingTypeName',
      render: (_, record) => <Tag color="blue" onClick={() => toEdi(record.buildingTypeId)}>{ record.buildingTypeName }</Tag>,
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      render: (_, record) => <sapn>{moment(record.createDate).format('YYYY-MM-DD')}</sapn>,
    },
    {
      title: '操作',
      dataIndex: 'row',
      key: 'row',
      render: (_, record) => (
        <span onClick={() => deleteType(record)}>
          <span style={{
              color: '#FF4A4A', right: '0',
          }} >
              删除
          <Icon type="rest" style={{ color: '#C0C4CC', marginLeft: '8px' }} />
          </span>
        </span>
      ),
    },
  ];

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    getList({ pageNum: 1, pageSize: 10 })
  }, [])

  function getList(params) {
    request({ ...apis.buildingType.getList, params: { ...params } }).then(res => {
      setData(res)
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={err}
        type="error"
        showIcon
      />
    })
  }

  // 分页
  function onChange(pageNumber) {
    // eslint-disable-next-line no-console
    console.log('Page: ', pageNumber);
    getList({ pageNum: pageNumber, pageSize: 10 })
  }

  // 删除
  function deleteType(row) {
    const { url, method } = apis.buildingType.update
    const tempUrl = url.substring(0, url.lastIndexOf('id')).concat(row.buildingTypeId)

    row.status = -1
    request({ url: tempUrl, method, data: { ...row } }).then(() => {
      getList({ pageNum: data.current, pageSize: 10 })
    })
  }

  // 跳转修改页
  function toEdi(currentId) {
    router.push({
      pathname: '/building/type/edi',
      query: {
        id: currentId || '',
      },
    });
  }

  return (
    <>
      <Button type="danger" onClick={() => toEdi()}>新增类型</Button>
      <Table style={{marginTop:'30px'}} dataSource={data.records} columns={columns} pagination={false}/>
      {/* 分页 */}
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={onChange} />
      </div>
    </>
  )
}

export default body
