import React, { Component, useState, useEffect } from 'react';
import EChart from '@/components/EchartsTest/EChart';
import request from '@/utils/request';
import apis from '@/services/apis';
import moment from 'moment';
import router from 'umi/router';
import 'echarts/lib/component/dataZoom'
import { Table, Select, Row, Col, Menu, Dropdown, Button, Icon, message, Modal } from 'antd';
import BuildSelect from '@/components/SelectButton/BuildSelect'

const { Option } = Select;


const eventcolumns = [
  {
    title: '编号',
    dataIndex: 'recordId',
    key: 'recordId',
    align: 'center',
    width: '16%',
  },
  {
    title: '访问时间',
    dataIndex: 'visitTime',
    key: 'visitTime',
    align: 'center',
    width: '18%',
    render: (x, row) => (
      <>
        <span>{moment(row.visitTime).format('YYYY-MM-DD hh:mm:ss')}</span>
      </>
    ),
  },
  {
    title: '离开时间',
    dataIndex: 'leaveTime',
    key: 'leaveTime',
    align: 'center',
    width: '18%',
    render: (x, row) => (
      <>
        <span>{row.leaveTime && moment(row.leaveTime).format('YYYY-MM-DD hh:mm:ss')}</span>
      </>
    ),
  },
]


class EventcoModal extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      eventList: [],
      visibleData: { visible: false, row: {} },
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.visibleData.visible !== prevProps.visibleData.visible) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({ visibleData: this.props.visibleData }, () => {
        this.showDetails(this.props.visibleData.row)
      })
    }
  }

  showDetails = row => {
    request({
      ...apis.indexEcharts.userBehavior.profile,
      params: { event: row.event, personId: row.personId },
    }).then(data => {
      this.setState({ eventList: data })
    })
  }

  handleOk = e => {
    this.props.onSuccess()
  };

  handleCancel = e => {
    this.props.onSuccess()
  };

  render() {
    return (
      <>
        <Modal
          title="访问详情"
          visible={this.state.visibleData.visible}
          onOk={() => this.handleOk()}
          onCancel={() => this.handleCancel()}
          footer={null}
        >
          <Table rowKey="UserBehavior" dataSource={this.state.eventList} columns={eventcolumns} pagination={false} rowKey="eventall" scroll={{ y: 400 }} />
        </Modal>
      </>
    )
  }
}


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 }
}
const UserBehaviorIndex = props => {
  const [data, setData] = useState({ records: [] })
  const [visibleData, setVisibleData] = useState({ visible: false, row: {} })
  const [buildingId, setBuildingId] = useState('')

  // 柱图
  useEffect(() => {
    const date = formatDate(props.startDate, props.endDate)
    getUserBehaviorSummary({
      ...date,
      activity: props.activity,
      event: props.event,
      eventType: props.eventType,
      buildingId: props.buildingId,
    })
    // getUserBehaviorProfile(formatDate(props.startDate, props.endDate))
  }, [props.startDate, props.endDate, props.activity, props.event, props.eventType, props.buildingId])

  const [recordList, setList] = useState([])
  function getUserBehaviorSummary(params) {
    request({
      ...apis.indexEcharts.userBehavior.tsUserBehavior,
      params,
    }).then(data => {
      setData(data || {})
      // setList((data.data.records || []).filter(e => e.activity !== '客户'))
    })
  }


  const seriesMaker = (data.selectUserBehavior || []).filter(e => e.activity !== '客户' && e.activity !== '首页').reduce((series, item) => {
    let { date, activityCount, activity } = item
    date = moment(date).format('YYYY-MM-DD')
    if (!activityCount) activityCount = 0

    // 使用对象, 可以去重
    series[`${activity}`] = (series[`${activity}`] || []).concat([[date, activityCount]])

    return series;
  }, {})


  const dataZoom = props.dataZoom ? [
    {
      type: 'inside',
      start: 0,
      end: 100,
    },
    {
      type: 'slider',
      start: 0,
      end: 100,
    },
  ] : undefined


  const options = {
    title: {},
    icon: 'rect',
    legend: {
      show: true,
      zlevel: 10,
      itemGap: 100,
    },
    color: ['#F12B3E', '#FE929C', '#647CE1', '#A2B9FF', '#FF844F', '#FFBB9D'],
    tooltip: {
      trigger: 'axis',
    },
    xAxis: { type: 'category' },
    yAxis: {},
    dataZoom,
    series: Object.keys(seriesMaker).map(x => ({
      type: 'line',
      smooth: true,
      name: x,
      data: seriesMaker[x],
    })),
  }
  function handleBuildingChange(e) {
    const date = formatDate(props.startDate, props.endDate)
    getUserBehaviorSummary({
      ...date,
      activity: props.activity,
      event: props.event,
      eventType: props.eventType,
      buildingId: e,
    })
    setBuildingId(e)
  }

  function showDetails(row) {
    setVisibleData({ visible: true, row })
  }

  function onSuccess() {
    setVisibleData({ visible: false, row: {} })
  }


  const style = {
    width: '100%',
    height: '400px',

  }

  const columns = [
    {
      title: '访问事件',
      dataIndex: 'eventName',
      key: 'eventName',
      align: 'center',
      width: '16%',

    },
    {
      title: '访问用户',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center',
      width: '15%',

    },
    {
      title: '访问次数',
      dataIndex: 'accessCount',
      key: 'accessCount',
      align: 'center',
      width: '17%',

      render: (x, row) => (
        <>
          <span style={{ color: '#EF273A', cursor: 'pointer' }} onClick={() => showDetails(row)}> {row.accessCount}</span>
        </>
      ),
    },
    {
      title: '首次访问时间',
      dataIndex: 'visitTime',
      key: 'visitTime',
      align: 'center',
      width: '18%',
      render: (x, row) => (
        <>
          <span>{row.visitTime && moment(row.visitTime).format('YYYY-MM-DD hh:mm:ss')}</span>
        </>
      ),
    },
    {
      title: '离开时间',
      dataIndex: 'leaveTime',
      key: 'leaveTime',
      width: '18%',
      align: 'center',
      render: (x, row) => (
        <>
          <span>{row.leaveTime && moment(row.leaveTime).format('YYYY-MM-DD hh:mm:ss')}</span>
        </>
      ),
    },
  ]


  return (
    <>
      <div>
        {/* <p onClick={() => router.push('/statistical/userBehavior')} style={{cursor: 'pointer'}}> */}
        <div style={{marginBottom:'40px'}}>
          <span style={{ borderBottom: '1px solid #f02d40', color: '#333', fontSize: '0.12rem', fontWeight: '600' }}>用户行为</span>
          {!props.BuildSelectHide && <span style={{ fontSize: '0.09rem', color: '#888', marginLeft: '0.06rem' }}>最近七天</span>}
          {/* </p> */}
          <div style={{ float: 'right' }}>
            {!props.BuildSelectHide && <BuildSelect slot="action" onChange={(e => handleBuildingChange(e))} value={buildingId}></BuildSelect>}
          </div>
        </div>
        <EChart options={options} style={style} />
        {false &&
          <Table rowKey="UserBehaviorTwo" dataSource={recordList} columns={columns} pagination={false} rowKey="userbehavior" scroll={{ y: 500 }} />
        }
      </div>
      <EventcoModal visibleData={visibleData} onSuccess={() => onSuccess()} />
    </>
  )
}

export default UserBehaviorIndex
