import { useState, useEffect, useImperativeHandle, forwardRef } from 'react'
import { CloudUploadOutlined } from '@ant-design/icons'
import { Form, Input, Spin, Upload, Button } from 'antd'
import OnlineImageList from './onlineImageList'
import { uploadFile } from '@/utils/oss'

const fileAccept = ['.png', '.jpg', '.jpeg', '.svg']

const randomOne = Math.random().toString(16).substring(2, 10)
const GalleryFormItem = (props, ref) => {
  const { activeKey, form, setPicList, galleryInfo, isOnline = false } = props

  const [uploading, setUploading] = useState(false) // 文件上传状态
  const [file, setFile] = useState({})
  const [imgUrl, setImgUrl] = useState('')

  useImperativeHandle(ref, () => {
    return {
      uploading
    }
  })
  useEffect(() => {
    if (galleryInfo && Object.entries(galleryInfo).length > 0) {
      const { galleryList } = galleryInfo
      let galleryArr = []
      try {
        galleryArr = JSON.parse(decodeURI(galleryList))
        if (galleryArr && !(galleryArr instanceof Array)) {
          galleryArr = [{ url: '', title: '', desc: '', key: randomOne }]
        }
      } catch (err) {
        galleryArr = [{ url: '', title: '', desc: '', key: randomOne }]
      }

      if (galleryArr.length > 0) {
        const values = { ['content']: {} }
        galleryArr.forEach(item => {
          values['content'][item.key] = {
            url: item.url,
            title: item.title,
            desc: item.desc
          }
        })
        form.setFieldsValue({ ...values, gallery: galleryArr })

        const item = galleryArr.filter(item => item.key === activeKey)
        if (item.length > 0) {
          const itemGallery = item[0]
          setImgUrl(itemGallery.url)
        }
      }
    }
  }, [galleryInfo])

  useEffect(() => {}, [])

  const uploadProps = {
    name: 'file',
    maxCount: 1,
    showUploadList: false,
    accept: fileAccept.join(','),
    beforeUpload: file => {
      setFile(file)
    },
    customRequest: async () => {
      setUploading(true)
      const url = await uploadFile(file)
      const values = {
        ['content']: {
          [activeKey]: {
            url: url,
            title: '',
            desc: ''
          }
        }
      }
      setImgUrl(url)
      form.setFieldsValue({ ...values })
      const allContent = form.getFieldValue('content')
      const newGalleryList = []
      // eslint-disable-next-line guard-for-in
      for (let key in allContent) {
        newGalleryList.push({ ...allContent[key], key: key })
      }
      setPicList(newGalleryList)
      form.setFieldsValue({ gallery: newGalleryList })
      setUploading(false)
    }
  }

  const changeTitleValue = e => {
    const allContent = form.getFieldValue('content')
    const newGalleryList = []
    // eslint-disable-next-line guard-for-in
    for (let key in allContent) {
      newGalleryList.push({ ...allContent[key], key: key })
    }
    setPicList(newGalleryList)
    form.setFieldsValue({ gallery: newGalleryList })
  }
  const changeDescValue = e => {
    const allContent = form.getFieldValue('content')
    const newGalleryList = []
    // eslint-disable-next-line guard-for-in
    for (let key in allContent) {
      newGalleryList.push({ ...allContent[key], key: key })
    }
    setPicList(newGalleryList)
    form.setFieldsValue({ gallery: newGalleryList })
  }

  const onOnlineImageChange = url => {
    setImgUrl(url)
    const values = {
      ['content']: {
        [activeKey]: {
          url: url,
          title: '',
          desc: ''
        }
      }
    }
    setImgUrl(url)
    form.setFieldsValue({ ...values })
    const allContent = form.getFieldValue('content')
    const newGalleryList = []
    // eslint-disable-next-line guard-for-in
    for (let key in allContent) {
      newGalleryList.push({ ...allContent[key], key: key })
    }
    setPicList(newGalleryList)
    form.setFieldsValue({ gallery: newGalleryList })
  }

  return (
    <>
      {isOnline ? (
        <Form.Item label="在线图片" extra="最多可上传10张" name={['content', activeKey, 'url']} rules={[{ required: true, message: '请选择图片' }]}>
          <OnlineImageList imgUrl={imgUrl} onChange={onOnlineImageChange}></OnlineImageList>
        </Form.Item>
      ) : (
        <Form.Item label="上传图片" extra="最多可上传10张" name={['content', activeKey, 'url']} rules={[{ required: true, message: '请上传画廊图片' }]}>
          <Spin spinning={uploading} tip="Loading">
            <div className="editor-dragger">
              <Upload.Dragger {...uploadProps} showUploadList={false}>
                {!imgUrl ? (
                  <>
                    <div className="editor-uploader-process">
                      <p className="ant-upload-drag-icon">
                        <CloudUploadOutlined style={{ fontSize: 40 }} />
                      </p>
                      <p className="ant-upload-text">点击上传或拖拽到此处上传</p>
                      <p className="ant-upload-hint">支持上传 .png、.jpg、.jpeg、.svg格式的图片</p>
                    </div>
                  </>
                ) : (
                  <div className="editor-uploader-result">
                    <div className="editor-uploader-result-img">
                      <img src={imgUrl} alt="" />
                    </div>
                    <div className="editor-uploader-result-tips">
                      <Button size="small" type="primary" ghost onClick={() => setImgUrl(null)}>
                        替换
                      </Button>
                    </div>
                  </div>
                )}
              </Upload.Dragger>
            </div>
          </Spin>
        </Form.Item>
      )}

      <Form.Item label="标题" rules={[{ required: false, message: '请输入图片标题' }]} name={['content', activeKey, 'title']} extra="最多输入100字">
        <Input maxLength={100} placeholder="" allowClear onChange={changeTitleValue} />
      </Form.Item>
      <Form.Item label="描述" rules={[{ required: false, message: '请输入图片描述' }]} name={['content', activeKey, 'desc']} extra="最多输入500字">
        <Input.TextArea maxLength={500} autoSize={{ minRows: 4, maxRows: 6 }} placeholder="请输入描述" onChange={changeDescValue} />
      </Form.Item>
    </>
  )
}

export default forwardRef(GalleryFormItem)
