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

const getData = fetch(apis.system.personLevel.detail)
const saveData = fetch(apis.system.personLevel.save)
const updateData = fetch(apis.system.personLevel.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(`/system/person-level-setting/detail?id=${res.levelId}`)
              }
            })
          }).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('levelId', {
                rules: [
                  {
                    required: true,
                    message: '请填写等级ID',
                  },
                ],
              })(<InputNumber min={1} />)}
            </Form.Item>
            <Form.Item label="名称">
              {getFieldDecorator('levelName', {
                rules: [
                  {
                    required: true,
                    message: '请填写等级名称',
                  },
                ],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="图标" help="建议图片尺寸：750*600px，比例5:4,格式：jpg" >
              {getFieldDecorator('levelIcon', {
                rules: [{ required: true, message: '请上传分类图标' }],
              })(
                <ImageUpload />,
              )}
            </Form.Item>
            <Form.Item label="积分规则">
              {getFieldDecorator('pointRule', {
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      const [val1, val2] = (value || '').split(',')
                      if (val1 === undefined || val2 === undefined) {
                        callback('请填写完整范围')
                        return
                      }

                      if (val1 - 0 > val2 - 0) {
                        callback('填写范围应该从小到大')
                        return
                      }

                      callback()
                    }
                  }
                ]
              })(<NumberRange tip="示例: 0-10, 代表 0 <= 用户积分 < 10" />)}
            </Form.Item>
            <Form.Item label="描述">
              {getFieldDecorator('levelDesc')(<Input.TextArea />)}
            </Form.Item>
            <Form.Item {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={handleCancel} style={{ marginLeft: '100px' }}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </div>
    </div>
  )
})
