import React, { Component, useState, useEffect } from 'react';
import { Radio, DatePicker, Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, Breadcrumb } from 'antd';
import { Row, Col, Menu, Dropdown } from 'antd';
import NewUsers from './components/NewUsers'
// import XForm, { FieldTypes } from '../../components/XForm';
import moment from 'moment';
import router from 'umi/router';
import EChart from '../../components/EchartsTest/EChart';
import request from '../../utils/request';
import apis from '../../services/apis';


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

let columns = [
  {
    title: '日期',
    dataIndex: 'createTime',
    key: 'createTime',
  },
]

let daterange = []

const header = props => {

  const [tableData, setTableData] = useState([])
  const [endDate, setEndDate] = useState({})
  const [data, setDate] = useState({})
  const [userType, setUserType] = useState({})
  const [startDate, setStartDate] = useState({})


  useEffect(() => {

    setEndDate(new Date())
    setStartDate(moment().subtract(7, 'day').toDate())
    // setStartDate(moment().subtract(7, 'day').toDate())
    userResource({ startDate: moment().subtract(7, 'day').toDate(), endDate: new Date() })
  }, [])

  const { RangePicker } = DatePicker;

  function onChangetime(dates, dateStrings) {

    daterange[1] = `${moment(dateStrings[1]).format('YYYY-MM-DDT00:00:00.000')}Z`
    daterange[0] = `${moment(dateStrings[0]).format('YYYY-MM-DDT00:00:00.000')}Z`

  }

  const handleSubmit = (e, props) => {

    e.preventDefault();

  }

  const getDataOf = (days) => () => {


    setEndDate(new Date())
    setStartDate(moment().subtract(days, 'day').toDate())
    userResource({ startDate: moment().subtract(days, 'day').toDate(), endDate: new Date() })
  }

  function onChange(e) {


  }

  function datalist() {
    setEndDate(daterange[1])
    setStartDate(daterange[0])
    userResource({ startDate, endDate })

  }

  function userResource(params) {
    request({
      ...apis.indexEcharts.selectPersonFrom,
      params,
    }).then((data) => {
      setDate(data);
      onTabledatas(data, "all")
    })
  }

  const onTabledatas = (e, changeType) => {
    e.tdWxDicts.map(x => {
      columns = columns.filter(y => y.key != x.sceneType).concat({
        title: x.sceneAlias,
        dataIndex: x.sceneType,
        key: x.sceneType,
      })
    })
    const data = (e.list || []).reduce((acc, item) => {
      const { sceneType, fromNum, registeredNum, createTime } = item
      const num = changeType === 'registered' ? registeredNum : fromNum
      acc[createTime] = { ...acc[createTime], ...item, [`${sceneType}`]: !num ? 0 : num }
      return acc
    }, {})

    const dictData = e.tdWxDicts.reduce((acc, item, index) => {
      const { sceneType } = item
      acc[sceneType] = 0
      return acc
    }, {})

    const tableData = Object.keys(data).map(k => data[k]).reduce((acc, item, index) => {
      acc[index] = { ...dictData, ...item }
      return acc
    }, [])

    setTableData(tableData)

  }

  function handleSelectChange(e) {
    setUserType(e)
    onTabledatas(data, e)
  }

  function exportUserStats() {
    console.log(startDate, endDate, userType)
    request({
      ...apis.indexEcharts.exportUserStats,
      params: { startDate, endDate, userType },
    }).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()
    })
  }

  const { Column, ColumnGroup } = Table;

  return (<>
    <div >
      <Radio.Group onChange={onChange} buttonStyle="solid" defaultValue="a" style={{ marginBottom: '20px' }}>
        {/* <Radio.Button value="c" onClick={getDataOf(0)}>今日</Radio.Button> */}
        <Radio.Button value="a" onClick={getDataOf(7)}>最近7天</Radio.Button>
        <Radio.Button value="b" onClick={getDataOf(30)}>最近1月</Radio.Button>
      </Radio.Group>
      <RangePicker
        style={{ paddingLeft: '30px' }}
        ranges={{
          Today: [moment(), moment()],
          'This Month': [moment().startOf('month'), moment().endOf('month')],
        }}
        // showTime
        // format="YYYY/MM/DD HH:mm:ss"
        onChange={onChangetime}
      />
      <Button type="primary" htmlType="submit" style={{ marginLeft: '30px' }} onClick={datalist}>
        搜索
          </Button>
      <Button onClick={() => router.go(-1)} style={{ float: 'right' }}>返回</Button>
      <div>
        <NewUsers BuildSelectHide={true} endDate={endDate} startDate={startDate} dataZoom={true} ></NewUsers>
        {/* */}

        <Row>
          <Col span={22}>
            <Select style={{ width: '180px' }} placeholder="所有用户" onChange={(e) => handleSelectChange(e)}>
              <Option value='all'>所有用户</Option>
              <Option value='registered'>注册用户</Option>
            </Select>
          </Col>
          <Col span={2}>
            <Button type="primary" onClick={exportUserStats}>导出</Button>
          </Col>
        </Row>

        <Table style={{ marginTop: '20px' }} dataSource={tableData} columns={columns} pagination={false} scroll={{ y: 500 }}></Table>
      </div>
    </div>
  </>
  )
}

export default header