import React, { useState, useEffect } from 'react'
import { Select, Spin, Table, Button, Form, Input, Divider, Modal, Popconfirm, Typography, notification } from 'antd'
import NavLink from 'umi/navlink'
import { fetch, fetchList, apis } from '@/utils/request'
import Search from '../components/Search'
import List from '../components/List'

const getNewsList = fetchList(apis.propNews.getNewsList)
const updateNews = fetch(apis.propNews.updateNews)
const deleteNews = fetch(apis.propNews.deleteNews)

const Condition = props => {
  return (
    <Search
      onSearch={props.onSearch}
      onReset={props.onReset}
      render={form => {
        const { getFieldDecorator } = form
        
        return (
          <>
            <Form.Item label="标题">
            {
              getFieldDecorator('newsName')(<Input placeholder="标题" />)
            }
            </Form.Item>
          </>
        )
      }}
    />
  )
}

const StatusDict = {
  '0': '未发布',
  '1': '已发布',
}

export default props => {
  const [loading, setLoading] = useState(false)
  const [listData, setListData] = useState([])
  const [pagination, setPagination] = useState({})
  const [queryParams, setQueryParams] = useState({ pageNum: 1, pageSize: 10 })

  const handleSearch = vals => {
    setQueryParams({
      ...queryParams,
      ...vals,
      pageNum: 1,
    })
  }

  const handleDeleteRow = row => {
    deleteNews({ urlData: {id: row.newsId} }).then(res => {
      Modal.success({
        content: '删除内容成功',
        onOk: () => {
          // 触发数据刷新
          setQueryParams({...queryParams})
        }
      })
    })
  }

  const handleStatusTrigger = row => {
    // 发布 -> 取消发布
    // 取消发布 -> 发布
    const status = Math.abs(row.status - 1)
    const data = { ...row, status }
    updateNews({data, urlData: {id: row.newsId}}).then(res => {
      notification.success({message: "操作成功"})
      // 触发数据刷新
      setQueryParams({...queryParams})
    })
  }

  const handlePageChange = (pageNum, pageSize) => {
    setQueryParams({
      ...queryParams,      
      pageNum,
      pageSize,
    })
  }

  useEffect(() => {
    setLoading(true)
    getNewsList(queryParams).then(res => {
      const [list, pageInfo] = res || {}
      setListData(list)
      setPagination(pageInfo)
      setLoading(false)
    }).catch(() => setLoading(false))
  }, [queryParams])

  return (
    <div>
      <Condition onSearch={handleSearch} onReset={handleSearch} />
      <div style={{ margin: '24px 0' }}>
        <NavLink to={`/property/news/edit`}>
          <Button type="primary">添加</Button>
        </NavLink>
      </div>
      <List dataSource={listData} loading={loading} pagination={pagination} onPageChange={handlePageChange} rowKey="newsId">
        <Table.Column title="#ID" dataIndex="newsId" key="newsId" />
        <Table.Column
          title="标题"
          dataIndex="newsName"
          key="newsName"
          render={(_, row) => {
            return (
              <NavLink to={`/property/news/edit?id=${row.newsId}`}>
                <Button type="link">{row.newsName}</Button>
              </NavLink>
            )
          }}
        />
        <Table.Column title="封面" dataIndex="newsImg" key="newsImg" render={t => <img src={t} alt="" style={{ width: '96px', height: '96px' }} />} />
        <Table.Column
          title="内容"
          dataIndex="newsDetail"
          key="newsDetail"
          render={t => <Typography.Text ellipsis>{(t||'').replace(/<[^>]*>|/g,"").substring(0, 20)}</Typography.Text>}
        />
        <Table.Column
          title="状态"
          dataIndex="status"
          key="status"
          render={(_, row) => StatusDict[row.status]}
        />
        <Table.Column title="创建时间" dataIndex="createDate" key="createDate" />
        <Table.Column
          title="操作"
          key="action"
          render={(_, row) => {
            return (
              <>
                <Popconfirm
                  title="确认进行删除操作?"
                  onConfirm={() => handleDeleteRow(row)}
                  okText="删除"
                  cancelText="取消"
                >
                  <Button type="link">删除</Button>
                </Popconfirm>
                <Divider type="vertical" />
                <Popconfirm
                  title={`确认进行${row.status === 1? '取消发布' : '发布'}操作`}
                  onConfirm={() => handleStatusTrigger(row)}
                  okText={row.status === 1? '取消发布' : '发布'}
                  cancelText="取消"
                >
                  <Button type="link">{row.status === 1? '取消发布' : '发布'}</Button>
                </Popconfirm>
                <Divider type="vertical" />
                <NavLink to={`/property/news/edit?id=${row.newsId}`}>
                  <Button type="link">编辑</Button>
                </NavLink>
              </>
            )
          }}
        />
      </List>

    </div>
  )
}
