import React, { useState, useEffect, useRef } from 'react';
import {
  Table,
  Button,
  notification,
  DatePicker,
  message,
  Tooltip,
  Tag,
  Modal,
  Select,
  Radio,
  Form,
  Pagination,
} from 'antd';
import moment from 'moment';
import styles from './LookModal.less';
import { GetIISAgentSite, QueryIISAgentCalllog } from '@/services/scheduledTasks/api';

const { RangePicker } = DatePicker;
const LookModal = props => {
  const { visible, onCancel, keepTableList } = props;
  const [form] = Form.useForm(null);
  const [currentTime, setCurrentTime] = useState('昨天');
  const [siteData, setSiteData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const tableList = useRef({
    pageSize: 20,
    pageIndex: 1,
    total: '',
    beginDate: `${moment()
      .subtract(1, 'days')
      .format('YYYY-MM-DD')} 00:00`,
    endDate: `${moment()
      .subtract(1, 'days')
      .format('YYYY-MM-DD')} 23:59`,
    jobName: '',
    state: '',
    siteName: '',
  });

  // 使用ref来确定一些在组件更新的时候不需要更改的变量
  const fixedVariable = useRef(['昨天', '今天', '上周', '本周', '本月', '上月', '自定义']);

  useEffect(() => {
    if (visible) {
      getSiteList();
      getLogList();
    }
  }, [visible]);

  const getSiteList = () => {
    GetIISAgentSite().then(res => {
      if (res.code === 0) {
        setSiteData(res.data);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const getLogList = val => {
    if (tableList.current.beginDate === '' && tableList.current.endDate === '') {
      message.warning('请先选择时间！');
      return;
    }
    if (!val) {
      tableList.current.pageIndex = 1;
    }
    QueryIISAgentCalllog(tableList.current).then(res => {
      if (res.code === 0) {
        tableList.current.total = res.data.count;
        setTableData(res.data.data);
      }
    });
  };

  // 时间选择
  const timeChoose = type => {
    setCurrentTime(type);
    switch (type) {
      case '全部':
        tableList.current.beginDate = '';
        tableList.current.endDate = '';
        break;
      case '今天':
        tableList.current.beginDate = `${moment().format('YYYY-MM-DD')} 00:00`;
        tableList.current.endDate = `${moment().format('YYYY-MM-DD')} 23:59`;
        break;
      case '昨天':
        tableList.current.beginDate = `${moment()
          .subtract(1, 'days')
          .format('YYYY-MM-DD')} 00:00`;
        tableList.current.endDate = `${moment()
          .subtract(1, 'days')
          .format('YYYY-MM-DD')} 23:59`;
        break;
      case '本周':
        tableList.current.beginDate = `${moment()
          .week(moment().week())
          .startOf('week')
          .format('YYYY-MM-DD')} 00:00`;
        tableList.current.endDate = `${moment()
          .week(moment().week())
          .endOf('week')
          .format('YYYY-MM-DD')} 23:59`;
        break;
      case '上周':
        tableList.current.beginDate = `${moment()
          .week(moment().week() - 1)
          .startOf('week')
          .format('YYYY-MM-DD')} 00:00`;
        tableList.current.endDate = `${moment()
          .week(moment().week() - 1)
          .endOf('week')
          .format('YYYY-MM-DD')} 23:59`;
        break;
      case '本月':
        tableList.current.beginDate = `${moment()
          .month(moment().month())
          .startOf('month')
          .format('YYYY-MM-DD')} 00:00`;
        tableList.current.endDate = `${moment()
          .month(moment().month())
          .endOf('month')
          .format('YYYY-MM-DD')} 23:59`;
        break;
      case '上月':
        tableList.current.beginDate = `${moment()
          .month(moment().month() - 1)
          .startOf('month')
          .format('YYYY-MM-DD')} 00:00`;
        tableList.current.endDate = `${moment()
          .month(moment().month() - 1)
          .endOf('month')
          .format('YYYY-MM-DD')} 23:59`;

        break;
      case '今年':
        tableList.current.beginDate = `${moment()
          .year(moment().year())
          .startOf('year')
          .format('YYYY-MM-DD')} 00:00`;
        tableList.current.endDate = `${moment()
          .year(moment().year())
          .endOf('year')
          .format('YYYY-MM-DD')} 23:59`;
        break;
      case '去年':
        tableList.current.beginDate = `${moment()
          .year(moment().year() - 1)
          .startOf('year')
          .format('YYYY-MM-DD')}00:00`;
        tableList.current.endDate = `${moment()
          .year(moment().year() - 1)
          .endOf('year')
          .format('YYYY-MM-DD')}23:59`;
        break;
      default:
        tableList.current.beginDate = '';
        tableList.current.endDate = '';
        break;
    }
    if (tableList.current.beginDate !== '' && tableList.current.endDate !== '') {
      getLogList();
    }
  };

  // 自定义时间日期变化函数
  const timeChange = value => {
    tableList.current.beginDate = `${value[0].format('YYYY-MM-DD')} 00:00`;
    tableList.current.endDate = `${value[1].format('YYYY-MM-DD')} 23:59`;
    getLogList();
  };

  const columns = [
    {
      title: '请求时间',
      dataIndex: '日志时间',
      key: '日志时间',
      width: 100,
      fixed: 'center',
      render: text => <Tooltip title={text}>{text}</Tooltip>,
    },
    {
      title: '站点名称',
      dataIndex: '站点名称',
      key: '站点名称',
      align: 'center',
      width: 200,
      onCell: () => ({
        style: {
          maxWidth: 200,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
        },
      }),
      render: text => <Tooltip title={text}>{text}</Tooltip>,
    },
    {
      title: '计划名称',
      dataIndex: '请求名称',
      key: '请求名称',
      align: 'center',
      width: 150,
      onCell: () => ({
        style: {
          maxWidth: 200,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
        },
      }),
      render: text => <Tooltip title={text}>{text}</Tooltip>,
    },
    {
      title: 'URL',
      dataIndex: '请求URL',
      key: '请求URL',
      align: 'center',
      width: 180,
      onCell: () => ({
        style: {
          maxWidth: 180,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
        },
      }),
      render: text => <Tooltip title={text}>{text}</Tooltip>,
    },
    {
      title: '状态',
      dataIndex: '请求状态',
      key: '请求状态',
      align: 'center',
      width: 80,
    },
    {
      title: '耗时（ms）',
      dataIndex: '耗时',
      key: '耗时',
      align: 'center',
      width: 150,
      onCell: () => ({
        style: {
          maxWidth: 150,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
        },
      }),
      render: text => <Tooltip title={text}>{text}</Tooltip>,
    },
    {
      title: '返回结果',
      dataIndex: '返回结果',
      key: '返回结果',
      align: 'center',
      width: 300,
      onCell: () => ({
        style: {
          maxWidth: 300,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
        },
      }),
      render: text => <Tooltip title={text}>{text}</Tooltip>,
    },
  ];

  const paginationChange = (page, pageSizes) => {
    tableList.current.pageSize = pageSizes;
    tableList.current.pageIndex = page;
    getLogList('flag');
  };

  const siteChange = e => {
    tableList.current.siteName = e;
    getLogList();
  };

  const planChange = e => {
    tableList.current.jobName = e;
    getLogList();
  };

  const stateChange = e => {
    tableList.current.state = e;
    getLogList();
  };

  return (
    <Modal title="调用日志" visible={visible} onCancel={onCancel} width="90%" footer={false}>
      <div className={styles.lookModal}>
        <div className={styles.header}>
          <span>时间选择：</span>
          <Radio.Group value={currentTime} className={styles.radioList}>
            {fixedVariable.current.map(v => (
              <Radio.Button
                value={v}
                key={v}
                onClick={() => {
                  timeChoose(v);
                }}
              >
                {v}
              </Radio.Button>
            ))}
          </Radio.Group>
          {currentTime === '自定义' ? <RangePicker showToday onChange={timeChange} /> : ''}
          <div className={styles.select}>
            <span>站点名称：</span>
            <Select
              style={{ width: '175px' }}
              allowClear
              placeholder="请选择站点名称"
              onChange={e => siteChange(e)}
            >
              {siteData && siteData.map(v => <Select.Option value={v}>{v}</Select.Option>)}
            </Select>
          </div>
          <div className={styles.select}>
            <span>计划名称：</span>
            <Select
              style={{ width: '155px' }}
              allowClear
              placeholder="请选择任务性质"
              onChange={e => planChange(e)}
            >
              {keepTableList.map(v => (
                <Select.Option value={v.Name}>{v.Name}</Select.Option>
              ))}
            </Select>
          </div>
          <div className={styles.select}>
            <span>请求状态:</span>
            <Select
              style={{ width: '155px', marginLeft: '10px' }}
              allowClear
              placeholder="请选择请求状态"
              onChange={e => stateChange(e)}
            >
              <Select.Option value="">全部</Select.Option>
              <Select.Option value={true}>成功</Select.Option>
              <Select.Option value={false}>异常</Select.Option>
            </Select>
          </div>
        </div>
        <div className={styles.table}>
          <Table
            size="small"
            bordered
            columns={columns}
            dataSource={tableData}
            scroll={{ y: 'calc(100% - 40px)' }}
            pagination={false}
          />
        </div>
        <div className={styles.footer}>
          <Pagination
            total={tableList.current.total}
            showTotal={(aa, range) =>
              `第${range[0]}-${range[1]} 条/共 ${tableList.current.total} 条`
            }
            pageSizeOptions={[10, 20, 40, 100]}
            current={tableList.current.pageIndex}
            onChange={paginationChange}
            size="small"
            pageSize={tableList.current.pageSize}
            showSizeChanger
          />
        </div>
      </div>
    </Modal>
  );
};

export default LookModal;
