import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import ScrollLoading from '@/components/ScrollLoading';
import { getHistoryRecord } from '@/services/SmartOps';
import { GetTokenFromUrl, UnityAction } from '@/utils/utils';
import { useNavigate, useParams, useRequest } from '@umijs/max';
import { Button, DatePicker, Select, Table } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import styles from './index.less';

const { RangePicker } = DatePicker;
const { Option } = Select;

const HistoryRecord = (props) => {
  const { projectId } = useParams();
  const navigate = useNavigate();

  const convertObject2FormData = (params) => {
    const formData = new FormData();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== null && value !== undefined && value !== NaN) {
        formData.append(key, value);
      }
    });
    return formData;
  };

  const defaultParams = {
    project_id: Number(projectId),
    start_time: '',
    end_time: '',
    page: 1,
    page_size: 20,
  };
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({});
  const [queryParams, setQueryParams] = useState(defaultParams);

  const [formData, setFormData] = useState(
    convertObject2FormData(defaultParams),
  );

  const { run: getList, loading } = useRequest(
    (params = formData) => getHistoryRecord(params),
    {
      onSuccess: (res) => {
        if (res.pagenation?.current == 1) {
          setData(res?.list);
        } else {
          setData([...data, ...res?.list]);
        }
        setPagination(res.pagenation);
      },
    },
  );

  const columns = [
    {
      title: '时间',
      dataIndex: 'CTime',
      key: 'CTime',
      render: (text) => {
        return dayjs(text).format('YYYY-MM-DD HH:mm') || '--';
      },
    },
    {
      title: '工况分析',
      dataIndex: 'Num1',
      key: 'Num1',
      render: (text) => {
        if (text === undefined || text === null) {
          return 0;
        }
        return text;
      },
    },
    {
      title: '设备分析',
      dataIndex: 'Num4',
      key: 'Num4',
      render: (text) => {
        if (text === undefined || text === null) {
          return '--';
        }
        return text;
      },
    },
    {
      title: '工艺分析',
      dataIndex: 'Num2',
      key: 'Num2',
      render: (text) => {
        if (!text) {
          return 0;
        } else {
          return text.split(',').length;
        }
      },
    },
    {
      title: '感知分析',
      dataIndex: 'Num3',
      key: 'Num3',
      render: (text) => {
        if (text === undefined || text === null) {
          return 0;
        }
        return text;
      },
    },

    {
      title: '操作',
      render: (record) => (
        <a
          onClick={() => {
            navigate(
              `/smart-ops/${projectId}?time=${record.CTime}&idList=${
                record.Num2
              }&patrolId=${record.PatrolId}&JWT-TOKEN=${GetTokenFromUrl()}`,
            );
          }}
        >
          详情
        </a>
      ),
    },
  ];

  const handleParamsChange = (key, value) => {
    const tempParams = {
      project_id: Number(projectId),
      start_time: queryParams.start_time || '',
      end_time: queryParams.end_time || '',
      page: queryParams.page || 1,
      page_size: queryParams.page_size || 20,
    };
    switch (key) {
      case 'date':
        if (value?.length === 2) {
          tempParams.start_time = dayjs(value[0]).format('YYYY-MM-DD 00:00:00');
          tempParams.end_time = dayjs(value[1]).format('YYYY-MM-DD 23:59:59');
        } else {
          tempParams.start_time = '';
          tempParams.end_time = '';
        }
        break;
      case 'page':
        tempParams.page = value;
        handleSearch(convertObject2FormData(tempParams));
        break;
      default:
        break;
    }
    setQueryParams(tempParams);
  };

  const handleSearch = (params) => {
    if (params !== undefined) {
      getList(params);
      return;
    }
    getList(formData);
  };

  useEffect(() => {
    const tempFormData = convertObject2FormData(queryParams);
    // page变更自动请求接口
    setFormData(tempFormData);
  }, [queryParams]);

  useEffect(() => {
    UnityAction.sendMsg('EnterHistoryPage');
  }, []);

  return (
    <PageContent>
      <PageTitle returnable>历史记录</PageTitle>
      <div className={styles.searchContent}>
        日期：
        <RangePicker
          inputReadOnly
          className={styles.timePicker}
          onChange={(value) => handleParamsChange('date', value)}
        />
        <Button
          className={styles.marginLeft}
          type="primary"
          onClick={() => handleSearch()}
        >
          查询
        </Button>
      </div>
      <ScrollLoading
        height={182}
        loading={loading}
        pagination={pagination}
        handleLoadData={(current) => handleParamsChange('page', current)}
      >
        <Table dataSource={data} columns={columns} pagination={false} />
      </ScrollLoading>
    </PageContent>
  );
};
export default HistoryRecord;
