import React, { useState } from 'react'
import GrentReducer from './grent'
import Upload from '../components/Upload'
import styles from './index.module.css'
import { sectionStepAction } from './ListState'
import Step from '../components/Upload/Step'
import Coor from './Coor'

const intervals: Array<any> = []

export default function ModelList({ className }: any) {
  intervals.forEach(interval => clearInterval(interval))
  const { referData, Element, modelDispatch, models, referItem } = GrentReducer({
    judgeUrl: '/raster/command/judge/coord/',
    delUrl: '/raster/delete/',
    getUrl: '/raster/list',
    sectionUrl: '/raster/command/osgeo/',
    transferUrl: '/raster/move/',
    ItemFn(model: Model) {
      if (model.status === 6) {
        return <Step step={model.sectStep ? model.sectStep : 0} />
      }
    },
    region: true
  })
  let [coorstr, setCoor] = useState('')

  async function getStep(model: Model) {
    let data = await sectionStepAction(modelDispatch, `/raster/progress/${model.id}/`, model)
    return data.data.progress
  };

  models.forEach((model: any) => {
    if (model.status !== 6) return;

    let interval = setInterval(async () => {
      let step = await getStep(model)
      if (model.sectStep !== step) {
        model.sectStep = step
        model = referItem(model)
        clearInterval(interval)

        if (model.sectStep === 100) {
          setTimeout(() => referData(), 1000)
        }
      }
    }, 1000)
    intervals.push(interval)
  })

  for (let i = 0; i < models.length; i++) {
    let model = models[i] as Model
    if (model.status !== 9) continue
    setTimeout(() => referData(), 1000)
    break;
  }

  return (
    <div className={className}>
      {Element}
      <div className={styles.uplayer + ' ' + styles.inuplayer} >
        <Coor coor={coorstr} onChange={(val: string) => setCoor(val)} />
        <Upload className={styles.uplayer} api='/raster/upload' body={{ coord: coorstr.split(',') }} check='/raster/check/' upHandle={referData} />
      </div>
    </div>
  )
}