import React, { useState } from 'react'
import GrentReducer from './grent'
import Upload from '../../components/Upload'
import { Link, useRouteMatch } from 'react-router-dom'
import styles from './index.module.css'
import { sectionStepAction } from './ListState'
import Step from '../../components/Upload/Step'
import Coor from './Coor'
import path from 'path'
import { fullRouteParams } from '../../util'


const intervals: Array<any> = []

export default function GeoList({ className }: any) {
  const match = useRouteMatch()
  const sid = (match?.params as any).sid

  intervals.forEach(interval => clearInterval(interval))
  const { referData, Element, models, referItem, modelDispatch } = GrentReducer({
    delUrl: '/cesium/vector/remove/',
    getUrl: '/cesium/vector/list',
    zipUrl: '/vector/unzip/',
    sectionUrl: '/cesium/vector/slice/',
    transferUrl: '/cesium/vector/publish',
    transformUrl: '/cesium/vector/toGeoJson/',
    judgeUrl: '/cesium/vector/coordJudge/',
    ItemFn (model: Model) {
      if (model.status === 6) {
        return <Step step={model.sectStep ? model.sectStep : 0} />
      } else if (model.status === 8 || model.status === 11 || model.status === 12) {
        return <Link to={fullRouteParams('/:sid/style/:id', {sid, id: model.id})} style={{ color: '#3e7cd3' }}>编辑样式</Link>
      }
    },
    region: true
  })

  let [dir, setDir] = useState('')
  let [coorstr, setCoor] = useState('')

  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(',') : []

  async function getStep(model: Model) {
    let data = await sectionStepAction(modelDispatch, sid, `/vector/progress/${model.id}/`, model)
    return data.data && 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)
  })

  function uploadFilter(files: Array<File>) {
    let susts = ['.shp', '.prj', '.dbf', '.shx']
    let optional = ['.sbx', '.sbn', '.xml']
    let exts = files.map(file => path.extname(file.name))
    let lack = susts.filter(sust => !exts.some(ext => ext === sust))
    let ret: {msg?: string, accord: boolean} = { accord: true }

    if (lack.length) {
      ret.msg = `矢量数据必须包含${lack.join('，')}文件`
      ret.accord = false
      return ret
    }

    let all = susts.concat(optional)
    let surplus = exts.filter(ext => !all.some(e => e === ext))
    if (surplus.length) {
      ret.msg = `矢量数据不需要${surplus.join('，')}文件`
      ret.accord = false
      return ret
    }

    return ret
  }

  return (
    <div className={className}>
      <div className={styles.uplayer + ' ' + styles.inuplayer} >
        <Coor coor={coorstr} onChange={(val:string) => setCoor(val)} />
        <div className={styles.inputitem}>
          填写目录：<input value={dir} placeholder="输入对应目录" onChange={ev => setDir(ev.target.value)} />
        </div>
        {dir && <Upload api={'/cesium/vector/upload/'} body={{ coord }} upHandle={referData} multiple className={styles.inputitem} filter={uploadFilter} />}
        
      </div>
      {Element}
    </div>
  )
}