import React, { useEffect, useState } from 'react';
import { Modal, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment/moment';
import { queryDeviceRunState } from '@/services/afterSales/afterSales';

interface editProps {
  visible: boolean;
  editCallback: () => void;
  params: any;
}

interface DataType {
  created_at: string;
  start_time: string;
  end_time: string;
  duration: number;
  record_id: string;
}

/**
 * 设备运行历史
 * @param props
 * @constructor
 */
const DeviceHistory: React.FC<editProps> = (props) => {
  const { params, visible, editCallback } = props;
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);

  // 设备运行历史
  const onHistory = () => {
    setLoading(true);
    const data = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      device_id: params.device_code,
    };
    queryDeviceRunState(data).then((res) => {
      if (res && res.code === 0) {
        setList(res.data.list || []);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    if (params) {
      onHistory();
    }
  }, []);

  const tableChange = (page: any) => {
    setLoading(true);
    const data = {
      q: 'page',
      current: page.current,
      pageSize: page.pageSize,
      device_id: params.device_code,
    };
    queryDeviceRunState(data).then((res) => {
      if (res && res.code === 0) {
        setList(res.data.list || []);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, _row: any, index: number) => index + 1,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (v) => v && <span>{moment(v).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '开机时间',
      dataIndex: 'start_time',
      key: 'start_time',
      render: (v) => v && <span>{moment(v).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '关机时间',
      dataIndex: 'end_time',
      key: 'end_time',
      render: (v) => v && <span>{moment(v).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '运行时长（小时）',
      dataIndex: 'duration',
      key: 'duration',
    },
  ];

  return (
    <Modal
      title="设备运行历史"
      width={800}
      footer={null}
      open={visible}
      onCancel={() => {
        editCallback();
      }}
    >
      <Table
        columns={columns}
        dataSource={list}
        rowKey={(record) => record.record_id}
        pagination={pagination}
        loading={loading}
        onChange={tableChange}
      />
    </Modal>
  );
};
export default DeviceHistory;
