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'
import { useRouteMatch } from 'react-router-dom'

const intervals: Array<any> = []

export default function ModelList({ className }: any) {
  const match = useRouteMatch()
  const sid = (match?.params as any).sid
  
  intervals.forEach(interval => clearInterval(interval))
  const { referData, Element, modelDispatch, models, referItem } = GrentReducer({
    judgeUrl: '/cesium/raster/coordJudge/',
    delUrl: '/cesium/raster/remove/',
    getUrl: '/cesium/raster/list',
    sectionUrl: '/cesium/raster/slice/',
    transferUrl: '/cesium/raster/publish/',
    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, sid, `/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;
  }

  let coord = coorstr.split(',').length > 1 ? coorstr.split(',') : []

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