import React, { useState, useEffect } from 'react';
import {
  DatePicker,
  Input,
  Table,
  Row,
  Col,
  Button,
  notification,
  message,
  Tooltip,
  Spin,
  Pagination,
} from 'antd';
import { SwapRightOutlined, SyncOutlined } from '@ant-design/icons';
import moment from 'moment';
import { get, PUBLISH_SERVICE } from '@/services/index';
import styles from './index.less';

const OmsLog = () => {
  const [loading, setLoading] = useState(false); // 源数据
  const [data, setData] = useState([]); // 源数据
  const [levelFilters, setLevelFilters] = useState([]); // 优先级筛选
  const [functionName, setFunctionName] = useState(''); // 接口名称筛选
  const [label, setLabel] = useState(''); // 标签筛选
  const [startTime, setStartTime] = useState(moment().startOf('month')); // 默认值当天0点
  const [filteredValue, setFilteredValue] = useState([]);
  const [endTime, setEndTime] = useState(
    moment(new Date(), 'YYYY-MM-DD HH:mm:ss'), // 默认值当前时间
  );
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [total, setTotal] = useState();
  const [pageSize, setPageSize] = useState(20);
  const [currentPage, setCurrentPage] = useState(1);

  const columns = [
    {
      title: '操作时间',
      dataIndex: 'LogTime',
      key: 'LogTime',
      width: 150,
      defaultSortOrder: 'descend',
      sortDirections: ['descend', 'ascend'],
      sorter: (a, b) => new Date(a.LogTime).getTime() - new Date(b.LogTime).getTime(),
    },
    {
      title: '接口名称',
      dataIndex: 'Function',
      key: 'Function',
      ellipsis: 'true',
      width: 300,
      render: item => searchStyle(item),
      // filters: functionNameFilters,
      // onFilter: (value, record) => record.functionName === value,
    },
    {
      title: '标签',
      dataIndex: 'Label',
      key: 'Label',
      ellipsis: 'true',
      width: 300,
      render: item => searchStyle1(item),
    },
    {
      title: '操作信息',
      dataIndex: 'ShortInfo',
      key: 'ShortInfo',
      onCell: () => ({
        style: {
          maxWidth: 800,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      render: record => (
        <Tooltip placement="topLeft" title={record}>
          {record}
        </Tooltip>
      ),
    },
    {
      title: '优先级',
      dataIndex: 'Level',
      key: 'Level',
      width: 100,
      filters: levelFilters,
      onFilter: (value, record) => record.Level === value,
      filteredValue,
      render: record => {
        if (record === 3) {
          return <span style={{ color: '#ff7875' }}>高</span>;
        }
        if (record === 2) {
          return <span style={{ color: '#faad14' }}>中</span>;
        }
        if (record === 1) {
          return <span style={{ color: '#52c41a' }}>低</span>;
        }
        return record;
      },
    },
  ];

  // 模糊查询匹配的样式
  const searchStyle = val => {
    let n;
    if (showSearchStyle) {
      n = val.replace(
        new RegExp(functionName, 'g'),
        `<span style='color:red'>${functionName}</span>`,
      );
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };

  const searchStyle1 = val => {
    let n;
    if (showSearchStyle) {
      n = val.replace(new RegExp(label, 'g'), `<span style='color:red'>${label}</span>`);
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };

  // 在起止时间任意一个变化后获取数据
  useEffect(() => {
    if (startTime && endTime) {
      setLoading(true);
      getData();
    }
  }, [startTime, endTime]);
  const getData = () => {
    get(`${PUBLISH_SERVICE}/LogCenter/GetOmsCustomerLog`, {
      logType: 'operationLog',
      StartDateTime: startTime.format('YYYY-MM-DD HH:mm:ss'),
      EndDate: endTime.format('YYYY-MM-DD HH:mm:ss'),
      function: functionName,
      label,
      PageIndex: 1,
      PageSize: 20,
    })
      .then(res => {
        if (res.code === 0) {
          // setData(res.root.filter(item => item.label!=="ServiceInput"&&item.label!=="ServiceReturn"));
          if (!res.data) {
            setData([]);
          } else {
            const result = res.data.list;
            setTotal(res.data.TotalCount);
            setPageSize(20);
            setCurrentPage(1);
            setData(
              result.map((item, index) => {
                item.key = index;
                return item;
              }),
            );
            console.log(result);
            // 过滤优先级
            let arr1 = result.map(item => item.Level);
            arr1 = arr1.filter((value, index) => arr1.indexOf(value) === index);
            setLevelFilters(arr1.map(item => ({ text: item, value: item })));
          }
        } else {
          notification.error({
            message: '数据获取失败',
            description: res.message,
          });
        }
        setLoading(false);
      })
      .catch(err => {
        message.error(err);
        setLoading(false);
      });
  };

  const getData1 = (page, size) => {
    get(`${PUBLISH_SERVICE}/LogCenter/GetOmsCustomerLog`, {
      logType: 'operationLog',
      StartDateTime: startTime.format('YYYY-MM-DD HH:mm:ss'),
      EndDate: endTime.format('YYYY-MM-DD HH:mm:ss'),
      function: functionName,
      label,
      PageIndex: page,
      PageSize: size,
    })
      .then(res => {
        if (res.code === 0) {
          // setData(res.root.filter(item => item.label!=="ServiceInput"&&item.label!=="ServiceReturn"));
          if (!res.data) {
            setData([]);
          } else {
            const result = res.data.list;
            setTotal(res.data.TotalCount);
            setData(
              result.map((item, index) => {
                item.key = index;
                return item;
              }),
            );
            console.log(result);
            // 过滤优先级
            let arr1 = result.map(item => item.Level);
            arr1 = arr1.filter((value, index) => arr1.indexOf(value) === index);
            setLevelFilters(arr1.map(item => ({ text: item, value: item })));
          }
        } else {
          notification.error({
            message: '数据获取失败',
            description: res.message,
          });
        }
        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('month'));
    setEndTime(moment(new Date(), 'YYYY-MM-DD HH:mm:ss'));
    setFunctionName('');
    setFilteredValue([]);
    setLabel('');
    setShowSearchStyle(false);
  };
  const onChangeInput = filters => {
    console.log('filters', filters);
    setFilteredValue(filters.Level);
  };

  const paginationChange = (page, pageSizes) => {
    getData1(page, pageSizes);
    setCurrentPage(page);
    setPageSize(pageSizes);
  };
  return (
    <>
      <div className={styles.omsLog}>
        <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>
            <span style={{ marginLeft: '20px' }}>接口查询:</span>
            <Input
              style={{ width: '200px' }}
              placeholder="请输入接口名称"
              onChange={e => {
                setFunctionName(e.target.value);
              }}
              value={functionName}
            />
            <span style={{ marginLeft: '20px' }}>标签查询:</span>
            <Input
              style={{ width: '200px' }}
              placeholder="请输入标签"
              onChange={e => {
                setLabel(e.target.value);
              }}
              value={label}
            />
            <Button
              type="primary"
              style={{ marginLeft: '10px' }}
              onClick={() => {
                getData();
                setShowSearchStyle(true);
              }}
            >
              查询
            </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={data}
              scroll={{ x: 'max-content', y: 'calc(100vh - 230px)' }}
              pagination={false}
              onChange={onChangeInput}
            />
          </div>
          <Pagination
            style={{ display: 'flex', justifyContent: 'end', padding: '10px' }}
            total={total}
            showTotal={(aa, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`}
            defaultPageSize={pageSize}
            defaultCurrent={1}
            pageSizeOptions={[10, 20, 40, 100]}
            current={currentPage}
            onChange={paginationChange}
            size="small"
            showQuickJumper
          />
        </Spin>
      </div>
    </>
  );
};
export default OmsLog;