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

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

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

  const [uploading, setUploading] = useState(false) // 文件上传状态
  const [progress, setProgress] = useState(0)
  const [file, setFile] = useState({})
  const [fileList, setFileList] = 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 normFile = (e) => {
    if (Array.isArray(e)) {
      return e
    }
    return e?.fileList
  }

  const uploadProps = {
    name: 'file',
    maxCount: 1,
    showUploadList: false,
    accept: fileAccept.join(','),
    beforeUpload: (file, fileList) => {
      const fileExt = file.name.substring(file.name.lastIndexOf('.'))
      if (!fileAccept.includes(fileExt.toLowerCase())) {
        message.error('请上传正确格式的图片')
        return false
      }
      setFile(file)
      setFileList(fileList)
    },
    customRequest: async () => {
      setUploading(true)
      let data = null
      if (file.size >= partSize) {
        data = await multipartUploader(file, 'gallery', ossClient, (progress, checkpoint) => {
          console.log(`上传进度 ${progress}`)
          setProgress(parseInt(progress * 100))
        })
        console.log('multipartUploader --> ', data)
      } else {
        data = await normalUploader(file, 'gallery', ossClient)
        console.log('normalUploader --> ', data)
      }

      if (data.status === 200 && data.statusCode === 200) {
        const { url, name } = data
        const filename = file.name.substring(0, file.name.lastIndexOf('.'))
        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="在线图片"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          extra="最多可上传10张"
          name={['content', activeKey, 'url']}
          rules={[{ required: true, message: '请选择图片' }]}>
          <OnlineImageList imgUrl={imgUrl} onChange={onOnlineImageChange}></OnlineImageList>
        </Form.Item>
      ) : (
        <Form.Item
          label="上传图片"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          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)
