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

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const listAnnouncement = fetch(apis.announcement.listAnnouncement)
const deleteAnnouncement = fetch(apis.announcement.deleteAnnouncement)
const updateannouncement = fetch(apis.announcement.updateannouncement)

const Condition = props => {
  const [communityId, setCommunityId] = useState()
  
  const handleCommunityChange = v => {
    setCommunityId(v)

    props.onCommunityChange(v)
  }

  return (
    <Search
      onSearch={props.onSearch}
      onReset={props.onReset}
      render={form => {
        const { getFieldDecorator } = form
        
        return (
          <>
            <Form.Item label="小区">
            {
              <CommunitySelect value={communityId} onChange={handleCommunityChange} autoInited />
            }
            </Form.Item>
            <Form.Item label="公告编号">
            {
              getFieldDecorator('announcementNumber')(<Input placeholder="公告编号" />)
            }
            </Form.Item>
            <Form.Item label="公告标题">
            {
              getFieldDecorator('announcementTitle')(<Input placeholder="公告标题" />)
            }
            </Form.Item>
            <Form.Item label="公告类型">
            {
              getFieldDecorator('annType')(
                <Select style={{minWidth: '120px'}}>
                  <Select.Option value="">全部</Select.Option>
                  <Select.Option value="notice">提醒</Select.Option>
                </Select>
              )
            }
            </Form.Item>
            <Form.Item label="状态">
            {
              getFieldDecorator('status')(
                <Select style={{minWidth: '120px'}}>
                  <Select.Option value="">全部</Select.Option>
                  <Select.Option value="0">未发布</Select.Option>
                  <Select.Option value="1">已发布</Select.Option>
                </Select>
              )
            }
            </Form.Item>
            <Form.Item label="创建时间">
            {getFieldDecorator('createTime')(
              <RangePicker placeholder={['开始时间', '结束时间']} />
            )}
          </Form.Item>
          </>
        )
      }}
    />
  )
}

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

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

  const handleSearch = vals => {
    let { createTime, ...submitValue  } = vals
    if (null != createTime && createTime.length > 0) {
      const [startCreateDate, endCreateDate] = createTime
      submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
      submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
    } else {
      submitValue.startCreateDate = null
      submitValue.endCreateDate = null
    }
    setQueryParams({
      ...queryParams,
      ...submitValue,
      pageNum: 1,
    })
  }

  const handleEditRow = row => {
    // 发布改为不发布, 调用删除接口
    if (1 === row.status - 0) {
      deleteAnnouncement({data: {id: [row.id]}}).then(res => {
        notification.success({message: '取消发布成功'})
        setQueryParams({...queryParams})
      })
    } else {
      // 未发布修改为已发布
      updateannouncement({data: {
        ...row,
        status: '1'
      }}).then(res => {
        notification.success({message: '发布成功'})
        setQueryParams({...queryParams})
      })
    }
  }
  const handleTableChange = (pagination, filters, sorter) => {
    console.log(sorter)
    setQueryParams({
      ...queryParams,      
      sortKey: sorter.columnKey,
      sortOrder: sorter.order,
    })
};

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

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

  return (
    <div>
      <Condition onSearch={handleSearch} onReset={handleSearch} onCommunityChange={v => setCommunityId(v)} />
      <div style={{ margin: '24px 0' }}>
        <NavLink to={`/property/notice/edit`}>
          <Button type="primary">添加</Button>
        </NavLink>
      </div>
      <List dataSource={listData} loading={loading} pagination={pagination} onPageChange={handlePageChange} 
      onChange={handleTableChange}
      rowKey="id">
        {/* <Table.Column title="编号" dataIndex="id" key="id" /> */}
        <Table.Column title="类型" dataIndex="annType" key="annType" render={t => t === 'notice' ? '提醒' : null} />
        <Table.Column
          title="标题"
          dataIndex="announcementTitle"
          key="announcementTitle"
          render={(_, row) => {
            return (
              <NavLink to={`/property/notice/edit?id=${row.id}`}>
                <Button type="link">{row.announcementTitle}</Button>
              </NavLink>
            )
          }}
        />
        <Table.Column title="查看数量" dataIndex="viewCount" key="viewCount" />
        <Table.Column
          title="状态"
          dataIndex="status"
          key="status"
          render={(_, row) => StatusDict[row.status]}
          sorter={true}
        />
        <Table.Column title="创建时间" dataIndex="createDate" key="create_date" 
        sorter={true}/>
        {/* <Table.Column title="发布人" dataIndex="createUserName" key="createUserName" />
        <Table.Column title="修改时间" dataIndex="updateDate" key="updateDate" />
        <Table.Column title="修改人" dataIndex="updateDateName" key="updateDateName" /> */}
        <Table.Column
          title="操作"
          key="action"
          render={(_, row) => {
            return (
              <>
                <Popconfirm
                  title="确认进行当前操作?"
                  onConfirm={() => handleEditRow(row)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="link">{row.status === '1' ? '取消发布' : '发布'}</Button>
                </Popconfirm>
                <Divider type="vertical" />
                <NavLink to={`/property/notice/edit?id=${row.id}`}>
                  <Button type="link">编辑</Button>
                </NavLink>
              </>
            )
          }}
        />
      </List>

    </div>
  )
}
