import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Pagination, Typography, Modal, DatePicker } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import AuthButton from '@/components/AuthButton';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import Navigate from '@/components/Navigate';
import Prompt from 'umi/prompt';
import SelectCity from '../../../components/SelectButton/CitySelect'
import BuildSelect from '../../../components/SelectButton/BuildSelect'
import apis from '../../../services/apis';
import request from '../../../utils/request';
import styles from '../../style/GoodsList.less';

const { Option } = Select;

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

  useEffect(() => {
    if (localStorage.getItem("helpActivePageParams")) {
      // props.form.setFieldsValue(JSON.parse(localStorage.getItem("helpActivePageParams")));
      // const { getFieldDecorator } = JSON.parse(localStorage.getItem("pageParams"))
      const localStorageValue = JSON.parse(localStorage.getItem("helpActivePageParams"))
      localStorageValue.startTime = localStorageValue.startTime ? moment(localStorageValue.startTime) : ''
      localStorageValue.endTime = localStorageValue.endTime ? moment(localStorageValue.endTime) : ''

      props.form.setFieldsValue(localStorageValue);
      getList(JSON.parse(localStorage.getItem("helpActivePageParams")))
    } else {
      localStorage.setItem("helpActivePageParams", JSON.stringify({ pageNum: 1, pageSize: 10 }));
      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
      },
    });
  }

  const getActivityDetail = (helpActivityId) => () => {
    router.push({
      pathname: '/activity/helpActivity/detailActivity',
      query: {
        helpActivityId,
      },
    });
  }

  const getJoinPeople = (helpActivityId) => () => {
    router.push({
      pathname: '/activity/helpActivity/helpRecord',
      query: {
        helpActivityId,
      },
    });
  }


  /**
   *
   *
   * @param {*} props
   * @returns
   */

  const columns = [
    {
      title: '活动标题',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      render: (x, row) => <Navigate onClick={getActivityDetail(row.helpActivityId)}><Typography.Text ellipsis>{row.title}</Typography.Text></Navigate>,
    },
    {
      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',
      render: (x, row) => <><div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', width: '201px', title: 'content' }}>
        <Navigate onClick={getJoinPeople(row.helpActivityId)}>{row.enlistNum}</Navigate>
      </div></>,
    },
    {
      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: 'heavy',
      key: 'heavy',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: withActions((x, row) => [
        <AuthButton name="admin.help.publish" noRight={null}>
          <EditIcon type={row.status === 1 ? 'cancel' : 'publish'} text={row.status === 1 ? '取消发布' : '发布'} onClick={sendOrPublicDynamic.bind(this, row)} />
        </AuthButton>,

        row.activityStatus === 0 ?
          <AuthButton name="admin.help.finish" noRight={null}>
            <EditIcon type="end" text="结束活动" onClick={topDynamic(row, 2)} />
          </AuthButton> : null,

        <EditIcon type="look" text="查看详情" onClick={getActivityDetail(row.helpActivityId)} />,

        <AuthButton name="admin.help.tag" noRight={null}>
          <EditIcon type={row.weight === 1 ? 'cancel' : 'add'} text={row.weight === 1 ? '取消标签' : '添加标签'} onClick={topDynamic(row, 0)} />
        </AuthButton>,

        <AuthButton name="admin.help.top" noRight={null}>
          <EditIcon type={row.isMain ? 'cancel' : 'top'} text={row.isMain ? '取消推首页' : '推荐首页'} onClick={topDynamic(row, 1)} />
        </AuthButton>,

        <AuthButton name="admin.helpActivity.dataRecord" noRight={null}>
          <EditIcon type="record" text="数据记录" onClick={() => toDataReacord(row.helpActivityId)} />
        </AuthButton>,

        (row.activityStatus === 1 || row.activityStatus === 0) ?
          <AuthButton name="admin.helpActivity.update.put" noRight={null}>
            <EditIcon type="edit" text="编辑" onClick={toEditGoods(row.helpActivityId)} />
          </AuthButton> : null,
      ]),
    },
  ];

  const toDataReacord = id => {
    router.push({
      pathname: '/activity/helpActivity/helpActivityRecord',
      query: {
        id,
      },
    });
  }

  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(JSON.parse(localStorage.getItem("helpActivePageParams")))
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      },
    });
  }

  //   置顶
  const topDynamic = (row, code) => () => {
    const title = code === 2 ? '活动会被强制结束，小程序端无法再发起或参与此拼团，如果不想让客户看到活动，请再点击取消发布按钮' : '是否进行该操作'

    Modal.confirm({
      title: title,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request({ ...apis.helpActivity.top, data: { helpActivityId: row.helpActivityId, status: code } }).then((data) => {
          console.log(data)
          message.info('操作成功！')
          getList(JSON.parse(localStorage.getItem("helpActivePageParams")))
        }).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) => {
    Modal.confirm({
      title: '活动会在小程序端隐藏，后台可以继续编辑重新发布',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        request({ ...apis.helpActivity.cancel, urlData: { id: row.helpActivityId } }).then((data) => {
          message.info('操作成功！')
          getList(JSON.parse(localStorage.getItem("helpActivePageParams")))
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      }
    });
  }

  //发布活动
  const sendDynamic = (row) => {
    Modal.confirm({
      title: '确定发布吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        request({ ...apis.helpActivity.send, urlData: { id: row.helpActivityId } }).then((data) => {
          message.info('操作成功！')
          getList(JSON.parse(localStorage.getItem("helpActivePageParams")))
        }).catch(err => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      }
    });
  }

  const changePageNum = pageNumber => {
    localStorage.setItem("helpActivePageParams", JSON.stringify({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() }));
    getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
  }

  // 提交事件
  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)
        localStorage.setItem("helpActivePageParams", JSON.stringify({ pageNum: 1, pageSize: 10, ...values, endDate, startDate }));

        getList({ pageNum: 1, pageSize: 10, ...values, endDate, startDate })
      }
    });
  }
  // 重置搜索
  function handleReset() {
    props.form.resetFields();
    localStorage.setItem("helpActivePageParams", JSON.stringify({ pageNum: 1, pageSize: 10 }));
    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>
          <AuthButton name="admin.help.search" noRight={null}>
            <Button type="primary" htmlType="submit" className={styles.searchBtn}>
              搜索
          </Button>
          </AuthButton>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
      <AuthButton name="admin.help.add.post" noRight={null}>
        <Button name="admin.helpActivity.add.post" noRight={null} type="danger" className={styles.addBtn} onClick={toEditGoods()}>新增</Button>
      </AuthButton>
      <Table
        // onRow={record => {
        //   return {
        //     onClick: getActivityDetail(record.helpActivityId),
        //   };
        // }}
        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} current={data.current} />
      </div>
      <Prompt message={location =>
        location.pathname.startsWith("/activity/helpActivity")
          ? true
          : localStorage.removeItem("helpActivePageParams")} />
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
