import React, { useState, useEffect } from 'react';
import {
  DatePicker,
  Table,
  Row,
  Col,
  Button,
  notification,
  message,
  Spin,
} from 'antd';
import { SwapRightOutlined, SyncOutlined } from '@ant-design/icons';
import { Chart, Interval, Tooltip, Axis } from 'bizcharts';
import { DataSet } from '@antv/data-set';
import moment from 'moment';
import { post, PUBLISH_SERVICE } from '@/services/index';
import styles from './index.less';

const LoginLog = () => {
  const [loading, setLoading] = useState(false); // 源数据
  const [data0, setData0] = useState([]); // 源数据
  const [LoginNameFilters, setLoginNameFilters] = useState([]); // 用户列筛选
  const [ShowNameFilters, setShowNameFilters] = useState([]); // 用户列筛选
  const [SystemTypeFilters, setSystemTypeFilters] = useState([]); // 用户列筛选
  // const [IPCount, setIPCount] = useState([]); // 接口调用次数,统计数据
  const [startTime, setStartTime] = useState(moment().startOf('week')); // 默认值当天0点
  const [endTime, setEndTime] = useState(
    moment(new Date(), 'YYYY-MM-DD HH:mm:ss'), // 默认值当前时间
  );
  const [filteredValue, setFilteredValue] = useState([]);

  const columns = [
    // {
    //   title: 'IP',
    //   dataIndex: 'IP',
    //   key: 'IP',
    //   fixed: 'left',
    // },
    {
      title: '登录时间',
      dataIndex: 'LoginTime',
      key: 'LoginTime',
    },
    {
      title: '登录名',
      dataIndex: 'LoginName',
      key: 'LoginName',
      filters: LoginNameFilters,
      onFilter: (value, record) => record.LoginName === value,
      filteredValue,
    },
    {
      title: '用户名',
      dataIndex: 'ShowName',
      key: 'ShowName',
      filters: ShowNameFilters,
      onFilter: (value, record) => record.ShowName === value,
      filteredValue,
    },
    {
      title: '系统类型',
      dataIndex: 'SystemType',
      key: 'SystemType',
      filters: SystemTypeFilters,
      onFilter: (value, record) => record.SystemType === value,
      filteredValue,
    },
    // {
    //   title: '终端',
    //   dataIndex: 'Terminal',
    //   key: 'Terminal',
    // },
  ];
  // 在起止时间任意一个变化后获取数据
  useEffect(() => {
    if (startTime && endTime) {
      setLoading(true);
      getData();
    }
  }, [startTime, endTime]);
  const getData = () => {
    post(`${PUBLISH_SERVICE}/LogCenter/GetLoginLog`, {
      DateFrom: startTime.format('YYYY-MM-DD HH:mm:ss'),
      DateTo: endTime.format('YYYY-MM-DD HH:mm:ss'),
      IP: '',
      Module: '',
      Description: '',
      LoginName: '',
      UserName: '',
    })
      .then(res => {
        if (res.code === 0) {
          setData0(res.data);
          // 过滤LoginName
          let arr1 = res.data.map(item => item.LoginName);
          arr1 = arr1.filter((value, index) => arr1.indexOf(value) === index);
          setLoginNameFilters(arr1.map(item => ({ text: item, value: item })));
          // 过滤ShowName
          let arr2 = res.data.map(item => item.ShowName);
          arr2 = arr2.filter((value, index) => arr2.indexOf(value) === index);
          setShowNameFilters(arr2.map(item => ({ text: item, value: item })));
          // 过滤系统类型SystemType
          let arr3 = res.data.map(item => item.SystemType);
          arr3 = arr3.filter((value, index) => arr3.indexOf(value) === index);
          setSystemTypeFilters(arr3.map(item => ({ text: item, value: item })));
        } else {
          notification.error({
            message: '数据获取失败',
            description: res.msg,
          });
        }
        setLoading(false);
      })
      .catch(err => {
        message.error(err);
        setLoading(false);
      });
  };
  // DatePicker改变点击确定时
  const changeStartTime = time => {
    setStartTime(time);
  };
  const changeEndTime = time => {
    setEndTime(time);
  };
  // 近1/6/12/24小时
  const setTime = time => {
    setEndTime(moment(new Date(), 'YYYY-MM-DD HH:mm:ss'));
    setStartTime(
      moment(
        new Date(new Date().getTime() - time * 60 * 60 * 1000),
        'YYYY-MM-DD HH:mm:ss',
      ),
    );
  };
  const handleReset = () => {
    setStartTime(moment().startOf('week'));
    setFilteredValue([]);
  };
  const onChangeInput = filters => {
    console.log('filters', filters);
    setFilteredValue(filters.LoginName, filters.ShowName, filters.SystemType);
  };
  return (
    <>
      <div className={styles.loginLog}>
        <Row className={styles.head}>
          <Col span={24}>
            <span style={{ lineHeight: 2 }}>时间：</span>
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="起始时间"
              value={startTime}
              onChange={changeStartTime}
              allowClear={false}
            />
            <SwapRightOutlined style={{ verticalAlign: '0.125em' }} />
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="结束时间"
              value={endTime}
              onChange={changeEndTime}
              style={{ marginRight: '10px' }}
              allowClear={false}
            />
            <Button onClick={() => setTime(1)}>近1小时</Button>
            <Button onClick={() => setTime(6)}>近6小时</Button>
            <Button onClick={() => setTime(24)}>近1天</Button>
            <Button onClick={() => setTime(24 * 7)}>近1周</Button>
            <Button onClick={() => setTime(14 * 24)}>近2周</Button>
            <Button onClick={() => setTime(30 * 24)}>近1月</Button>
            <Button
              icon={<SyncOutlined className={styles.icon} />}
              onClick={handleReset}
              style={{
                marginLeft: '25px',
                verticalAlign: 'middle',
                marginTop: '-3px',
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
        <Spin spinning={loading} tip="loading">
          <div className={styles.table}>
            <Table
              size="small"
              bordered
              columns={columns}
              dataSource={data0}
              scroll={{ x: 'max-content', y: 'calc(100vh - 230px)' }}
              pagination={{
                showTotal: (total, range) =>
                  `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 20,
                showQuickJumper: true,
                showSizeChanger: true,
              }}
              onChange={onChangeInput}
            />
          </div>
        </Spin>
      </div>
    </>
  );
};
export default LoginLog;
