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 apis from '../../../services/apis';
import request from '../../../utils/request';
import AuthButton from '@/components/AuthButton';

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({ ...apis.helpActivity.list, params: { ...params } }).then((data) => {
        console.log(data)
        setData(data)
    })
  }

  
// 跳转到助力新增
const toEditGoods = (helpActivityId) => () => {
    router.push({
      pathname: '/activity/helpActivity/edithelpActivity',
      query: {
        helpActivityId
      },
    });
  }
  
  /**
   *
   *
   * @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 HH:mm:ss')} —— ${moment(row.endDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '已参加人数',
      dataIndex: 'enlistNum',
      key: 'enlistNum',
      align: 'center',
    },
    {
      title: '助力成功数',
      dataIndex: 'succeedCount',
      key: 'succeedCount',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'isEnlist',
      key: 'isEnlist',
      align: 'center',
      render: (text, records) => {
        if (records.activityStatus === 1) { return '未开始' }
        if (records.activityStatus === 0) { return '进行中' }
        if (records.activityStatus === 2) { return '已结束' }
      },
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: (x, row) => (
        <>
          {row.activityStatus === 0 &&
          <AuthButton name="admin.SignList.get" noRight={null}>
        
            <span style={{ color: '#1990FF', cursor: 'pointer' }} onClick={ getSignList.bind(this, row.helpActivityId)}>助力记录<Icon type="snippets" className={styles.shoppingCart} /></span>
            <span style={{ color: '#1990FF', cursor: 'pointer' }} onClick={topDynamic(row, 2)}>结束活动<Icon type="poweroff" className={styles.edit} /></span>
            <span style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }} onClick={topDynamic(row, 0)}>{ row.weight === 1 ? '取消置顶' : '置顶' }<Icon type="vertical-align-top" className={styles.edit} /></span>
            <span style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }} onClick={topDynamic(row, 1)}>{ row.isMain === true ? '取消推首页' : '推首页' }<Icon type="vertical-align-top" className={styles.edit} /></span>
          </AuthButton> }

          {row.activityStatus === 1 &&
           <AuthButton name="admin.buildingDynamic.finish.put" noRight={null}>
                      <span style={{ color: '#FF925C', cursor: 'pointer' }} onClick={toEditGoods(row.helpActivityId)}>编辑<Icon type="form" className={styles.edit} /></span>
                      {/* <span style={{ color: '#1990FF', cursor: 'pointer' }} onClick={topDynamic(row, 2)}>结束活动<Icon type="poweroff" className={styles.edit} /></span> */}
            <span style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }} onClick={topDynamic(row, 0)}>{ row.weight === 1 ? '取消置顶' : '置顶' }<Icon type="vertical-align-top" className={styles.edit} /></span>
            <span style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }} onClick={topDynamic(row, 1)}>{ row.isMain === true ? '取消推首页' : '推首页' }<Icon type="vertical-align-top" className={styles.edit} /></span>
            </AuthButton>
          }

          {row.activityStatus === 2 &&
        <AuthButton name="admin.buildingDynamic.finish.put" noRight={null}>
           <span style={{ color: '#1990FF', cursor: 'pointer' }} onClick={ getSignList.bind(this, row.helpActivityId)}>助力记录<Icon type="snippets" className={styles.shoppingCart} /></span>
           <span style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }} onClick={topDynamic(row, 0)}>{ row.weight === 1 ? '取消置顶' : '置顶' }<Icon type="vertical-align-top" className={styles.edit} /></span>
            <span style={{ color: '#1990FF', marginRight: '20px', cursor: 'pointer' }} onClick={topDynamic(row, 1)}>{ row.isMain === true ? '取消推首页' : '推首页' }<Icon type="vertical-align-top" className={styles.edit} /></span>
        </AuthButton>
          }
        </>
      ),
    },
  ];
  const getSignList = helpActivityId => {
      router.push({
          pathname: '/activity/helpActivity/helpRecord',
          query: {
            helpActivityId,
          },
        });
  }
  
  const finishDynamic = (row) => {
      Modal.confirm({
          title: '结束以后将无法编辑, 是否继续?',
          okText: '确定',
          cancelText: '取消',
          onOk() {
              request({ ...apis.activity.finish, 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, code) => () => {
      request({ ...apis.helpActivity.top, data: { helpActivityId: row.helpActivityId, status: code } }).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({ ...apis.activity.cancel, urlData: {id: row.dynamicId}}).then((data) => {
          message.info('操作成功！')
          getList({ pageNum: 1, pageSize: 10 })
      }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
      })
  }
  
  //发布活动
  const sendDynamic = (row) => {
      request({ ...apis.activity.send, urlData: {id: row.dynamicId}}).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) => {
      const startDate = values.startTime === undefined ? null : moment(values.startTime).format('YYYY-MM-DD')
      const endDate = values.endTime === undefined ? null : moment(values.endTime).format('YYYY-MM-DD')
      // 删除时间会传默认值 Invalid date

      if (!err) {
        console.log('提交数据: ', values)
        getList({ pageNum: 1, pageSize: 10, ...values, endDate, startDate })
      }
    });
  }
   // 重置搜索
   function handleReset() {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 10 })
  }


  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('startTime')(
            <DatePicker placeholder="活动开始时间"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('endTime')(
            <DatePicker placeholder="活动结束时间"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('activityStatus')(
            <Select style={{ width: '180px' }} placeholder="活动状态">
              <Option value="1">未开始</Option>
              <Option value="0">进行中</Option>
              <Option value="2">已结束</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className={styles.searchBtn}>
            搜索
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
        </Form.Item>
      </Form>
      <AuthButton name="admin.buildingDynamic.add.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={toEditGoods()}>新增</Button>
      </AuthButton>
      <Table dataSource={data.records} columns={columns} pagination={false} rowKey="activityList"/>
      <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
