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 style from './compenents/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 Prompt from 'umi/prompt';


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

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

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

let columns = [
  {
    title: '分享者姓名',
    dataIndex: 'sharePersonName',
    key: 'sharePersonName',
  },
  {
    title: '分享者类型',
    dataIndex: 'shareType',
    key: 'shareType',
    render: (text, records) => {
      if (records.sharePersonType === 'drift') { return '游客' }
      if (records.sharePersonType === 'customer') { return '普通客户' }
      if (records.sharePersonType === 'Realty Consultant') { return '置业顾问' }
      if (records.sharePersonType === 'estate agent') { return '专业经纪人' }
    },
  },
  {
    title: '分享时间',
    dataIndex: 'shareTime',
    key: 'shareTime',
    render: (x, row) => <><span>{`${moment(row.shareTime).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
  },
  {
    title: '分享者电话',
    dataIndex: 'sharePersonPhone',
    key: 'sharePersonPhone',
  },
  // {
  //   title: '访问人数',
  //   dataIndex: 'visitPersonNum',
  //   key: 'visitPersonNum',
  // },
]

class SharePersonNum extends React.Component {

  constructor(props) {
    super(props)
    console.log(props)
    queryDate = props.location.query.queryDate
    let startDate;
    let endDate;
    if (props.location.query.queryDate) {
      startDate = moment(props.location.query.queryDate).hours(0).minutes(0).seconds(0).milliseconds(0).format('YYYY-MM-DDTHH:mm:ss') + '.000Z';
      endDate = moment(props.location.query.queryDate).hours(23).minutes(59).seconds(59).milliseconds(999).format('YYYY-MM-DDTHH:mm:ss') + '.999Z';
    } else {
      startDate = moment(props.location.query.startDate).hours(0).minutes(0).seconds(0).milliseconds(0).format('YYYY-MM-DDTHH:mm:ss') + '.000Z';
      endDate = moment(props.location.query.endDate).hours(23).minutes(59).seconds(59).milliseconds(999).format('YYYY-MM-DDTHH:mm:ss') + '.999Z';
    }
    this.state = {
      formData: {
        sharePhone: '',
        sharePersonType: '',
        pageNum: '',
        pageSize: '',
        shareName: '',
        sort: null,
        colKey: null,
        startDate: startDate,
        endDate: endDate,
        activityId: props.location.query.activityId,
        activityType: props.location.query.activityType,
        personId: props.location.query.personId,
        buildingId: props.location.query.buildingId
      },
      personData: [],
      dataSoures: [],
      tableData: [],
      userType: 'all',
      activityName: props.location.query.activityName
    }
  }

  componentDidMount() {
    this.getTableList()
  }

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

  handleSubmit = (e, props) => {
    let startDate = null
    let endDate = null
    const sharePersonType = this.props.form.getFieldValue("sharePersonType");
    const sharePersonPhone = this.props.form.getFieldValue("sharePersonPhone");
    const sharePersonName = this.props.form.getFieldValue("sharePersonName");
    const { formData } = this.state
    this.setState({
      formData: {
        ...formData,
        sharePersonType: sharePersonType,
        sharePersonPhone: sharePersonPhone,
        sharePersonName: sharePersonName,
        pageNum: 1,
        pageSize: 999
      }
    }, this.getTableList)
  }

  //重置搜索
  handleReset = e => {
    this.props.form.resetFields()
    let startDate;
    let endDate;
    if (this.props.location.query.queryDate) {
      startDate = moment(this.props.location.query.queryDate).hours(0).minutes(0).seconds(0).milliseconds(0).format('YYYY-MM-DDTHH:mm:ss') + '.000Z';
      endDate = moment(this.props.location.query.queryDate).hours(23).minutes(59).seconds(59).milliseconds(999).format('YYYY-MM-DDTHH:mm:ss') + '.999Z';
    } else {
      startDate = moment(this.props.location.query.startDate).hours(0).minutes(0).seconds(0).milliseconds(0).format('YYYY-MM-DDTHH:mm:ss') + '.000Z';
      endDate = moment(this.props.location.query.endDate).hours(23).minutes(59).seconds(59).milliseconds(999).format('YYYY-MM-DDTHH:mm:ss') + '.999Z';
    }
    this.setState({
      formData: {
        sharePhone: '',
        sharePersonType: '',
        pageNum: '',
        pageSize: '',
        shareName: '',
        sort: null,
        colKey: null,
        startDate: startDate,
        endDate: endDate,
        activityId: this.props.location.query.activityId,
        activityType: this.props.location.query.activityType,
        personId: this.props.location.query.personId,
        buildingId: this.props.location.query.buildingId
      },
      personData: [],
      dataSoures: [],
      tableData: [],
      userType: 'all',
      activityName: this.props.location.query.activityName
    }, this.getTableList)
  }

  goback = () => {
    router.go(-1);
  }

  exportActivityStats = () => {
    const { formData } = this.state
    request({ ...apis.activityDataStatis.activityShareNumExport, params: 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,
        sharePersonType: formData.sharePersonType,
        sharePhone: formData.sharePhone,
        shareName: formData.shareName,
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        sort: sorter.order,
        colKey: sorter.columnKey
      }
    }, this.getTableList)
  };

  render() {
    const { radioVal } = this.state
    const { getFieldDecorator } = this.props.form;

    return (
      <>
        <div align="right" style={{ marginBottom: '16px' }}><Button onClick={this.goback}>返回</Button></div>
        <div>
          <span style={{ marginLeft: '20px' }}>分享内容：{this.state.activityName}</span>
        </div>
        <Form layout="inline" onSubmit={e => this.handleSubmit(e, this.props)} style={{ display: 'flex', alignItems: 'center' }}>
          <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
            {getFieldDecorator('sharePersonType')(
              <Select placeholder="分享者类型" style={{ width: 150, marginLeft: '20px' }}>
                <Option value="drift">游客</Option>
                <Option value="customer">普通客户</Option>
                <Option value="Realty Consultant">置业顾问</Option>
                <Option value="estate agent">专业经纪人</Option>
              </Select>
            )}
          </Form.Item>
          <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
            {getFieldDecorator('sharePersonPhone')(<Input placeholder="分享者电话" />)}
          </Form.Item>
          <Form.Item style={{ marginTop: '20px', marginBottom: '20px' }}>
            {getFieldDecorator('sharePersonName')(<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>
          <AuthButton name="admin.statistical.activity.export" noRight={null}>
            <Button type="primary" style={{ position: 'absolute',right:'27px', zIndex: 1 }} onClick={this.exportActivityStats}>
              导出
            </Button>
          </AuthButton>
        </Form>
        <div>

          <Table style={{ marginTop: '20px' }} dataSource={this.state.tableData} columns={columns} pagination={{ total: this.state.total }} onChange={this.handleTableChange} scroll={{ y: 500 }}></Table>
        </div>
        <Prompt message={location =>
          location.pathname.startsWith("/statistical/activity")
            ? true
            : localStorage.removeItem("tabState")} />
      </>
    )

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