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

interface editPros {
  visible: boolean;
  editCallback: () => void;
  recordId: any;
}

interface DataType {
  name: string;
  home_name: number;
  type_name: string;
  creator_name: string;
  description_expr: string;
  record_id: string;
}

const SceneHistory: React.FC<editPros> = (props) => {
  const { visible, editCallback, recordId } = props;
  const [dataList, setDataList] = useState([]);
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [loading, setLoading] = useState(false);

  const getHistoryList = () => {
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      scene_id: recordId,
    };
    queryScenesHis(params).then((res: any) => {
      if (res && res.code === 0) {
        const list = res.data.list || [];
        setDataList(list);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    setLoading(true);
    getHistoryList();
  }, []);

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

  const onOk = () => {};

  const onCancel = () => {
    editCallback();
  };

  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) => {
        return v && moment(v).format('YYYY-MM-DD HH:mm');
      },
    },
    {
      title: '触发条件',
      dataIndex: 'trigger_condition',
      key: 'trigger_condition',
    },
    {
      title: '执行结果',
      dataIndex: 'result',
      key: 'result',
    },
  ];

  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => {
      return <span> 共 {total}条 </span>;
    },
    ...pagination,
  };

  return (
    <Modal title="历史记录" open={visible} onOk={onOk} onCancel={onCancel} width={1000}>
      <Table
        columns={columns}
        dataSource={dataList}
        rowKey={(record) => record.record_id}
        pagination={paginationProps}
        loading={loading}
        onChange={tableChange}
      />
    </Modal>
  );
};
export default SceneHistory;
