import React, { useState } from 'react'
import styles from './index.module.css'

const infos = ['x平移米数', 'y平移米数', 'z平移米数', 'rx旋转米数', 'ry旋转米数', 'rz旋转米数', 's缩放']

export default function Coor(props: {coor: string, onChange: Function}) {
  let [coor, setCoor] = useState(props.coor)
  let [info, setInfo] = useState('')


  const changeInput = (ev: React.ChangeEvent<HTMLInputElement>) => {
    let val = (ev.target.value as string)
    let args = val.split(',')
    let i = 0
    if (args.length > 7) {
      return setInfo('参数超过限制')
    }

    if (!args[args.length - 1]) {
      setInfo('正在输入' + infos[args.length - 1])
    } else {
      for (; i < args.length; i++) {
        if (!args[i] || isNaN(Number(args[i]))) break;
      }
      if (i !== args.length) {
        return setInfo(infos[i] + '格式不正确')
      } else {
        setInfo('正在输入' + infos[args.length - 1])
      }
    }
    setCoor(ev.target.value)
  }

  const blurHandle = () => {
    let args = coor.split(',')
    let push: Array<string> = []
    args.forEach(v => v && push.push(v))

    let newCoor = push.length < 3 ? '' :
      push.length < 7 ? push.slice(0, 3).join(',') :
      push.length === 7 ? push.join(',') : push.slice(0, 7).join(',')

    setCoor(newCoor)
    props.onChange(newCoor)
    setInfo('')
  }

  return (
    <div className={styles.tip + ' ' + styles.inputitem}>
      输入坐标转换参数：<input value={coor} placeholder="输入对应坐标" onChange={changeInput} onFocus={changeInput} onBlur={blurHandle} />
      <div style={{ display: info ? 'block' : 'none' }}>
        <p>{info}</p>
        <p>以,(英文符号)结束输入，并输入下一个参数如0,0,0</p>
      </div>
    </div>
  )
}