import React, { useState, useEffect, useRef } from 'react'
import { Select, Spin, Table, Button, Form, Input, Divider, Tag, Modal,Popconfirm } from 'antd'
import { connect } from 'dva';
import NavLink from 'umi/navlink'
import { fetch, apis, fetchList } from '@/utils/request'
import Search from '../../components/Search'
import List from '../../components/List'
import Editor from './Editor'
import Preview from './components/Preview'

const listMessageEvent = fetchList(apis.announcement.messageEvent.list)
const saveMessageEvent = fetch(apis.announcement.messageEvent.save)
const updateMessageEvent = fetch(apis.announcement.messageEvent.update)
const deleteMessageEvent = fetch(apis.announcement.messageEvent.delete)

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

const EvtTypeDict = {
  'birthday': '生日',
  'festival': '节日',
}

const Condition = props => {
  return (
    <Search
      onSearch={props.onSearch}
      onReset={props.onReset}
      render={form => {
        const { getFieldDecorator } = form
        
        return (
          <>
            <Form.Item label="名称">
            {
              getFieldDecorator('name')(<Input placeholder="名称" />)
            }
            </Form.Item>
            <Form.Item label="公告类型">
            {
              getFieldDecorator('evtType')(
                <Select style={{minWidth: '120px'}} allowClear>
                  {
                    Object.entries(EvtTypeDict).map(pair => {
                      const [key, val] = pair
                      return <Select.Option key={key} value={key}>{val}</Select.Option>
                    })
                  }
                </Select>
              )
            }
            </Form.Item>
          </>
        )
      }}
    />
  )
}

export default connect(({user}) => ({user}))(props => {
  const [loading, setLoading] = useState(false)
  const [listData, setListData] = useState([])
  const [pagination, setPagination] = useState({})
  const [queryParams, setQueryParams] = useState({ pageNum: 1, pageSize: 10 })
  const [showEditor, setShowEditor] = useState(false)
  const [showPreview, setShowPreview] = useState(false)
  const currentRow = useRef({})

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

  const handleNameClick = row => {
    currentRow.current = {
      ...row,
      org: props.user.currentUser.orgName
    }
    setShowPreview(true)
  }

  const handleSubmit = data => {
    saveMessageEvent({data}).then(res => {
      Modal.success({
        content: '新增内容成功',
        onOk: () => {
          // 触发数据刷新
          setQueryParams({...queryParams})
          setShowEditor(false)
        }
      })
    })
  }

  const handleEdit = row => {
    const status = Math.abs(row.status - 1)
    const data = {...row, status}
    updateMessageEvent({data, urlData: {id: row.evtId}}).then(res => {
      Modal.success({
        content: '操作成功',
        onOk: () => {
          // 触发数据刷新
          setQueryParams({...queryParams})
        }
      })
    })
  }

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

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

  useEffect(() => {
    setLoading(true)
    listMessageEvent({ data: 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' }}>
        <Button type="primary" onClick={() => setShowEditor(true)}>添加</Button>
      </div>
      <List dataSource={listData} loading={loading} pagination={pagination} onPageChange={handlePageChange} rowKey="evtId">
        <Table.Column title="类型" dataIndex="evtType" key="evtType" render={t => EvtTypeDict[t] || ''} />
        <Table.Column title="名称" dataIndex="name" key="name" render={(t, row) => {
          return <Button type="link" onClick={() => handleNameClick(row)}>{t}</Button>
        }} />
        <Table.Column title="发生日" dataIndex="evtDate" key="evtDate" render={(_, row) => {
          return row.evtDate && (
            <span>
              <Tag color={!row.isSolar ? '#87d068' : '#108ee9'}>{!row.isSolar ? '阴历' : '阳历'}</Tag>
              <span>{row.evtDate}</span>
            </span>
          )
        }} />
        <Table.Column title="祝福语" dataIndex="wishes" key="wishes" />
        <Table.Column title="状态" dataIndex="status" key="status" render={t => StatusDict[t] || ''} />
        <Table.Column title="创建时间" dataIndex="createDate" key="createDate" width="180px" />
        <Table.Column
          title="操作"
          key="action"
          width="200px"
          render={(_, row) => {
            return (
              <>
                {
                  row.evtType !== 'birthday' && (
                    <>
                      <Popconfirm
                        title="确认进行删除操作?"
                        onConfirm={() => handleDeleteRow(row)}
                        okText="删除"
                        cancelText="取消"
                      >
                        <Button type="link">删除</Button>
                      </Popconfirm>
                      <Divider type="vertical" />
                    </>
                  )
                }
                <Button type="link" onClick={() => handleEdit(row)}>{row.status === 1 ? '取消发布' : '发布'}</Button>
              </>
            )
          }}
        />
      </List>
      <Editor visible={showEditor} onCancel={() => setShowEditor(false)} onSubmit={handleSubmit} />
      <Preview visible={showPreview} dataSource={currentRow.current} onOk={() => setShowPreview(false)} onCancel={() => setShowPreview(false)} />
    </div>
  )
})
