import React, { useState, useEffect, useMemo } 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 ReactEcharts from 'echarts-for-react';
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 [chartData, setChartData] = useState([]);
  const [showChart, setShowChart] = useState(true);

  const colorArr = ['#FFAB18',
    '#17B5F9',
    '#1975FF',
    '#56CF3A',
    '#7D5CD4',
    '#FF0060',
    '#CA4ED9',
    '#01CC9F',
    '#FF4C3E',
    '#E945D0',
    '#0EC6DC',
    '#63636D',
    '#66517F',
    '#996B6B',
    '#ACAFC6',
    '#FFAB18',
    '#17B5F9',
    '#1975FF',
    '#56CF3A',
    '#7D5CD4',
    '#FF0060',
    '#CA4ED9',
    '#01CC9F',
    '#FF4C3E',
    '#E945D0',
    '#0EC6DC',
    '#63636D',
    '#66517F',
    '#996B6B',
    '#ACAFC6',
    '#FFAB18',
    '#17B5F9',
    '#1975FF',
    '#56CF3A',
    '#7D5CD4',
    '#FF0060',
    '#CA4ED9',
    '#01CC9F',
    '#FF4C3E',
    '#E945D0',
    '#0EC6DC',
    '#63636D',
    '#66517F',
    '#996B6B',
    '#ACAFC6']

  console.log(colorArr, 'colorArrcolorArrcolorArr');

  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.Client === 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.tableData);
          let chartArr1 = res.data.chartData.map(item => item.clientName || item.client)
          let chartArr2 = res.data.chartData.map(item => item.count)
          let chartArr3 = res.data.chartData.map(item => {
            return {
              value: item.count,
              name: item.client,
            }
          });
          setChartData([chartArr1, chartArr2, chartArr3])
          // 过滤LoginName
          let arr1 = res.data.tableData.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.tableData.map(item => item.ShowName);
          arr2 = arr2.filter((value, index) => arr2.indexOf(value) === index);
          setShowNameFilters(arr2.map(item => ({ text: item, value: item })));
          // 过滤系统类型Client
          let arr3 = res.data.tableData.map(item => item.Client);
          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.Client);
  };

  const rightOption = useMemo(() => {
    return {
      xAxis: {
        type: 'category',
        data: chartData[0],
        // axisLabel: {
        //   interval: 0, //x轴文字全部显示
        //   formatter: function (params) {
        //     let newParamsName = ''
        //     const paramsNameNumber = params.length // 获取文数总长度
        //     const provideNumber = 8 //控制每行的字段
        //     const rowNumber = Math.ceil(paramsNameNumber / provideNumber)
        //     if (paramsNameNumber > provideNumber) {
        //       for (let p = 0; p < rowNumber; p++) {
        //         const start = p * provideNumber
        //         const end = start + provideNumber
        //         const tempStr = p === rowNumber - 1 ? params.substring(start, paramsNameNumber) :
        //           params.substring(start, end) + '\n'
        //         newParamsName += tempStr
        //       }
        //     } else {
        //       newParamsName = params
        //     }
        //     return newParamsName
        //   },
        // },
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          data: chartData[1],
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            formatter: params => {
              const total = chartData[1].reduce((acc, val) => acc + val, 0);
              const percentage = ((params.data / total) * 100).toFixed(2) + '%';
              return `${params.data}次 (${percentage})`;
            }
          },
          itemStyle: {
            color: function (params) {
              // 这里可以根据你的需求设置不同的颜色，例如根据数据值或索引
              return (colorArr[params.dataIndex])
            }
          }
        },
      ],
      tooltip: {
        trigger: 'item',
        show: true,
        formatter: '{b} : {c}次', // 展示的文字 类型+百分比
      },
    };
  }, [chartData])
  const leftOption = useMemo(() => {
    return {
      title: {
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
        show: true,
        formatter: '{b} : {c}次 {d}%', // 展示的文字 类型+百分比
      },
      legend: {
        orient: 'horizontal',
        left: 'center',
        top: '10%',
      },
      color: colorArr,
      series: [
        {
          name: '占比',
          type: 'pie',
          radius: '50%',
          data: chartData[2],
          label: {
            show: true,
            // formatter: '{b}次6666 : {d}%', // 展示的文字 类型+百分比
            position: 'outer', // 标签位置在饼图外部
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
          },
        },
      ]
    };
  }, [chartData])
  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)' }}
              scroll={{ x: 'max-content', y: `calc(100vh - ${showChart ? '630' : '230'}px)` }}
              pagination={{
                showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 20,
                showQuickJumper: true,
                showSizeChanger: true,
              }}
              onChange={onChangeInput}
            />
            <Button style={{ position: 'absolute', bottom: '2px', left: '10px' }} onClick={() => setShowChart(!showChart)}>{showChart ? '收起' : '展开'}</Button>
          </div>
          {
            showChart ? <div className={styles.chartDiv}>
              <div>
                <ReactEcharts style={{ width: '100%', height: '100%' }} option={leftOption} />
              </div>
              <div>
                <ReactEcharts style={{ width: '100%', height: '100%' }} option={rightOption} />
              </div>
            </div> : null
          }
        </Spin>
      </div>
    </>
  );
};
export default LoginLog;
