import React, { useState, useEffect, useRef, Component } from 'react'
import { connect } from 'dva'
import { initFilter, addRuleAndGroups, guid, extendInclude, extendRule, extendOrder, extend, initQueryFilter } from "../../../utils/common"
import { Table, Row, Col, Button, Select, DatePicker, message } from 'antd';
import echarts from 'echarts';
import moment from 'moment'
const { Option } = Select;
class BI005LoginRecord extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pagination: {},
      retData: [],
      totalUsers: 0,
      totalActiveUsers: 0,
      maxTime: moment().format('YYYY-MM-DD'),
      minTime: moment().add(-1, "month").format('YYYY-MM-DD'),
      searchMaxTime: moment().add(1, "day").format('YYYY-MM-DD'),
      searchMinTime: moment().format('YYYY-MM-DD'),
      selectUser: "",
      selectDepartment: "",
      dates: [],
      activeNums: [],
      loginNums: [],
      todayCount: 0,
      showLoading: false
    };
  };

  componentDidMount() {
    this.state.columns1 = [
      {
        title: '序号',
        render: (text, record, index) => `${index + 1}`
      },
      {
        title: '姓名',
        dataIndex: 'Nav_User.NAME',
      },
      {
        title: '组织',
        dataIndex: 'Nav_Department.NAME',
      },
      {
        title: '登陆时间',
        dataIndex: 'CREATE_TIME',
      },
    ]
    const json = initFilter(this.props.login.OrgId);
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'BI/BIController/userCount',
      payload: json,
      onlyData: false,
      onComplete: (ret) => {
        this.state.totalUsers = ret.Data
        this.getBaseInfoData();
      }
    })
  };
  handleClick = (value) => {
    if (moment(this.state.searchMaxTime).diff(this.state.searchMinTime, 'day') >= 7) {
      message.error("查询时间请勿大于等于7天");
      return
    }
    this.getBaseInfoData()
  }
  //获取数据
  getBaseInfoData = () => {
    this.state.showLoading = true;
    const json2 = initFilter(this.props.login.OrgId)
    extendInclude(json2, 'Nav_User')
    extendInclude(json2, 'Nav_Department')
    extendRule(json2, 'CREATE_TIME', 6, this.state.searchMinTime)
    extendRule(json2, 'CREATE_TIME', 4, this.state.searchMaxTime)
    if (this.state.selectUser != "" && this.state.selectUser != undefined) {
      extendRule(json2, 'USER_ID', 1, this.state.selectUser)
    }
    if (this.state.selectDepartment != "" && this.state.selectDepartment != undefined) {
      extendRule(json2, 'DEPARTMENT_ID', 1, this.state.selectDepartment)
    }
    extendOrder(json2, "CREATE_TIME", 1);
    json2.Limit = 100;
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'BI/LoginRecord/OrderEntities',
      payload: json2,
      onlyData: false,
      onComplete: (ret) => {
        if (ret) {
          this.state.retData = ret?.Data;
          let userArr = [];
          for (let i = 0; i < this.state.retData.length; i++) {
            userArr.push(this.state.retData[i].USER_ID);
          }
          let newArr = [...new Set(userArr)];
          if (this.state.todayCount == 0) {
            this.state.todayCount = newArr.length;
          }
          this.chart1(this.state.todayCount);
          this.state.showLoading = false;
        }

      }
    })
  };
  chart1 = (todayCount) => {
    const json1 = initFilter(this.props.login.OrgId)
    extendRule(json1, 'DATE', 5, moment().subtract(30, 'days'))
    extendOrder(json1, "DATE", 0);
    json1.Limit = 60;
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'BI/ActiveUserRecord/OrderPaged',
      payload: json1,
      onlyData: false,
      onComplete: (ret) => {
        if (ret) {
          this.state.activeNums = [];
          this.state.dates = [];
          this.state.loginNums = [];
          for (let i = 0; i < ret.Data.length; i++) {
            if (ret.Data[i].type == 0) {
              this.state.activeNums.push(ret.Data[i].COUNT);
              this.state.dates.push(moment(ret.Data[i].DATE).format('MM-DD'));
            } else {
              this.state.loginNums.push(ret.Data[i].COUNT);
            }
          }
          if (this.state.totalActiveUsers == 0) {
            this.state.totalActiveUsers = ret.Data.reverse().find(item => item.type === 0).COUNT;
          }
          this.state.dates.push(moment().format('MM/DD'));
          this.state.loginNums.push(todayCount);
          let chart1s = document.getElementById('chart1');
          if (chart1s) {
            let myChart = echarts.init(chart1s);
            myChart.on('click', (params) => {
              this.state.searchMinTime = moment().format('YYYY') + "-" + params.name + " 00:00:00";
              this.state.searchMaxTime = moment(this.state.searchMinTime).add(1, "day").format('YYYY-MM-DD 00:00:00');
              if (params.seriesName == "活跃用户数") {
                this.state.totalActiveUsers = params.value;
              } else {
                this.state.totalActiveUsers = ret.Data.find(item => item.DATE == this.state.searchMinTime && item.type == 0).COUNT;
              }
              this.getBaseInfoData()
            });
            myChart.setOption({
              grid: {
                left: '5%',
                right: '5%',
              },
              legend: {
                bottom: '0px'
              },
              title: {
                text: "系统活跃用户数走势分析",
                left: 'center'
              },
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                },
              },
              xAxis: {
                type: 'category',
                data: this.state.dates,
                axisLabel: {
                  showMaxLabel: true
                }
              },
              yAxis: {
                type: 'value',
              },
              series: [
                {
                  name: '活跃用户数',
                  data: this.state.activeNums,
                  type: 'line',
                }, {
                  name: '登录用户数',
                  data: this.state.loginNums,
                  type: 'line',
                }
              ]
            });
          }
        }
      }
    })
  }
  onChange = (type, value) => {
    this.setState({
      [type]: value
    })
  }
  render() {
    return (
      <div style={{ backgroundColor: 'white', width: '1200px', top: '0', bottom: '0', left: '0', right: '0', margin: 'auto', borderStyle: 'solid', borderColor: '#ccc', borderWidth: '1px', }}>
        <h1 style={{ textAlign: "center", marginTop: '30px', fontWeight: 'bold' }}>用户登录系统统计分析</h1>
        <div style={{ textAlign: "center" }}>
          <Button style={{ width: "110px", height: "60px", borderRadius: '8px', border: '2px RGB(24, 149, 255) solid', margin: "10px" }}>总用户数<br></br><span style={{ fontWeight: "bold", fontSize: "20px", color: 'black' }}>{this.state.totalUsers}</span></Button>
          <Button style={{ width: "110px", height: "60px", borderRadius: '8px', border: '2px RGB(24, 149, 255) solid', margin: "10px" }}>活跃用户数<br></br><span style={{ fontWeight: "bold", fontSize: "20px", color: 'green' }}>{this.state.totalActiveUsers}</span></Button>
          <Button style={{ width: "110px", height: "60px", borderRadius: '8px', border: '2px RGB(24, 149, 255) solid', margin: "10px" }}>用户活跃度<br></br><span style={{ fontWeight: "bold", fontSize: "20px", color: 'orange' }}>{((this.state.totalActiveUsers / this.state.totalUsers) * 100).toFixed(0) + "%"}</span></Button>
        </div>
        <Row gutter={10} style={{ marginTop: "14px" }}>
          <Col span={1}>
          </Col>
          <Col span={22}>
            <div className="dashboard-div-style" style={{ borderRadius: '10px', backgroundColor: 'white', boxShadow: '0px 0px 10px rgba(0,0,0,.15)' }}>
              <div id="chart1" style={{ width: '100%', height: '350px' }}></div>
            </div>
          </Col>
          <Col span={1}>
          </Col>
        </Row>
        <hr style={{ border: '1px dashed #ccc', marginBottom: "20px", marginTop: "20px" }}></hr>
        <Row gutter={10} style={{ marginTop: "14px" }}>
          <Col span={4} style={{ textAlign: 'center' }}>

            <DatePicker
              allowClear={true}
              value={moment(this.state.searchMinTime, 'YYYY-MM-DD')}
              onChange={(evt, ds) => this.onChange('searchMinTime', ds)}
              style={{ width: '90%', padding: '10px' }}
            />
            <DatePicker
              allowClear={true}
              value={moment(this.state.searchMaxTime, 'YYYY-MM-DD')}
              onChange={(evt, ds) => this.onChange('searchMaxTime', ds)}
              style={{ width: '90%', padding: '10px' }}
            />
            {/* 组织:
              <DropDownPagination inputDataApi={'FM/Department/OrderPaged'} fieldName={'Nav_Department.NAME'}
                onSelect={onSelectDepartment} onFilter={({ params }) => {
                  params.OrderType = 1
                  params.OrgId = this.state.data ? this.state.data.ORG_ID : this.props.login.OrgId
                }} /> */}
            <Select showSearch value={this.state.selectUser} style={{ width: '90%', padding: '10px' }} onChange={value => this.setState({ selectUser: value })}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {
                this.state.assessUserList ? this.state.assessUserList.map(d => (
                  <Option key={d.ID} value={d.ID} label={d.NAME}>
                    {d.NAME}
                  </Option>
                )) : ''
              }
            </Select>
            <Button type={"primary"} onClick={() => this.handleClick()}>查询</Button>
          </Col>
          <Col span={19} style={{ height: '100%' }}>
            <div className="dashboard-div-style" style={{ boxShadow: '0px 0px 10px rgba(0,0,0,.15)' }}>
              <Table
                dataSource={this.state.retData}
                columns={this.state.columns1}
                pagination={true}
                bordered
                loading={this.state.showLoading}
                size="small"
                rowKey="1"
              />
            </div>
          </Col>
        </Row>
        <br />
      </div>
    )
  }
}
export default connect(({ login, app }) => ({ login, app }))(BI005LoginRecord)
