import React, { useReducer, useEffect, useState, Fragment } from 'react'
import { RouteComponentProps } from 'react-router'
import { reducer, initialState, getLayersAction, updateLayerAction, saveLayersAction, Item } from './reducer'
import VectorShow from '../../components/VectorShow'
import Color from '../../components/Color'
import styles from './style.module.css'

type Attr = 'lineColor' | 'lineWidth' | 'fillColor' | 'show'
type EvAttr = 'value' | 'checked'

function StyleEdit(props: RouteComponentProps) {
  let [state, dispatch] = useReducer(reducer, initialState)
  let layers = Object.keys(state)
  let [layer, setLayer] = useState('')
  let params = props.match.params as any
  let style = (layer && state[layer]) as Item

  useEffect(() => { getLayersAction(dispatch, params.id) }, [params.id])
  useEffect(() => { layer || setLayer(layers[0]) }, [layer, layers])

  const changeHandle = (attr: Attr, evAttr: EvAttr = 'value', init = false) => (ev: any) => {
    updateLayerAction(dispatch, layer, { ...style, [attr]: init ? ev : ev.target[evAttr] })
  }
  const saveHandle = async () => {{
    if (await saveLayersAction(style, params.id)) {
      alert('成功发布')
    } else {
      alert('发布失败')
    }
  }}
  const verctorInfo = style && { ...style, url: style.getUrl }

  return (
    <div>
      <div className={styles.filter}>
        <div className={styles.inputitem}>
          <label>图层选择</label>
          <select value={layer} onChange={ev => setLayer(ev.target.value)}>
            {layers.map(layer => <option value={layer} key={layer}>{layer}</option>)}
          </select>
        </div>
        {style && (
          <Fragment>
            <div className={styles.inputitem}>
              <label>填充颜色</label>
              <Color color={style.fillColor} onChange={changeHandle('fillColor', void 0, true)} />
            </div>
            <div className={styles.inputitem}>
              <label>线条颜色</label>
              <Color color={style.lineColor} onChange={changeHandle('lineColor', void 0, true)} />
            </div>
            <div className={styles.inputitem}>
              <label>线条厚度</label>
              <input type="number" value={style.lineWidth} onChange={changeHandle('lineWidth')} />
            </div>
            <div className={styles.inputitem}>
              <label>是否显示</label>
              <input type="checkbox" checked={style.show} onChange={changeHandle('show', 'checked')} />
            </div>
            <div className={styles.inputitem}>
              <button onClick={saveHandle}>发布</button>
            </div>
            </Fragment>
        )}
      </div>
      {style && <div className={styles.content}><VectorShow {...verctorInfo} height={2500} /></div>}
    </div>
  )
}

export default StyleEdit