import type { Scene, EditableScene } from '../../store/scene'
import { 
  ChangeEvent, 
  Dispatch, 
  SetStateAction,
  useCallback, 
  useState,
  useEffect
} from 'react'
import axios, { baseURL } from '../../http'
import React from 'react'
import { SceneType } from '../../store/scene'
import { Button, Form, Input, Space, Upload, UploadFile, Select, message } from 'antd'
import UploadOutlined from '@ant-design/icons/lib/icons/UploadOutlined'

const { Option } = Select


export const usePostFromArgs = (onSubmitRaw: (post: EditableScene) => void | any, post?: EditableScene) => {
  const initCover = post?.cover || null
  const initTitle = post?.title || ''
  const initType = post?.type ? post.type : SceneType.GIS
  const initM = post?.m || ''

  const titleState = useState(initTitle)
  const coverState = useState(initCover)
  const typeState = useState(initType)
  const mState = useState(initM)

  const checkInput = useCallback(() => {
    const msg = 
      !titleState[0] ? '请填写标题' :
      !coverState[0] ? '请上传封面' :
      (typeState[0] !== SceneType.GIS && !mState[0]) 
        ? '非gis类别必须填写场景码' 
        : null

    msg && message.error(msg);
    return !msg
  }, [titleState, coverState, typeState, mState])

  const onSubmit = useCallback(async () => {
    if (checkInput()) {
      const postRaw = {
        type: typeState[0],
        title: titleState[0],
        cover: coverState[0],
        m: mState[0]
      }
      try {
        if (await onSubmitRaw(postRaw as any) !== false) {
          titleState[1](initTitle)
          coverState[1](initCover)
          typeState[1](initType)
          mState[1](initM)
        }
      } catch {

      }
    }
  }, [titleState, coverState, onSubmitRaw, initTitle, initCover, typeState, mState, initType, initM, checkInput])

  return {
    title: titleState,
    cover: coverState,
    type: typeState,
    m: mState,
    onSubmit
  }
}

type FromScene = {
  [key in keyof EditableScene]: Array<any> & {
    0: Scene[key], 
    1: (Dispatch<SetStateAction<Scene[key]>>)
  }
}
type SceneFromProps<T extends FromScene> = T & { onSubmit: () => void }

const uploadHandler = async (file: File): Promise<string> => {
  console.log('-->', file)
  const from = new FormData()
  from.append('file', file)
  const res = await axios({
    method: 'POST',
    url: '/cms/scene/upload',
    headers: { 'Content-Type': 'multipart/form-data' },
    data: from
  })
  return baseURL + res.data.data.filePath
}

export const PostFrom = <T extends FromScene>({onSubmit, ...article }: SceneFromProps<T>) => {
  const [title, setTitle] = article.title
  const [cover, setCover] = article.cover
  const [type, setType] = article.type
  const [m, setM] = article.m
  const [fileList, setFileList] = useState<UploadFile[]>([])

  useEffect(() => {
    if (!cover) return;
    setFileList([{
      uid: '-1',
      name: '封面图',
      status: 'done',
      url: cover,
      type: 'image/png'
    }])
  }, [cover])

  useEffect(() => {
    if (type === SceneType.GIS) {
      setM('')
    }
  }, [type, setM])

  const onTitleChanged = (e: ChangeEvent<HTMLInputElement>) => setTitle(e.target.value)
  const onMChanged = (e: ChangeEvent<HTMLInputElement>) => setM(e.target.value)
  const handleChange = (info: {fileList: UploadFile[]}) => {
    setFileList(info.fileList)

    if (info.fileList.length && info.fileList[0].status === 'done') {
      setCover(info.fileList[0].response.url)
    }
  }


  const typeOptions = [
    { value: SceneType.GIS, label: 'gis' },
    { value: SceneType.KANKAN, label: '四维看看' },
    { value: SceneType.LASER, label: '激光场景' },
  ]
  const renderOptions = typeOptions.map(option => (
    <Option value={option.value} key={option.value}>
      {option.label}
    </Option>
  ))
  const renderMInput = type !== SceneType.GIS && (
      <Form.Item label="场景码">
        <Input value={m} onChange={onMChanged} />
      </Form.Item>
    )

  const uploadAction = (file: File) => {
    uploadHandler(file).then(setCover)
    return null
  }
  return (
    <Form
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
    >
      <Form.Item label="场景名称">
        <Input value={title} onChange={onTitleChanged} />
      </Form.Item>
      <Form.Item label="场景类别">
        <Select defaultValue={ type } onChange={value => setType(value)}>
          { renderOptions }
        </Select>
      </Form.Item>
      { renderMInput }
      <Form.Item label="封面图">
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <Upload
            action={uploadAction}
            listType="picture"
            fileList={fileList}
            onChange={handleChange}
            maxCount={1}
          >
            <Button icon={<UploadOutlined translate={undefined} />}>上传</Button>
          </Upload>
        </Space>
      </Form.Item>
    </Form>
  )
}