import React, { useState, useEffect } from 'react'
import { Button, Form, Input, message } from 'antd'
import ImageUpload from '@/components/XForm/ImageUpload'
import AuthButton from '@/components/AuthButton'
import { fetch, apis } from '@/utils/request'

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 3 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
}
const getData = fetch(apis.activity.shareContent)
const saveData = fetch(apis.activity.addShareContent)
const updateData = fetch(apis.activity.updateShareContent)

const ShareForm = (props) => {
  const { target, form, rights } = props
  const { id: targetId, type: targetType } = target
  const { getFieldDecorator, resetFields, setFieldsValue, validateFields } = form

  const [formData, setFormData] = useState()
  const [loading, setLoading] = useState(false)

  const handleSubmit = (e) => {
    e.preventDefault();
    validateFields((err, values) => {
      if (err) {
        console.error(err)
        return
      }

      const request = formData?.shareContentId ? updateData : saveData
      const urlData = formData?.shareContentId ? { id: formData.shareContentId } : undefined
      const data = {
        targetId,
        shareContentType: targetType,
        ...(formData || {}),
        ...values,
      }

      setLoading(true)
      request({ urlData, data }).then((res) => {
        setLoading(false)
        setFormData(res)
        message.success('操作成功')
      }).catch((err) => {
        setLoading(false)
        console.error(err)
      })
    })
  }

  useEffect(() => {
    if (targetId && targetType) {
      setLoading(true)
      getData({ params: { targetId, targetType } }).then((res) => {
        setFormData(res ? res[0] : undefined)
        setLoading(false)
      }).catch((err) => {
        console.error(err)
        setLoading(false)
      })
    }
  }, [targetId, targetType])

  useEffect(() => {
    const { shareContentImg, shareContentTitle } = formData || {}

    resetFields()
    setFieldsValue({ shareContentImg, shareContentTitle })
  }, [formData])

  return (
    <Form {...formItemLayout} onSubmit={handleSubmit}>
      <Form.Item label="分享标题">
      {getFieldDecorator('shareContentTitle', {
        rules: [{required: true, message: '请填写分享标题'}]
      })(<Input placeholder="建议不要超过20字" />)}
      </Form.Item>
      <Form.Item label="分享图" help="建议图片尺寸：750*600px，比例5:4,格式：jpg">
      {getFieldDecorator('shareContentImg', {
          rules: [{ required: true, message: '请上传分享图' }],
      })(<ImageUpload />)}
      </Form.Item>
      <Form.Item label=" " colon={false} style={{marginTop: '2em'}}>
        <AuthButton name={rights}>
          <Button loading={loading} style={{marginLeft: '4em'}} type="primary" htmlType="submit">保存</Button>
        </AuthButton>
        {/* <Button style={{marginLeft: '2em'}} onClick={props.onCancel}>取消</Button> */}
      </Form.Item>
    </Form>
  )
}

export default Form.create({})(ShareForm)
