import React, { useEffect, useState } from 'react'
import { PageHeader, Button, Icon, Table, Spin, notification } from 'antd'
import router from 'umi/router'
import { fetchList, apis } from '@/utils/request'

const getData = fetchList(apis.system.personLevel.list)

const DataTable = (props) => {
  const handleDetail = (row) => () => {
    props.onDetail(row)
  }

  const columns = [
    {
      title: '等级',
      dataIndex: 'levelId',
      key: 'levelId',
    },
    {
      title: '名称',
      dataIndex: 'levelName',
      key: 'levelName',
    },
    {
      title: '图标',
      dataIndex: 'levelIcon',
      key: 'levelIcon',
      render: imgURL => (
        <span>
          {imgURL && <img src={imgURL} width={16} height={16} />}
        </span>
      )
    },
    {
      title: '积分规则',
      dataIndex: 'pointRule',
      key: 'pointRule',
      render: pointRule => pointRule && (
        <span>{pointRule.replace(',', '--')}</span>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button type="link" onClick={handleDetail(record)}><Icon type="edit" /> 详情</Button>
        </span>
      ),
    },
  ];

  const pagination = {
    ...props.pagination,
    onChange: (page, pageSize) => {
      props.onPageChange(page, pageSize)
    }
  }

  return <Table rowKey="levelId" columns={columns} dataSource={props.dataSource} pagination={pagination} />
}

export default (props) => {
  const defaultPageInfo = { pageNum: 1, pageSize: 10 }
  const [loading, updateLoading] = useState(false)
  const [pageData, updatePageData] = useState({})

  const getList = (params) => {
    updateLoading(true)
    getData(params).then(res => {
      updateLoading(false)
      updatePageData({
        list: res[0],
        pagination: res[1]
      })

      if (!res[1].total) {
        notification.info({ message: '没有查询到数据' })
      }
    }).catch(err => {
      updateLoading(false)
      // do nothing
    })
  }

  const handleAdd = () => {
    router.push('/system/person-level-setting/detail')
  }

  const toDetailPage = (row) => {
    router.push(`/system/person-level-setting/detail?id=${row.levelId}`)
  }

  const handlePageChange = (pageNum, pageSize) => {
    getList({
      pageNum,
      pageSize,
      ...filterParams
    })
  }

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

  return (
    <div>
      <PageHeader
        ghost={false}
        backIcon={false}
        title="用户等级设置"
        extra={[<Button key={1} type="primary" onClick={handleAdd}>新增</Button>]}
      ></PageHeader>
      <div style={{marginTop: '16px'}}>
        <Spin spinning={loading} delay={300} tip="请稍候...">
          <DataTable
            dataSource={pageData.list}
            pagination={pageData.pagination}
            onDetail={toDetailPage}
            onPageChange={handlePageChange}
          />
        </Spin>
      </div>
    </div>
  )
}
