import React, { useEffect } from 'react';
import { Table } from 'antd';
import moment from 'moment';
import { useRequest } from 'umi';
import classnames from 'classnames';
import style from './style.less';
import { fetchDeviceFile } from '@/services/device';
import { fetchDocumentUrl } from '@/services/dict';

type FileTabProps = {
  deviceInfo: {
    [name: string]: any;
  };
};

const FileTab: React.FC<FileTabProps> = (props) => {
  const { deviceInfo } = props;
  const fileList = useRequest(fetchDeviceFile, { manual: true });

  const moveToNewUrl = useRequest(fetchDocumentUrl, {
    manual: true,
    onSuccess: (res) => {
      if (res) window.open(res);
    },
  });

  const deviceFile = [
    { title: '文件名称', dataIndex: 'name' },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      render: (val: number | string) => val && moment(val).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      dataIndex: 'path',
      render: (val: string) => val && <a onClick={() => moveToNewUrl.run(val)}>预览</a>,
    },
  ];

  useEffect(() => {
    if (deviceInfo?.id) fileList.run(deviceInfo?.id);
  }, [deviceInfo]);

  return (
    <div style={{ display: 'flex', padding: 10 }}>
      <div style={{ flex: 1 }} className="pos_aline_start">
        <div className={classnames(style.png_box, 'pos_center')}>
          <img
            src={deviceInfo?.imgUrls?.[0] || '/img/empty.png'}
            alt=""
            style={{ width: 220, height: 220 }}
          />
        </div>

        <div style={{ marginLeft: 20 }}>{deviceInfo?.description}</div>
      </div>
      <div style={{ flex: 1.8 }}>
        <Table
          rowKey={(record) => record.id}
          size="small"
          dataSource={fileList?.data || []}
          columns={deviceFile}
          scroll={{ y: 200 }}
        />
      </div>
    </div>
  );
};

export default FileTab;