import { useEffect, useState } from 'react'
import { Button, Flex, Modal } from 'antd'
import { read, utils } from 'xlsx'
import { uniqueId } from 'lodash-es'
import axios from 'axios'
import DataRender from './DataRender'

export default function ViewDataButtonModal({ data }: { data: any }) {
  const [open, setOpen] = useState(false)
  const [dataset, setDataset] = useState<any[]>([])
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    const workbook = async () => {
      setIsLoading(true)
      try {
        const file = JSON.parse(data.file)
        const res = await axios(file.url, { responseType: 'arraybuffer' })
        const workbook = read(res.data)
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData = utils.sheet_to_json(worksheet, { defval: '' })
        setDataset(jsonData)
      } catch (error) {
        console.error(error)
      }
      setIsLoading(false)
    }
    if (open) workbook()
  }, [open, data])

  const columns: any =
    dataset.length > 0
      ? Object.keys(dataset[0]).map((key) => ({
          title: key,
          dataIndex: key,
          align: 'center',
        }))
      : []

  const dataSource = dataset.map((item) => ({ ...item, pk_id: uniqueId() }))

  return (
    <>
      <Button color="primary" variant="text" onClick={() => setOpen(true)}>
        查阅
      </Button>
      <Modal title="查阅数据集" width={'80%'} open={open} footer={null} onCancel={() => setOpen(false)}>
        <Flex justify="space-between" style={{ marginBottom: 20 }}>
          <div>数据集名称:{data.name}</div>
          <div>共计:{data.number}条数据</div>
        </Flex>
        <DataRender rowKey={'pk_id'} dataSource={dataSource} columns={columns} loading={isLoading}></DataRender>
      </Modal>
    </>
  )
}
