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

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

const header = props => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [data, setData] = useState({ list: [], total: 0 })
  //   const [page, changePage] = useState({})
  const [time, setTime] = useState('')

  // 查询列表
  const getList = params => {
    request({ ...apis.activity.list, params: { ...params } }).then(data => {
      console.log(data)
      setData(data)
    })
  }

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {

    if (localStorage.getItem("activePageParams")) {

      const localStorageValue = JSON.parse(localStorage.getItem("activePageParams"))
      localStorageValue.time = localStorageValue.time ? moment(localStorageValue.time) : ''

      props.form.setFieldsValue(localStorageValue);
      getList(JSON.parse(localStorage.getItem("activePageParams")))
    } else {
      localStorage.setItem("activePageParams", JSON.stringify({ pageNum: 1, pageSize: 10 }));
      getList({ pageNum: 1, pageSize: 10 });
    }
  }, [])

  // 跳转到编辑商品
  const toEditGoods = dynamicId => () => {
    router.push({
      pathname: '/activity/editActivity',
      query: {
        dynamicId,
      },
    });
  }

  const newQrcode = row => {
    const x = new XMLHttpRequest();
    const resourceUrl = row.qrCode
    x.open('GET', resourceUrl, true);
    x.responseType = 'blob';
    x.onload = function (e) {
      const url = window.URL.createObjectURL(x.response)
      const a = document.createElement('a');
      a.href = url;
      a.style.display = 'none'
      a.download = '活动二维码.png';
      a.click();
    }
    x.send();
  }

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

  const getJoinPeople = (dynamicId) => () => {
    router.push({
      pathname: '/activity/SignList',
      query: {
        dynamicId,
      },
    });
  }

  const toDataReacord = (id) => () => {
    router.push({
      pathname: '/activity/activityRecord',
      query: {

        id,
      },
    });
  }

  /**
   *
   *
   * @param {*} props
   * @returns
   */
  const columns = [
    {
      title: '活动标题',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      // width: '15%',
      render: (x, row) => <Navigate onClick={getActivityDetail(row.dynamicId)}><Typography.Text ellipsis>{row.title}</Typography.Text></Navigate>,
    },
    {
      title: '活动时间',
      dataIndex: 'startDate',
      key: 'startDate',
      align: 'center',
      // width: '15%',
      // width: '20%',
      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',
      render: (x, row) => <Navigate onClick={getJoinPeople(row.dynamicId)}>{row.count}</Navigate>,
    },
    // {
    //   title: '阅读量',
    //   dataIndex: 'pvNum',
    //   key: 'pvNum',
    //   align: 'center',
    //   // width: '10%',
    // },
    // {
    //   title: '转发量',
    //   dataIndex: 'shareNum',
    //   key: 'shareNum',
    //   align: 'center',
    //   // width: '10%',
    // },
    // {
    //   title: '收藏数',
    //   dataIndex: 'saveNum',
    //   key: 'saveNum',
    //   align: 'center',
    //   // width: '10%',
    // },
    {
      title: '报名状态',
      dataIndex: 'activityStatus',
      key: 'activityStatus',
      align: 'center',
      render: activityStatus => (activityStatus == 0 ? '进行中' : activityStatus == 1 ? '未开始' : '已结束'),
    },
    {
      title: '权重',
      dataIndex: 'heavy',
      key: 'heavy',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: withActions((x, row) => [
        <AuthButton name="admin.buildingDynamic.send.dynamicId.put" noRight={null}>
          <EditIcon type={row.status === 1 ? 'cancel' : 'publish'} text={row.status === 1 ? '取消发布' : '发布'} onClick={sendOrPublicDynamic.bind(this, row)} />
        </AuthButton>,

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

        row.activityStatus === 0 ?
          <AuthButton name="admin.buildingDynamic.finish.put" noRight={null}>
            <EditIcon type="end" text="结束活动" onClick={finishDynamic.bind(this, row)} />
          </AuthButton> : null,

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

        <EditIcon type={row.home === 1 ? 'cancel' : 'top'} text={row.home === 1 ? '取消推首页' : '推荐首页'} onClick={homeDynamic(row)} />,

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

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

  const getSignList = dynamicId => {
    router.push({
      pathname: '/activity/SignList',
      query: {
        dynamicId,
      },
    });
  }

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

  //   置顶
  const topDynamic = row => () => {
    const weight = Math.abs(row.weight - 1)
    request({ ...apis.activity.weight, params: { dynamicId: row.dynamicId, weight } }).then(data => {
      console.log(data)
      message.info('操作成功！')
      getList(JSON.parse(localStorage.getItem("activePageParams")))
    }).catch(err => {
      console.log(err)
      message.info(err.msg || err.message)
    })
  }

  //   推首页
  const homeDynamic = row => () => {
    const home = Math.abs(row.home - 1)
    request({ ...apis.activity.home, params: { dynamicId: row.dynamicId, home } }).then(data => {
      console.log(data)
      message.info('操作成功！')
      getList(JSON.parse(localStorage.getItem("activePageParams")))
    }).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.activity.cancel, urlData: { id: row.dynamicId } }).then(data => {
          message.info('操作成功！')
          getList(JSON.parse(localStorage.getItem("activePageParams")))

        }).catch(err => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      }
    });
  }

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

  const changePageNum = pageNumber => {
    props.form.validateFields((err, values) => {
      if (!err) {
        localStorage.setItem("activePageParams", JSON.stringify({ pageNum: pageNumber, pageSize: 10, ...values }));
        // eslint-disable-next-line react-hooks/rules-of-hooks
        getList({ pageNum: pageNumber, pageSize: 10, ...values })
      }
    });

  }

  // 提交事件
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log('提交数据: ', values)
        if (time) {
          values.time = `${moment(time).format('YYYY-MM-DDT00:00:00.000')}Z`
        } else {
          values.time = null
        }
        localStorage.setItem("activePageParams", (JSON.stringify({ pageNum: 1, pageSize: 10, ...values })));
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

  // 重置搜索
  function handleReset() {
    props.form.resetFields();
    setTime('')
    props.form.resetFields();
    localStorage.setItem("activePageParams", JSON.stringify({ pageNum: 1, pageSize: 10 }));
    getList({ pageNum: 1, pageSize: 10 })
  }

  // 时间回调
  function timeOnChange(date, dateString) {
    console.log(date, dateString)
    setTime(date)
  }


  const { getFieldDecorator } = props.form
  return (

    <>
      {/* style={{ display: 'none' }} */}
      <div id="qrcode"></div>
      <Form layout="inline" onSubmit={e => handleSubmit(e)}>
        {/* <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 onChange={timeOnChange} />,
          )}
        </Form.Item>
        <Form.Item>
          <AuthButton name="admin.buildingDynamic.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.buildingDynamic.add.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={toEditGoods()}>新增</Button>
      </AuthButton>
      <Table
        // onRow={record => {
        //   return {
        //     onClick: getActivityDetail(record.dynamicId),
        //   };
        // }}
        dataSource={data.list} columns={columns} pagination={false} rowKey="dynamicId" />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={e => changePageNum(e)} current={data.current} />
      </div>
      <Prompt message={location =>
        location.pathname.startsWith("/activity/ActivityList")
          ? true
          : location.pathname.startsWith("/activity/detailActivity") ? true : localStorage.removeItem("activePageParams")} />
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);
// ||"/activity/detailActivity"
export default WrappedHeader
