import { ServiceVersionData } from '@/pages/ModelDeployment/types';
import { getServiceVersionLogReq } from '@/services/modelDeployment';
import { to } from '@/utils/promise';
import { DoubleRightOutlined } from '@ant-design/icons';
import { Button, DatePicker, type TimeRangePickerProps } from 'antd';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import styles from './index.less';
const { RangePicker } = DatePicker;

// 滚动到底部
// const scrollToBottom = (smooth: boolean = true) => {
//   const element = document.getElementById('server-log');
//   if (element) {
//     const optons: ScrollToOptions = {
//       top: element.scrollHeight,
//       behavior: smooth ? 'smooth' : 'instant',
//     };
//     element.scrollTo(optons);
//   }
// };

type LogData = {
  log_content: string;
  end_time: string;
  start_time: string;
};

type ServerLogProps = {
  info?: ServiceVersionData;
};

function ServerLog({ info }: ServerLogProps) {
  const [dateRange, setDateRange] = useState<NonNullable<TimeRangePickerProps['value']>>([
    dayjs().add(-1, 'h'),
    dayjs(),
  ]);
  const [logTime, setLogTime] = useState<[string, string]>([
    `${dateRange[0]!.valueOf() * Math.pow(10, 6)}`,
    `${dateRange[1]!.valueOf() * Math.pow(10, 6)}`,
  ]);
  const [logData, setLogData] = useState<LogData[]>([]);
  const [hasMore, setHasMore] = useState(false);

  const rangePresets: TimeRangePickerProps['presets'] = [
    { label: '最近 1 小时', value: [dayjs().add(-1, 'h'), dayjs()] },
    { label: '最近 2 小时', value: [dayjs().add(-2, 'h'), dayjs()] },
    { label: '最近 3 小时', value: [dayjs().add(-3, 'h'), dayjs()] },
    { label: '最近 1 天', value: [dayjs().add(-1, 'd'), dayjs()] },
    { label: '最近 2 天', value: [dayjs().add(-2, 'd'), dayjs()] },
    { label: '最近 7 天', value: [dayjs().add(-7, 'd'), dayjs()] },
    { label: '最近 14 天', value: [dayjs().add(-14, 'd'), dayjs()] },
    { label: '最近 30 天', value: [dayjs().add(-30, 'd'), dayjs()] },
  ];

  useEffect(() => {
    // 获取服务日志
    const getModelDeploymentLog = async () => {
      if (info && logTime && logTime.length === 2) {
        const params = {
          start_time: logTime[0],
          end_time: logTime[1],
          id: info.id,
        };
        const [res] = await to(getServiceVersionLogReq(params));
        if (res && res.data) {
          setLogData((prev) => [...prev, res.data]);
          setHasMore(!!res.data.log_content);
          // setTimeout(() => {
          //   scrollToBottom();
          // }, 100);
        }
      }
    };
    getModelDeploymentLog();
  }, [info, logTime]);

  // 搜索
  const handleSearch = () => {
    setLogData([]);
    setHasMore(false);
    setLogTime([
      `${dateRange[0]!.valueOf() * Math.pow(10, 6)}`,
      `${dateRange[1]!.valueOf() * Math.pow(10, 6)}`,
    ]);
  };

  // 加载更多日志
  const loadMoreLog = () => {
    const lastLog = logData[logData.length - 1];
    setLogTime([lastLog.start_time, lastLog.end_time]);
  };

  // 禁止选择今天之后和之前31天的日期
  const disabledDate: TimeRangePickerProps['disabledDate'] = (currentDate) => {
    return (
      Date.now() - currentDate.valueOf() < 0 ||
      Date.now() - currentDate.valueOf() > 31 * 24 * 60 * 60 * 1000
    );
  };

  // 处理日期变化
  const handleRangeChange: TimeRangePickerProps['onChange'] = (dates) => {
    if (dates) {
      setDateRange(dates);
    }
  };

  const logContent = logData.map((v) => v.log_content).join('');

  return (
    <div className={styles['server-log']}>
      <div>
        <RangePicker
          presets={rangePresets}
          showTime
          value={dateRange}
          format="YYYY-MM-DD HH:mm:ss"
          onChange={handleRangeChange}
          allowClear={false}
          disabledDate={disabledDate}
        />
        <Button type="default" style={{ marginLeft: '20px' }} onClick={handleSearch}>
          查询
        </Button>
      </div>
      {logContent ? (
        <div className={styles['server-log__data']} id="server-log">
          <div>{logContent}</div>
          {hasMore && (
            <Button
              type="text"
              className={styles['server-log__data__more']}
              style={{ color: 'white' }}
              onClick={loadMoreLog}
            >
              更多
              <DoubleRightOutlined rotate={90} />
            </Button>
          )}
        </div>
      ) : (
        <div className={classNames(styles['server-log__data'], styles['server-log__data--empty'])}>
          暂无日志
        </div>
      )}
    </div>
  );
}

export default ServerLog;
