import React, { useEffect, useState } from 'react'
import { PageHeader, Form, Input, Rate, Button, Spin, Modal, notification, InputNumber } from 'antd'
import router from 'umi/router'
import { fetch, apis } from '@/utils/request'
import ImageUpload from '@/components/XForm/ImageUpload'

const getData = fetch(apis.shop.type.detail)
const saveData = fetch(apis.shop.type.save)
const updateData = fetch(apis.shop.type.update)

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 6,
    },
  },
}

export default Form.create({})(props => {
  const [title, updateTitle] = useState('分类详情')
  const [loading, updateLoading] = useState(false)
  const [pageData, updatePageData] = useState({})

  const { id } = props.location.query
  const { getFieldDecorator, setFieldsValue, validateFields } = props.form

  const handleCancel = () => {
    router.go(-1)
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        updateLoading(true)
        if (!id) {
          saveData({data: values}).then(res => {
            updateLoading(false)
            // 保存成功之后直接跳转到详情
            Modal.success({
              content: '保存信息成功',
              onOk: () => {
                router.replace(`/shop/type/detail?id=${res.typeId}`)
              }
            })
          }).catch(err => {
            updateLoading(false)
          })
        } else {
          updateData({ data: values, urlData: { id } }).then(res => {
            updateLoading(false)
            updatePageData(res)
            notification.success({ message: '更新信息成功' })
          }).catch(err => {
            updateLoading(false)
          })
        }
      }
    });
  }

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

  useEffect(() => {
    if (id) {
      updateLoading(true)
      getData({ urlData: {id} }).then((res) => {
        updatePageData(res)
        updateLoading(false)
        if (!res) {
          notification.info({ message: '没有查询到数据' })
        } else {
          updateTitle(res.typeName)
        }
      }).catch(err => {
        updateLoading(false)
      })
    }
  }, [])

  return (
    <div>
      <PageHeader
        ghost={false}
        backIcon={false}
        title={title}
      ></PageHeader>
      <div style={{marginTop: '16px'}}>
        <Spin spinning={loading} tip="请稍候...">
          <Form {...formItemLayout} onSubmit={handleSubmit} >
            <Form.Item label="名称">
              {getFieldDecorator('typeName', {
                rules: [
                  {
                    required: true,
                    message: '请填写分类名称',
                  },
                ],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="图标" help="建议图片尺寸：750*600px，比例5:4,格式：jpg" >
              {getFieldDecorator('thumb', {
                rules: [{ required: true, message: '请上传分类图标' }],
              })(
                <ImageUpload />,
              )}
            </Form.Item>
            <Form.Item label="描述">
              {getFieldDecorator('typeDesc')(<Input.TextArea />)}
            </Form.Item>
            <Form.Item label="排序">
              {getFieldDecorator('sortNo')(<InputNumber min={0} />)}
            </Form.Item>
            <Form.Item {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={handleCancel} style={{ marginLeft: '100px' }}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </div>
    </div>
  )
})
