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 request from '../../../utils/request';
import apis from '../../../services/apis';
import StatsChart from './component/StatsChart';
import BuildSelect from '../../../components/SelectButton/BuildSelect'
import router from 'umi/router';
import AuthButton from '@/components/AuthButton';


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

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

class buildingStats extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      barData: {},
      tableData: [],
      total: 0,
      userType: 'all',
      endDate: {},
      startDate: {},
      buildingId: '',
      radioValue: 'a'
    }
  }

  componentDidMount() {
    this.getBarData(moment().subtract(6, 'day').toDate(), new Date())
    this.getTableData(moment().subtract(6, 'day').toDate(), new Date(), this.state.buildingId)
    this.setState({ ...this.state, endDate: new Date(), startDate: moment().subtract(6, 'day').toDate() })

  }

  // 获取图表数据
  getBarData = (startDate, endDate) => {
    request({ ...apis.stats.barList, params: { startDate: moment(startDate).format('YYYY-MM-DDT00:00:00.000') + 'Z', endDate: moment(endDate).format('YYYY-MM-DDT23:59:59.999') + 'Z'
  } }).then((data) => {
      this.setState({ ...this.state, barData: data })
    })
  }

  //获取表格数据
  getTableData = (startDate, endDate, buildingId, pageNum, pageSize, sortField, sortOrder) => {
    request({ ...apis.stats.tableList, params: { startDate: moment(startDate).format('YYYY-MM-DDT00:00:00.000') + 'Z', endDate: moment(endDate).format('YYYY-MM-DDT23:59:59.999') + 'Z', buildingId, pageNum, pageSize, sortField, sortOrder } }).then((data) => {
      this.setState({ ...this.state, tableData: data.records, total: data.total })
    })
  }

  formatDate = (start, end) => {
    const tempStartDate = `${moment(start).format('YYYY-MM-DDT00:00:00.000')}Z`
    const tempEndDate = `${moment(end).format('YYYY-MM-DDT23:59:59.999')}Z`
    return { startDate: tempStartDate, endDate: tempEndDate }
  }

  //时间选择器改变的时候
  onChangetime = (_dates, dateStrings) => {
    daterange[0] = `${moment(dateStrings[0]).format('YYYY-MM-DDT00:00:00.000')}Z`
    daterange[1] = `${moment(dateStrings[1]).format('YYYY-MM-DDT23:59:59.999')}Z`
  }

  //切换三个标签页
  getDataOf = (days,val) => {
    this.getBarData(moment().subtract(days, 'day').toDate(), new Date())
    this.getTableData(moment().subtract(days, 'day').toDate(), new Date(), this.state.buildingId)
    this.setState({ ...this.state, endDate: new Date(), startDate: moment().subtract(days, 'day').toDate(), radioValue: val })
  }

  //点击查询
  datalist = () => {
    this.getBarData(daterange[0] === undefined ? moment().subtract(6, 'day').toDate() : daterange[0], daterange[1] === undefined ? new Date() : daterange[1])
    this.getTableData(daterange[0] === undefined ? moment().subtract(6, 'day').toDate() : daterange[0], daterange[1] === undefined ? new Date() : daterange[1], this.state.buildingId)
    this.setState({
      ...this.state,
      endDate: daterange[1] === undefined ? new Date() : daterange[1],
      startDate: daterange[0] === undefined ? moment().subtract(6, 'day').toDate() : daterange[0],
    })

  }

  //切换楼盘信息
  handleBuildingChange = (e) => {
    this.getTableData(this.state.startDate, this.state.endDate, e)
    this.setState({ ...this.state, buildingId: e })
  }

  //排序
  handleTableChange = (pagination, filters, sorter) => {
    console.log(pagination, filters, sorter)
    this.getTableData(this.state.startDate, this.state.endDate, this.state.buildingId, pagination.current, 10, sorter.columnKey, sorter.order)
  };

  //导出
  exportBuildingStats = () => {
    request({ ...apis.stats.buildingExport, params: { startDate: this.state.startDate, endDate: this.state.endDate, buildingId: this.state.buildingId } })
      .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(() => {

      })
  }

  //去详情页面
  toDetailPage = (record) => {
    router.push({
      pathname: '/statistical/building/detail',
      query: {
        buildingId: record.buildingId,
        buildingName: record.buildingName
      },
    });
  }

  //重置搜索
  handleReset = () => {
    daterange = []
    this.props.form.resetFields();
    this.setState({ ...this.state, endDate: new Date(), startDate: moment().subtract(6, 'day').toDate(), radioValue: "a" })
    this.getBarData(moment().subtract(6, 'day').toDate(), new Date())
    this.getTableData(moment().subtract(6, 'day').toDate(), new Date(), this.state.buildingId)
  }

  render() {
    const columns = [
      {
        title: '项目名称',
        dataIndex: 'buildingName',
        key: 'buildingName',
      },
      {
        title: '新增客户',
        dataIndex: 'khNum',
        key: 'kh_num',
        sorter: true,
      },
      {
        title: '公客',
        dataIndex: 'gkNum',
        key: 'gk_num',
        sorter: true,
      },
      {
        title: '私客',
        dataIndex: 'skNum',
        key: 'sk_num',
        sorter: true,
      },
      {
        title: '访问人数',
        dataIndex: 'uvNum',
        key: 'uv_num',
        sorter: true,
      },
      {
        title: '访问次数',
        dataIndex: 'pvNum',
        key: 'pv_num',
        sorter: true,
      },
      {
        title: '详情',
        render: (_, record) => (
          <Button type="link" style={{ color: 'red' }} onClick={() => this.toDetailPage(record)}>查看详情</Button>
        ),
      },
    ];

    const { getFieldDecorator } = this.props.form;
    return (

    <div>
      <Form layout="inline">
      <Radio.Group buttonStyle="solid" value={this.state.radioValue}>
          <Radio.Button value="c" onClick={() => this.getDataOf(0,"c")}>今日</Radio.Button>
          <Radio.Button value="a" onClick={() => this.getDataOf(6,"a")}>最近7天</Radio.Button>
          <Radio.Button value="b" onClick={() => this.getDataOf(30,"b")}>最近1月</Radio.Button>
        </Radio.Group>
        <Form.Item>
        {getFieldDecorator('time', {
            initialValue: [],
        })(
          <RangePicker
              style={{ paddingLeft: '30px' }}
              ranges={{
                Today: [moment(), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
              }}
              onChange={(_dates, dateStrings) => this.onChangetime(_dates, dateStrings)}
            />
        )}
        </Form.Item>
        <Button type="primary" htmlType="submit" style={{ marginLeft: '30px' }} onClick={() => this.datalist()}>
          搜索
        </Button>
        <Button onClick={this.handleReset} style={{ marginBottom: '18px', marginLeft: '30px' }}>重置</Button>
        </Form>
        <div style={{fontSize:'0.09rem',color:'#999',marginBottom:'0.16rem'}}>最多显示6个项目，其他项目请在下方详细数据中搜索</div>
        <Row>
          <Col span={12} style={{paddingRight:'0.08rem'}}>
            <StatsChart title="项目公客排行" data={this.state.barData.gkBarMap} />
          </Col>
          <Col span={12}style={{paddingLeft:'0.08rem'}}>
            <StatsChart title="项目私客排行" data={this.state.barData.skBarMap} />
          </Col>
        </Row>
        <Row>
          <Col span={12} style={{paddingRight:'0.08rem'}}>
            <StatsChart title="项目访问人数排行" subtext="项目详情访问情况" data={this.state.barData.wgBarMap} />
          </Col>
          <Col span={12} style={{paddingLeft:'0.08rem'}}>
            <StatsChart title="项目访问次数排行" subtext="项目详情访问情况,与上方时间筛选无关" data={this.state.barData.fwBarMap} />
          </Col>
        </Row>
        <Row>
          <Col span={22}>
            <span style={{ marginRight: '10px' }} >详细数据</span>
            <BuildSelect slot='action' onChange={(e => this.handleBuildingChange(e))} value={this.state.buildingId}></BuildSelect>
          </Col>
          <Col span={2}>
            <AuthButton name="admin.statistical.building.export" noRight={null}>
              <Button type="primary" onClick={this.exportBuildingStats}>导出</Button>
            </AuthButton>
          </Col>
        </Row>


        <Table style={{ marginTop: '20px' }} dataSource={this.state.tableData} columns={columns} pagination={{ total: this.state.total }} onChange={this.handleTableChange} scroll={{ y: 500 }}></Table>
      </div>
    )
  }
}

const WrappedHeader = Form.create({ name: 'record' })(buildingStats);

export default WrappedHeader
