import React, { useState, useEffect, useImperativeHandle } from 'react'
import { Table, Space, message } from 'antd'
import { getJoblog, refreshLogsStatus } from '../services'
import moment from 'moment'
import { useNavigate } from 'react-router-dom'

let timeout = null

const DatasourceLog = ({ onRef, logId }) => {
  // 初始化日志列表
  const [logList, setLogList] = useState([])
  // 表格Loading状态
  const [dataLoading, setDataLoading] = useState(false)

  const [currentPage, setCurrentPage] = useState(1)
  const [currentPageSize, setCurrentPageSize] = useState(10)
  const [dataTotal, setDataTotal] = useState(0)

  const navigate = useNavigate()

  const changeTask = () => {}

  // 暴露更新列表方法
  useImperativeHandle(onRef, () => {
    return {
      updateLogList: fetchJoblog,
    }
  })

  const checkLog = id => {
    navigate('/datasource/log-watcher', {
      state: { id },
    })
  }
  const columns = [
    {
      title: '同步ID',
      dataIndex: 'jobId',
      key: 'jobId',
    },
    {
      title: '任务描述',
      dataIndex: 'jobDesc',
      key: 'jobDesc',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
    },
    {
      title: '同步状态',
      dataIndex: 'handleResult',
      key: 'handleResult',
      render: code => (
        <span
          style={{
            color: code === 3 ? '#FF4D4F' : code === 2 ? '#52C41A' : '#4A4A4A',
          }}>
          {code === 3
            ? '失败'
            : code === 2
            ? '成功'
            : code === 1
            ? '运行中'
            : code === 0
            ? '队列中'
            : '暂无'}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'operation',
      render: (_, record) => (
        <Space size="middle">
          <span
            onClick={() => {
              checkLog(record.key)
            }}
            style={{ color: '#1881DA', cursor: 'pointer' }}>
            查看
          </span>
          {/* <a href="/#" onClick={editData} style={{ color: '#1881DA' }}>
            编辑
          </a> */}
          {/* <span
            onClick={() => {
              changeTask(record.key)
            }}
            style={{ color: '#1881DA', cursor: 'pointer' }}>
            终止任务
          </span> */}
        </Space>
      ),
    },
  ]

  const fetchJoblog = async (page = 1, pageSize = 10) => {
    setDataLoading(true)
    const { data } = await getJoblog({
      page: page,
      size: pageSize,
      id: logId,
    })
    if (data.code === 200) {
      setDataTotal(data.data.extra_data.total)
      setCurrentPage(data.data.extra_data.page)
      setCurrentPageSize(data.data.extra_data.size)
      const refreshLogs = []
      const list = data.data.item.map(item => {
        if ([0, 1].includes(item.execute_result)) {
          refreshLogs.push(item.id)
        }
        return {
          key: item.id,
          jobId: item.job_id,
          jobDesc: item.job_desc,
          afJobId: item.af_job_id,
          runId: item.run_id,
          startTime: item.start_time
            ? moment(Math.round(item.execute_time) * 1000).format(
                'YYYY.MM.DD HH:mm:ss'
              )
            : '无',
          handleResult: item.result,
        }
      })
      setLogList(list)
      refreshStatus(refreshLogs)
    }
    setDataLoading(false)
  }

  const refreshStatus = async refreshLogs => {
    if (refreshLogs.length !== 0) {
      const { data } = await refreshLogsStatus(refreshLogs.toString())
      if (data.code === 200) {
        const list = []
        let logs = []
        const keys = Object.keys(data.data)
        keys.forEach(item => {
          if ([2, 3].includes(data.data[item])) {
            logs = logList.map(logData => {
              if (logData.id === item) {
                logData.execute_result = data.data[item]
              }
              return logData
            })
          } else {
            list.push(item)
          }
        })
        if (logs.length !== 0) {
          setLogList(logs)
        }
        timeout = setTimeout(() => {
          refreshStatus(list)
        }, 10000)
      } else {
        message.error(data.msg)
      }
    }
  }

  const pageChange = (page, pageSize) => {
    fetchJoblog(page, pageSize)
  }

  useEffect(() => {
    fetchJoblog()
  }, [logId])

  useEffect(() => {
    return () => {
      clearTimeout(timeout)
    }
  }, [])

  return (
    <Table
      columns={columns}
      dataSource={logList}
      bordered
      loading={dataLoading}
      pagination={{
        current: currentPage,
        total: dataTotal,
        pageSize: currentPageSize,
        onChange: pageChange,
      }}
    />
  )
}

export default DatasourceLog
