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 buildingId = ''
let activityType = ''

const toSharePersonNum = rowData => () => {
  console.log(rowData, 'rowData')
  if(rowData) {
    router.push({
    pathname: '/statistical/activity/sharePersonNum',
    query: {
      queryDate: rowData.date,
      buildingId: buildingId, 
      activityType: activityType
    },
  });
    return
  }
}

const toShareNum = rowData => () => {
  console.log(rowData, 'rowData')
  if(rowData) {
    router.push({
    pathname: '/statistical/activity/shareNum',
    query: {
      queryDate: rowData.date,
      buildingId: buildingId, 
      activityType: activityType
    },
  });
    return
  }
} 

const toAddRegistNum = rowData => () => {
  console.log(rowData, 'rowData')
  if(rowData) {
    router.push({
    pathname: '/statistical/activity/addRegistNum',
    query: {
      queryDate: rowData.date,
      buildingId: buildingId, 
      activityType: activityType
    },
  });
    return
  }
} 

const toAddVisitNum = rowData => () => {
  console.log(rowData, 'rowData')
  if(rowData) {
    router.push({
    pathname: '/statistical/activity/visitNum',
    query: {
      queryDate: rowData.date,
      buildingId: buildingId, 
      activityType: activityType
    },
  });
    return
  }
} 

const toAddVisitPersonNum = rowData => () => {
  console.log(rowData, 'rowData')
  if(rowData) {
    router.push({
    pathname: '/statistical/activity/visitPersonNum',
    query: {
      queryDate: rowData.date,
      buildingId: buildingId, 
      activityType: activityType
    },
  });
    return
  }
}


let columns = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
  },
  {
    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>
      ),
  },
]


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

    this.state = {
      radioVal: defaultDays,
      formData: {
        startDate: moment().subtract(6, 'day').toDate(),
        endDate: new Date,
        buildingId: '',
        targetType: '',
        pageNum:'',
        pageSize:'',
        sort:null,
        colKey:null
      },
      personData: [],  
      dataSoures: [],
      tableData: [],
      barData: {},
      userType: 'all',
      endDate: '',
      startDate: '',
      buildingId: [],
      targetType: [],
      helpVisible: false,
    }
  }

  componentDidMount() {
    activityType = ''
    buildingId = ''
    this.getList()
    this.getTableList()
  }

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

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

    request({
      ...apis.activityDataStatis.total,
      params: this.getFormatedParams(formData),
    }).then(res => {
      this.setState({ personData: res })
    }).catch(err => {
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={err}
        type="error"
        showIcon
      />
    })
  }

  getTableList () {
    const { formData } = this.state
    request({ ...apis.activityDataStatis.tableData, 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
    buildingId = this.props.form.getFieldValue("buildingId");
    activityType = this.props.form.getFieldValue("targetType");

    const buildingIdSearch = this.props.form.getFieldValue("buildingId");
    const targetType = this.props.form.getFieldValue("targetType");
    if (this.props.form.getFieldValue("startDate") != undefined){
      startDate = this.props.form.getFieldValue("startDate").toDate()
    }else{
      startDate = moment().subtract(6, 'day').toDate()
    }
    if (this.props.form.getFieldValue("endDate") != undefined){
      endDate = this.props.form.getFieldValue("endDate").toDate()
    }else{
      endDate = new Date
    }
    const { formData } = this.state
    this.setState({
      formData: {
        ...formData,
        startDate: startDate,
        endDate: endDate,
        buildingId: buildingId,
        targetType: activityType,
        pageNum: 1,
        pageSize: 999
      }
    }, this.getAllList)
    this.setState({ startDate: startDate, endDate: endDate, buildingId: this.props.form.getFieldValue("buildingId"), targetType: this.props.form.getFieldValue("targetType") })
  }

  //重置搜索
  handleReset = e => {
    this.props.form.resetFields()
    console.log('handleReset',this.state.formData)
    this.setState( {
      radioVal: 6,
      formData: {
        startDate: moment().subtract(6, 'day').toDate(),
        endDate: new Date,
        buildingId: '',
        targetType: '',
        pageNum:'',
        pageSize:'',
        sort:null,
        colKey:null
      },
      personData: [],  
      dataSoures: [],
      tableData: [],
      barData: {},
      userType: 'all',
      endDate: '',
      startDate: '',
      buildingId: [],
      targetType: [],
      helpVisible: false,
    },this.getAllList)
    
  }

  exportActivityStats = () => {
    const { formData } = this.state
    request({ ...apis.activityDataStatis.tableDataExport, 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.getAllList)
  };

  getAllList(){
    this.getList()
    this.getTableList()
  }

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

  setShowHelp = (e) => {
    this.setState({ ...this.state, helpVisible: e })
  }

  render() {
    const { radioVal } = this.state
    const { getFieldDecorator } = this.props.form;
    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 placeholder="开始日期"/>,
            )}
            </Form.Item>
            <Form.Item style={{marginTop:'20px', marginBottom:'20px'}}>
            {getFieldDecorator('endDate', {
                initialValue: moment(endDate)

              })(
                <DatePicker 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'}}>
            <Button type="primary" htmlType="submit" style={{ marginLeft: '30px' }}>
                搜索
            </Button>
            <Button onClick={e => this.handleReset()} style={{ marginLeft: '30px' }}>重置</Button>
          </Form.Item>
          <Icon type="question-circle" theme="filled" style={{ marginTop:'25px', fontSize: '25px', color: '#F00', marginLeft:'30px'}} onClick={() => this.setShowHelp(true)}/>
          
          </Form>     
          
        <div>

            <div style={{ display: 'flex', marginBottom: '33px' }}>
            <div style={{
                textAlign: 'center', display: 'flex', justifyContent: 'center', lineHeight: '100px', background: 'linear-gradient(144deg,rgba(241,43,62,1) 0%,rgba(254,144,155,1) 100%)',  height: '100px',
                borderRadius: '12px', width: '32%', marginRight: '2%'
            }}>
                <span style={{ fontSize: '24px', color: '#fff' }}>访问总人数 </span>
                <span style={{ fontSize: '52px', color: '#fff', marginLeft: '26px', fontFamily: 'fantasy' }}>{ this.state.personData.visitPersonNum || '0'}</span>
            </div>  
            <div style={{
                textAlign: 'center', display: 'flex', justifyContent: 'center', lineHeight: '100px', background: '#FFC6AA',  height: '100px',
                borderRadius: '12px', width: '32%', marginRight: '2%'
            }}>
                <span style={{ fontSize: '24px', color: '#fff' }}>访问总次数 </span>
                <span style={{ fontSize: '52px', color: '#fff', marginLeft: '26px', fontFamily: 'fantasy' }}>{ this.state.personData.visitNum || '0'}</span>
            </div>  
            <div style={{
                textAlign: 'center', display: 'flex', justifyContent: 'center', lineHeight: '100px', background: 'linear-gradient(137deg,rgba(107,130,230,1) 0%,rgba(152,175,251,1) 100%)', height: '100px',
                borderRadius: '12px', width: '32%', marginRight: '2%'
            }}>
                <span style={{ fontSize: '24px', color: '#fff' }}>分享总人数 </span>
                <span style={{ fontSize: '52px', color: '#fff', marginLeft: '26px', fontFamily: 'fantasy' }}>{ this.state.personData.sharePersonNum || '0'}</span>
            </div>
            <div style={{
                textAlign: 'center', display: 'flex', justifyContent: 'center', lineHeight: '100px', background: 'linear-gradient(137deg,rgba(150,83,215,1) 0%,rgba(208,160,255,1) 100%)', height: '100px',
                borderRadius: '12px', width: '32%', marginRight: '2%'
            }}>
                <span style={{ fontSize: '24px', color: '#fff' }}>分享总次数 </span>
                <span style={{ fontSize: '52px', color: '#fff', marginLeft: '26px', fontFamily: 'fantasy' }}>{ this.state.personData.shareNum || '0'}</span>
            </div>
            </div>
          
            <div style={{ display: 'flex' }}>
                <div className={style.bar}>
                    <NewUsers startDate={this.state.formData.startDate} endDate={this.state.formData.endDate} buildingId={this.state.buildingId} targetType={this.state.targetType} dataZoom={false}></NewUsers>
                </div>
            </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>

      <Modal
          title="指标说明"
          visible={this.state.helpVisible}
          onCancel={() => this.setShowHelp(false)}
          footer={null}
        >
          <Row>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>分享人数：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>分享小程序活动的总人数</p>
            
            
          </Row>
          <Row>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>分享次数：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>触发小程序活动分享的总次数</p>
          </Row>
          
          <Row>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>新增注册用户：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>通过分享的活动授权手机号的总人数</p>
          </Row>
          
          <Row>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>访问人数：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>访问小程序活动的总人数</p>
          </Row>
          
          <Row>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>访问次数：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>访问小程序活动的总次数</p> 
          </Row>
          
        </Modal>
    </>
    )
    
  }
}
const WrappedTypeForm = Form.create()(OverView);
export default WrappedTypeForm
