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 moment from 'moment';
import 'moment/dist/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { post, PUBLISH_SERVICE } from '@/services/index';
import styles from './index.less';
const { RangePicker } = DatePicker;

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('month')); // 默认值当天0点
  const [endTime, setEndTime] = useState(
    moment(new Date(), 'YYYY-MM-DD HH:mm:ss'), // 默认值当前时间
  );
  const [allTime, setAllTime] = useState([
    moment().startOf('month'),
    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',
      width: 300,
    },
    {
      title: '登录名',
      dataIndex: 'LoginName',
      key: 'LoginName',
      filters: LoginNameFilters,
      onFilter: (value, record) => record.LoginName === value,
      filteredValue,
    },
    {
      title: 'IP',
      dataIndex: 'IP',
      key: 'IP',
    },
    {
      title: 'IP属地',
      dataIndex: 'IPTerritory',
      key: 'IPTerritory',
      width: 250,
    },
    {
      title: '用户名',
      dataIndex: 'ShowName',
      key: 'ShowName',
      filters: ShowNameFilters,
      onFilter: (value, record) => record.ShowName === value,
      filteredValue,
    },
    {
      title: '系统类型',
      dataIndex: 'Client',
      key: 'Client',
      width: 300,
      filters: SystemTypeFilters,
      onFilter: (value, record) => record.Ciient === value,
      filteredValue,
    },
    // {
    //   title: '终端',
    //   dataIndex: 'Terminal',
    //   key: 'Terminal',
    // },
  ];
  // 在起止时间任意一个变化后获取数据
  useEffect(() => {
    if (allTime) {
      setLoading(true);
      getData();
    }
  }, [allTime]);
  const getData = () => {
    post(`${PUBLISH_SERVICE}/LogCenter/GetLoginLog`, {
      DateFrom: allTime[0].format('YYYY-MM-DD HH:mm:ss'),
      DateTo: allTime[1].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 })));
          // 过滤系统类型Ciient
          let arr3 = res.data.map(item => item.Ciient);
          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);
  };

  const changeTime = time => {
    setAllTime(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'),
    );
    setAllTime([
      moment(new Date(new Date().getTime() - time * 60 * 60 * 1000), 'YYYY-MM-DD HH:mm:ss'),
      moment(new Date(), 'YYYY-MM-DD HH:mm:ss'),
    ]);
  };
  const handleReset = () => {
    setStartTime(moment().startOf('week'));
    setAllTime([moment().startOf('week'), moment(new Date(), 'YYYY-MM-DD HH:mm:ss')]);
    setFilteredValue([]);
  };
  const onChangeInput = filters => {
    // console.log('filters', filters);
    setFilteredValue(filters.LoginName, filters.ShowName, filters.Ciient);
  };
  return (
    <>
      <div className={styles.loginLog}>
        <Row className={styles.head}>
          <Col span={24}>
            <span style={{ lineHeight: 2 }}>时间：</span>
            <RangePicker
              locale={locale}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              onChange={changeTime}
              value={allTime}
              allowClear={false}
            />
            {/* <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)} style={{ marginLeft: '20px' }}>
              近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;
