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 { FormattedMessage } from 'umi-plugin-react/locale';
import styles from '../../style/GoodsList.less';
import moment from 'moment';
import apis from '../../../services/apis';
import request from '../../../utils/request';
import { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } from 'constants';
import AuthButton from '../../../components/AuthButton';
import { timeout } from 'q';
import Prompt from 'umi/prompt';

const data = []

const header = (props) => {
  const { drainageId, name } = props.location.query


  const [datas, setDatas] = useState([])
  const [content, setContent] = useState([{}, {}])
  const [columns, setColumns] = useState([])
  const [startDate, setStartDate] = useState('')
  const [endDate, setEndDate] = useState('')
  const [total, setTotal] = useState({})
  // let content = {}
  useEffect(() => {

    gettaDrainageRecord({ pageNum: 1, pageSize: 10, drainageId: drainageId })

  }, [])

  function gettaDrainageRecord(params) {
    request({ ...apis.activity.taDrainageRecord, params: { ...params } }).then((data) => {
      // setDatas(data) 
      console.log(data, '3333333333333')
      if (data.total != 0) {
        setTotal(data)
        setDatas(tableData(data.records))
        // content = data.records[0]
        console.log('json: ', eval('(' + data.records[0].content + ')'))
        setContent(eval('(' + data.records[0].content + ')'))
        setColumns(tableTitle(data.records))
      }
      else {
        setDatas([])
        message.info('数据为空')
      }



    }).catch((err) => {
      console.log(err)
      message.info(err.msg || err.message)
    })
  }
  function tableData(data) {
    console.log('tabledata', data)
    return data.map((row, inx) => {
      return eval('(' + row.content + ')').reduce((acc, col) => {
        const r = {

          key: inx + 1,
          createDate: row.createDate,
          [`${col.key}`]: col.value,
          ...acc,
        }
        console.log('r', r)
        return r
      }, {})
    })
  }

  function tableTitle(data) {
    tableTitle = eval('(' + data[0].content + ')')
    const cols = [{
      title: "提交时间",
      dataIndex: "createDate",
      key: "createDate",
      render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    }]
    return cols.concat(tableTitle.map((item) => {
      const col = {
        title: item.label,
        dataIndex: item.key,
        key: item.key
      }
      return col
    }))
  }
  // function datalist () {

  //   gettaDrainageRecord({ pageNum: 1, pageSize: 10, drainageId: drainageId, startTime: Time(startDate), endTime: Time(endDate) })
  // }

  function fromTime(str) {
    return str === '' ? null : `${moment(str).format('YYYY-MM-DDT00:00:00.000')}Z`
  }

  function Time(str) {
    return str === '' ? null : `${moment(str).format('YYYY-MM-DD')}`
  }
  // 2019-10-30T11:04:49
  function onChangetime(dates, dateStrings) {
    console.log(dateStrings[1])
    setEndDate(dateStrings[1])
    setStartDate(dateStrings[0])

  }

  const changePageNum = pageNumber => {
    gettaDrainageRecord({ pageNum: pageNumber, pageSize: 10, drainageId: drainageId, startTime: Time(startDate), endTime: Time(endDate) })
  }


  function excelPort() {
    // const fieldsValue = getFieldsValue()

    request({ ...apis.activity.exporttaDrainageRecord, params: { drainageId: drainageId, startTime: fromTime(startDate), endTime: fromTime(endDate) } })
      .then(response => {
        download(response)
      }).catch(error => {

      })
  }



  function download(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()
  }

  function handleReset(e) {
    console.log(e)
    props.form.resetFields();
    setEndDate('')
    setStartDate('')
  }

  const handleSubmit = (e, props) => {
    e.preventDefault();
    gettaDrainageRecord({ pageNum: 1, pageSize: 10, drainageId: drainageId, startTime: Time(startDate), endTime: Time(endDate) })
  }

  const { RangePicker } = DatePicker;
  const { getFieldDecorator } = props.form
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>

          <Form.Item label="提交时间">
            {getFieldDecorator('time')(
              <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"
                showTime
                onChange={onChangetime}
              />,
            )}
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" >
              搜索
          </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
        <Button onClick={() => router.go(-1)} style={{ float: 'right' }}>返回</Button>
      </div>
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div style={{ lineHeight: '92px', width: '600px', fontWeight: 'bold', fontSize: '18px' }}>
            H5项目：{name}
          </div>
          {/* H5项目名称 style={{ float: 'right', margin: '20px 0', zIndex: 1 }} */}
          <AuthButton name="admin.taDrainageRecord.export.get" noRight={null}>
            <Button type="primary" style={{ marginLeft: '30px', float: 'right', marginTop: '30px', marginBottom: '30px', zIndex: 1 }} onClick={excelPort}>导出数据</Button>
          </AuthButton>
        </div>
        <Table columns={columns} dataSource={datas} pagination={false} />
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
          <Pagination showQuickJumper defaultCurrent={1} total={total.total} onChange={(e) => changePageNum(e)} current={total.current} />
        </div>
      </div>

      <Prompt message={location =>
        location.pathname.startsWith("/activity/drainage")
          ? true
          : localStorage.removeItem("drainageActivePageParams")} />


    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
