import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, DatePicker } from 'antd';
import router from 'umi/router';
import apis from '../../../../services/apis';
import request from '../../../../utils/request';
import AuthButton from '../../../../components/AuthButton';
import WxDictSelect from '@/components/SelectButton/WxDictSelect';
import moment from 'moment';

const date = {
  startDate: moment().year(1000).hours(0).minutes(0).seconds(0).milliseconds(0).format('YYYY-MM-DDTHH:mm:ss')+'.000Z',
  endDate: moment().year(3000).hours(0).minutes(0).seconds(0).milliseconds(0).format('YYYY-MM-DDTHH:mm:ss')+'.000Z'
}

const header = props => {
  const [showHelp, setShowHelp] = useState(false)
  const [data, setData] = useState({})
  const activityId = props.id
  const activityType = props.type

  useEffect(() => {
    console.log(activityId, activityType)
    getList({ pageNum: 1, pageSize: 10 })

  }, [])

  const getList = params => {
    console.log(params)
    request({ ...apis.activityDataStatis.activityVisitNum, params: { ...params, activityId: activityId, activityType: activityType, ...date } }).then(data => {
      console.log(data)
      props.getData()
      setData(data)
    }).catch(e => {
      console.log(e)
    })
  }

  const format = data =>{    
  return <div dangerouslySetInnerHTML={{__html:data.replace(/,/g,",<br/>")}}>{}</div>
  }

  let columns = [
    {
      title: '姓名',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
    },
    {
      title: '归属地',
      dataIndex: 'province',
      key: 'province',
    },
    {
      title: '来源渠道',
      dataIndex: 'personFrom',
      key: 'personFrom',
    },
    {
      title: '置业顾问',
      dataIndex: 'realtyConsultant',
      key: 'realtyConsultant',
      render: (x, row) => <>{row.realtyConsultant?format(row.realtyConsultant):''}</>,
      width:180
    },
    {
      title: '置业顾问电话',
      dataIndex: 'realtyConsultantPhone',
      key: 'realtyConsultantPhone',
      render: (x, row) => <>{row.realtyConsultantPhone?format(row.realtyConsultantPhone):''}</>,
      width:180
    },
    {
      title: '分享者',
      dataIndex: 'sharePersonName',
      key: 'sharePersonName',
    },
    {
      title: '分享者电话',
      dataIndex: 'sharePersonPhone',
      key: 'sharePersonPhone',
    },
    {
      title: '访问时间',
      dataIndex: 'visitDate',
      key: 'visitDate',
      render: (x, row) => <><span>{`${moment(row.visitDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
  ]

  function handleReset() {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 10 })
  }

  const changePageNum = pageNumber => {
    getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
  }

  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

  const exportActivityStats = () => {

    request({ ...apis.activityDataStatis.activityVisitNumExport, params: { activityId: activityId, activityType: activityType, ...props.form.getFieldsValue(), ...date } }).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()
  }

  const { getFieldDecorator } = props.form
  return <>
    <div>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)} style={{ display: 'flex', alignItems: 'center' }}>
        <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
          {getFieldDecorator('personFrom')(
            <WxDictSelect />,
          )}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
          {getFieldDecorator('province')(<Input placeholder="请输入归属地" />)}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
          {getFieldDecorator('realtyConsultant')(<Input placeholder="置业顾问" />)}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
          {getFieldDecorator('realtyConsultantPhone')(<Input placeholder="置业顾问电话" />)}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
          <Button type="primary" htmlType="submit" style={{ marginLeft: '30px' }}>
            搜索
            </Button>
          <Button onClick={handleReset} style={{ marginLeft: '30px' }}>重置</Button>
        </Form.Item>
        <Icon type="question-circle" theme="filled" style={{ fontSize: '25px', color: '#F00', marginLeft: '30px' }} onClick={() => setShowHelp(true)} />
        <Modal
          title="指标说明（数据会存在一定时间延迟）"
          centered
          visible={showHelp}
          footer={null}
          onCancel={() => setShowHelp(false)}
        >
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>分享人数：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>分享小程序活动的总人数</p>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>分享次数：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>触发小程序活动分享的总次数</p>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>新增注册用户：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>通过当前活动授权手机号的总人数</p>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>访问人数：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>访问小程序活动的总人数</p>
          <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>访问次数：</p>
          <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>访问小程序活动的总次数</p>
        </Modal>
      </Form>
      <div>


        <Button type="primary" style={{ float: 'right', marginBottom: '20px', zIndex: 1 }} onClick={exportActivityStats} >
          导出
            </Button>

      </div>
      <Table style={{ marginTop: '30px' }} 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>
    </div>
  </>
}

const WrappedTypeForm = Form.create()(header);
export default WrappedTypeForm