import React, { Component, useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Table, Avatar, Radio, Modal, Descriptions } from 'antd';
import moment from 'moment';
import EChart from '../../../../components/EchartsTest/EChart';
import NewUsers from './NewUsers'
import style from './style.less';
import request from '../../../../utils/request';
import apis from '../../../../services/apis';
import router from 'umi/router';
import AuthButton from '@/components/AuthButton';
import BuildingSelect from '@/components/SelectButton/BuildSelect';
import Navigate from '@/components/Navigate';


const { RangePicker } = DatePicker;
const { Option } = Select

const formItemLayout = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
};

let daterange = []
let tableTitle = ['类型']
let dateType = ''

const toSharePersonNum = rowData => () => {
  const startDate = moment().subtract(dateType, 'day').toDate()
  const endDate = new Date()

  if (rowData) {
    router.push({
      pathname: '/statistical/activity/sharePersonNum',
      query: {
        startDate: startDate,
        endDate: endDate,
        activityId: rowData.activityId,
        activityType: rowData.activityType,
        activityName: rowData.activityName
      },
    });
    return
  }
}

const toShareNum = rowData => () => {
  const startDate = moment().subtract(dateType, 'day').toDate()
  const endDate = new Date()
  if (rowData) {
    router.push({
      pathname: '/statistical/activity/shareNum',
      query: {
        startDate: startDate,
        endDate: endDate,
        activityId: rowData.activityId,
        activityType: rowData.activityType,
        activityName: rowData.activityName
      },
    });
    return
  }
}

const toAddRegistNum = rowData => () => {
  const startDate = moment().subtract(dateType, 'day').toDate()
  const endDate = new Date()
  console.log(rowData, 'rowData')
  if (rowData) {
    router.push({
      pathname: '/statistical/activity/addRegistNum',
      query: {
        startDate: startDate,
        endDate: endDate,
        activityId: rowData.activityId,
        activityType: rowData.activityType,
        activityName: rowData.activityName
      },
    });
    return
  }
}

const toAddVisitNum = rowData => () => {
  const startDate = moment().subtract(dateType, 'day').toDate()
  const endDate = new Date()
  console.log(rowData, 'rowData')
  if (rowData) {
    router.push({
      pathname: '/statistical/activity/visitNum',
      query: {
        startDate: startDate,
        endDate: endDate,
        activityId: rowData.activityId,
        activityType: rowData.activityType,
        activityName: rowData.activityName
      },
    });
    return
  }
}

const toAddVisitPersonNum = rowData => () => {
  const startDate = moment().subtract(dateType, 'day').toDate()
  const endDate = new Date()
  if (rowData) {
    router.push({
      pathname: '/statistical/activity/visitPersonNum',
      query: {
        startDate: startDate,
        endDate: endDate,
        activityId: rowData.activityId,
        activityType: rowData.activityType,
        activityName: rowData.activityName
      },
    });
    return
  }
}

const toDetail = rowData => {
  const startDate = moment().subtract(dateType, 'day').format('YYYY-MM-DD')
  const endDate = moment().format('YYYY-MM-DD')
  // const { formData } = this.state
  if (rowData) {
    router.push({
      pathname: '/statistical/activity/detail',
      query: {
        startDate: startDate,
        endDate: endDate,
        targetId: rowData.activityId,
        targetType: rowData.activityType,
        targetName: rowData.activityName,
        buildingId: '',
      },
    });

    return
  }
}

let columns = [
  {
    title: '活动类型',
    dataIndex: 'activityType',
    key: 'activityType',
    render: (text, records) => {
      if (records.activityType === 'h5') { return 'H5活动' }
      if (records.activityType === 'live') { return '直播活动' }
      if (records.activityType === 'group') { return '拼团活动' }
      if (records.activityType === 'help') { return '助力活动' }
      if (records.activityType === 'activity') { return '报名活动' }
    },
  },
  {
    title: '活动名称',
    dataIndex: 'activityName',
    key: 'activityName',
  },
  {
    title: '访问人数',
    dataIndex: 'visitPersonNum',
    key: 'visitPersonNum',
    sorter: true,
    render: (text, record) => (
      <Navigate onClick={toAddVisitPersonNum(record)}>{record.visitPersonNum}</Navigate>
      // <a style={{ color: '#66B3FF' }} onClick={toAddVisitPersonNum(record)}><span>{record.visitPersonNum}</span></a>
    ),
  },
  {
    title: '访问次数',
    dataIndex: 'visitNum',
    key: 'visitNum',
    sorter: true,
    render: (text, record) => (
      <Navigate onClick={toAddVisitNum(record)}>{record.visitNum}</Navigate>
      // <a style={{ color: '#66B3FF' }} onClick={toAddVisitNum(record)}><span>{record.visitNum}</span></a>
    ),
  },
  {
    title: '新增注册用户',
    dataIndex: 'addRegistNum',
    key: 'addRegistNum',
    sorter: true,
    render: (text, record) => (
      <Navigate onClick={toAddRegistNum(record)}>{record.addRegistNum}</Navigate>
      // <a style={{ color: '#66B3FF' }} onClick={toAddRegistNum(record)}><span>{record.addRegistNum}</span></a>
    ),
  },
  {
    title: '分享人数',
    dataIndex: 'sharePersonNum',
    key: 'sharePersonNum',
    sorter: true,
    render: (text, record) => (
      <Navigate onClick={toSharePersonNum(record)}>{record.sharePersonNum}</Navigate>
      // <a style={{ color: '#66B3FF' }} onClick={toSharePersonNum(record)}><span>{record.sharePersonNum}</span></a>
    ),
  },
  {
    title: '分享次数',
    dataIndex: 'shareNum',
    key: 'shareNum',
    sorter: true,
    render: (text, record) => (
      <Navigate onClick={toShareNum(record)}>{record.shareNum}</Navigate>
      // <a style={{ color: '#66B3FF' }} onClick={toShareNum(record)}><span>{record.shareNum}</span></a>
    ),
  },
  {
    title: '详情',
    align: 'center',
    render: (text, record) => (
      <a style={{ color: '#FF4A4A' }} onClick={() => toDetail(record)}>查看</a>
    ),
  },
]


function getDayBegin(dt) {
  return moment(dt, 'day').hours(0).minutes(0).seconds(0).milliseconds(0).format('YYYY-MM-DDTHH:mm:ss') + '.000Z';
}


function getDayEnd(dt) {
  return moment(dt, 'day').hours(23).minutes(59).seconds(59).milliseconds(999).format('YYYY-MM-DDTHH:mm:ss') + '.999Z';
}


class OverView extends React.Component {

  constructor(props) {
    super(props)

    const defaultDays = 6
    dateType = defaultDays
    console.log(dateType)
    this.state = {
      radioVal: defaultDays,
      formData: {

        startDate: moment().subtract(6, 'day').toDate(),
        endDate: new Date,
        buildingId: '',
        targetType: '',
        pageNum: '',
        pageSize: '',
        activityName: '',
        sort: null,
        colKey: null
      },
      personData: [],
      dataSoures: [],
      tableData: [],
      barData: {},
      userType: 'all',
      endDate: '',
      startDate: '',
      buildingId: [],
      targetType: []
    }
  }

  componentDidMount() {
    this.getTableList()
  }

  getFormatedParams = (params) => {
    return {
      ...params,
      startDate: getDayBegin(params.startDate),
      endDate: getDayEnd(params.endDate),
    }
  }

  getTableList() {
    const { formData } = this.state

    request({
      ...apis.activityDataStatis.activityDetailTableData,
      params: this.getFormatedParams(formData),
    }).then(data => {
      console.log(data)
      this.setState({ tableData: data.records, total: data.total })
    }).catch()
  }


  onChangetime = (_dates, dateStrings) => {
    daterange[1] = dateStrings[1]
    daterange[0] = dateStrings[0]
  }

  handleSubmit = (e, props) => {
    let startDate = null
    let endDate = null
    const buildingId = this.props.form.getFieldValue("buildingId");
    const targetType = this.props.form.getFieldValue("targetType");
    const activityName = this.props.form.getFieldValue("activityName");
    if (this.props.form.getFieldValue("startDate") != undefined) {
      startDate = this.props.form.getFieldValue("startDate").toDate()
    }
    if (this.props.form.getFieldValue("endDate") != undefined) {
      endDate = this.props.form.getFieldValue("endDate").toDate()
    }
    const { formData } = this.state
    this.setState({
      formData: {
        ...formData,
        startDate: startDate,
        endDate: endDate,
        buildingId: buildingId,
        targetType: targetType,
        activityName: activityName,
        pageNum: 1,
        pageSize: 999
      }
    }, this.getTableList)
  }

  //重置搜索
  handleReset = e => {
    this.props.form.resetFields()
    const defaultDays = 6
    dateType = defaultDays
    console.log(dateType)
    this.setState({
      radioVal: defaultDays,
      formData: {

        startDate: moment().subtract(6, 'day').toDate(),
        endDate: new Date,
        buildingId: '',
        targetType: '',
        pageNum: '',
        pageSize: '',
        activityName: '',
        sort: null,
        colKey: null
      },
      personData: [],
      dataSoures: [],
      tableData: [],
      barData: {},
      userType: 'all',
      endDate: '',
      startDate: '',
      buildingId: [],
      targetType: []
    }, this.getTableList)
  }

  exportActivityStats = () => {
    const { formData } = this.state
    request({ ...apis.activityDataStatis.activityDetailTableDataExport, params: this.getFormatedParams(formData) }).then(data => {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', '活动统计.xlsx')
      document.body.append(link)
      link.click()
    }).catch()
  }

  //排序
  handleTableChange = (pagination, filters, sorter) => {
    console.log(pagination, filters, sorter)
    const { formData } = this.state
    this.setState({
      formData: {
        ...formData,
        startDate: formData.startDate,
        endDate: formData.endDate,
        buildingId: formData.buildingId,
        targetType: formData.targetType,
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        sort: sorter.order,
        colKey: sorter.columnKey
      }
    }, this.getTableList)
  };

  handleRadioChange = (e) => {
    const { formData } = this.state
    const val = e.target.value;
    dateType = val;
    this.setState({
      radioVal: val - 0,
      formData: {
        ...formData,
        startDate: moment().subtract(val, 'day').toDate(),
        endDate: new Date,
      }
    }, this.getTableList)
  }


  render() {
    const { radioVal } = this.state
    const { getFieldDecorator } = this.props.form;
    console.log(this.state.formData, 'this.state.formData')
    const startDate = this.state.formData.startDate
    const endDate = this.state.formData.endDate

    return (
      <>
        <div >
          <Radio.Group buttonStyle="solid" value={radioVal} onChange={this.handleRadioChange}>
            <Radio.Button value={0}>今日</Radio.Button>
            <Radio.Button value={6}>最近7天</Radio.Button>
            <Radio.Button value={30}>最近1月</Radio.Button>
          </Radio.Group>
          <Form layout="inline" onSubmit={e => this.handleSubmit(e, this.props)}>
            <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
              {getFieldDecorator('startDate', {
                initialValue: moment(startDate)

              })(
                <DatePicker allowClear={false} placeholder="开始日期" />,
              )}
            </Form.Item>
            <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
              {getFieldDecorator('endDate', {
                initialValue: moment(endDate)

              })(
                <DatePicker allowClear={false} placeholder="结束日期" />,
              )}
            </Form.Item>
            <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
              {getFieldDecorator('buildingId')(<BuildingSelect />)}
            </Form.Item>
            <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
              {getFieldDecorator('targetType')(
                <Select placeholder="活动类型" style={{ width: 150, marginLeft: '20px' }}>
                  <Option value="activity">报名活动</Option>
                  <Option value="help">助力活动</Option>
                  <Option value="group">拼团活动</Option>
                  <Option value="h5">H5活动</Option>
                  <Option value="live">直播</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
              {getFieldDecorator('activityName')(<Input placeholder="请输入活动名称" />)}
            </Form.Item>
            <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
              <Button type="primary" htmlType="submit" style={{ marginLeft: '30px' }}>
                搜索
            </Button>
              <Button onClick={e => this.handleReset()} style={{ marginLeft: '30px' }}>重置</Button>
            </Form.Item>
          </Form>
          <div>
            <AuthButton name="admin.statistical.activity.export" noRight={null}>
              <Button type="primary" style={{ float: 'right', margin: '20px 0', zIndex: 1 }} onClick={this.exportActivityStats}>
                导出
            </Button>
            </AuthButton>
            <Table style={{ marginTop: '20px' }} dataSource={this.state.tableData} columns={columns} pagination={{ total: this.state.total }} onChange={this.handleTableChange} scroll={{ y: 500 }}></Table>
          </div>
        </div>
      </>
    )

  }
}
const WrappedTypeForm = Form.create()(OverView);
export default WrappedTypeForm
