import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, DatePicker } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import styles from '../style/GoodsList.less';
import router from 'umi/router';
import moment from 'moment';
import SelectCity from '../../components/SelectButton/CitySelect'
import BuildSelect from '../../components/SelectButton/BuildSelect'

import request from '../../utils/request'

const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const header = (props) => {
  const [ data, setData ] = useState({})
//   const [page, changePage] = useState({})

  useEffect(() => {
    getList({ pageNum: 1, pageSize: 10 });
  },[])

  // 查询列表
  const getList = (params) => {
    request({
        url: '/api/admin/iBuildingDynamicList',
        method: 'GET',
        params: { ...params },
    }).then((data) => {
        console.log(data)
        setData(data)
    })
  }

  
// 跳转到编辑商品
const toEditGoods = (dynamicId) => () => {
    router.push({
      pathname: '/activity/editActivity',
      query: {
        dynamicId
      },
    });
  }
  
  /**
   *
   *
   * @param {*} props
   * @returns
   */
  
  const columns = [
    {
      title: '活动标题',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
    },
    {
      title: '活动时间',
      dataIndex: 'startDate',
      key: 'startDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.startDate).format('YYYY-MM-DD')} —— ${moment(row.endDate).format('YYYY-MM-DD')}`}</span></>
    },
    {
      title: '已参加人数',
      dataIndex: 'count',
      key: 'count',
      align: 'center',
    },
    {
      title: '阅读量',
      dataIndex: 'pvNum',
      key: 'pvNum',
      align: 'center',
    },
    {
      title: '转发量',
      dataIndex: 'shareNum',
      key: 'shareNum',
      align: 'center',
    },
    {
      title: '收藏数',
      dataIndex: 'saveNum',
      key: 'saveNum',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'isEnlist',
      key: 'isEnlist',
      align: 'center',
      render: (isEnlist)=> <><span>{isEnlist == 0 ?"未开始" : isEnlist==1 ? "进行中" : "已结束"}</span></>
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: (x,row) => <><span style={{ color: '#1990FF'}} onClick={getSignList.bind(this, row.dynamicId)}>{row.isEnlist == '1' || row.isEnlist == '2' ? "报名记录" : ""}<Icon type="snippets" className={styles.shoppingCart} /></span>
                           <span style={{ color: '#1990FF' }} onClick={sendOrPublicDynamic.bind(this,row)}>{ row.status === 1 ? '取消发布' : '发布' }<Icon type="close-circle" className={styles.edit} /></span>
                           <span style={{ color: '#1990FF' }} onClick={finishDynamic.bind(this,row)}>结束活动<Icon type="poweroff" className={styles.edit} /></span>
                           <span style={{ color: '#1990FF', marginRight: '20px' }} onClick={topDynamic(row)}>{ row.weight === 1 ? '取消置顶' : '置顶' }<Icon type="vertical-align-top" className={styles.edit} /></span>
                           <span style={{ color: '#FF925C' }} onClick={toEditGoods(row.dynamicId)}>编辑<Icon type="form" className={styles.edit} /></span>
                         </>
    },
  ];
  
  const getSignList = (dynamicId) => {
      router.push({
          pathname: '/activity/SignList',
          query: {
              dynamicId
          },
        });
  }
  
  const finishDynamic = (row) => {
      Modal.confirm({
          title: '结束以后将无法编辑, 是否继续?',
          okText: '确定',
          cancelText: '取消',
          onOk() {
              request({
                  url: '/api/admin/buildingDynamic/finish',
                  method: 'PUT',
                  data: {dynamicId: row.dynamicId, top: ""},
              }).then((data) => {
                  console.log(data)
                  message.info('操作成功！')
                  getList({ pageNum: 1, pageSize: 10 })
              }).catch((err) => {
                  console.log(err)
                  message.info(err.msg || err.message)
              })
          },
        });
  }
  
//   置顶
  const topDynamic = (row) => () => {
      const weight = Math.abs(row.weight - 1)
      request({
          url: '/api/admin/buildingDynamic/weight',
          method: 'PUT',
          params: {dynamicId: row.dynamicId, weight},
      }).then((data) => {
          console.log(data)
          message.info('操作成功！')
          getList({ pageNum: 1, pageSize: 10 })
      }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
      })
  }
  
  const sendOrPublicDynamic = (row) => {
      if (row.status === 1) {
          cancelDynamic(row)
      } else {
          sendDynamic(row)
      }
  }
  
  // 取消活动
  const cancelDynamic = (row) => {
      request({
          url: '/api/admin/buildingDynamic/cancel/'+row.dynamicId,
          method: 'PUT',
      }).then((data) => {
          message.info('操作成功！')
          getList({ pageNum: 1, pageSize: 10 })
      }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
      })
  }
  
  //发布活动
  const sendDynamic = (row) => {
      request({
          url: '/api/admin/buildingDynamic/send/'+row.dynamicId,
          method: 'PUT',
      }).then((data) => {
          message.info('操作成功！')
          getList({ pageNum: 1, pageSize: 10 });
      }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
      })
  }
  
  const changePageNum = (pageNumber) => {
      getList({ pageNum: pageNumber, pageSize: 10 })
  }

  // 提交事件
const handleSubmit = (e, props) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log('提交数据: ', values)
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

  const { getFieldDecorator } = props.form
  return (

    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('cityId')(
            <SelectCity />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('buildingId')(
            <BuildSelect />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('title')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="请输入标题"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('time')(
            <DatePicker />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('isEnlist')(
            <Select style={{ width: '180px' }} placeholder="是否报名">
              <Option value="1">已报名</Option>
              <Option value="0">未报名</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className={styles.searchBtn}>
            搜索
          </Button>
        </Form.Item>
      </Form>
      <Button type="danger" className={styles.addBtn} onClick={toEditGoods()}>新增</Button>
      <Table dataSource={data.list} columns={columns} pagination={false}/>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} />
      </div>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
