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

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

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 [typeList, updateTypeList] = 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/detail?id=${res.shopId}`)
              }
            })
          }).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(() => {
    // 请求分类
    getTypeData({ pageNum: 1, pageSize: 999 }).then(res => {
      updateTypeList(res[0])
    })

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

  const handeLngLatChange = (lnglat, regeo) => {
    setFieldsValue({
      address: regeo.formatted_address
    })
  }

  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('shopName', {
                rules: [
                  {
                    required: true,
                    message: '请填写商户名称',
                  },
                ],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="LOGO" help="建议图片尺寸：750*600px，比例5:4,格式：jpg" >
              {getFieldDecorator('shopLogo', {
                rules: [{ required: true, message: '请上传店铺LOGO' }],
              })(
                <ImageUpload />,
              )}
            </Form.Item>
            <Form.Item label="分类">
              {getFieldDecorator('typeId')(
                <Select>
                  {
                    (typeList || []).map(tp => <Select.Option value={tp.typeId} key={tp.typeId}>{tp.typeName}</Select.Option>)
                  }
                </Select>
              )}
            </Form.Item>
            <Form.Item label="电话">
              {getFieldDecorator('phone')(<Input />)}
            </Form.Item>
            <Form.Item label="描述">
              {getFieldDecorator('shopDesc')(<ImageUpload />)}
            </Form.Item>
            <Form.Item label="经纬度">
              {getFieldDecorator('lngLat')(<AMapSelector onChange={handeLngLatChange} />)}
            </Form.Item>
            <Form.Item label="地址">
              {getFieldDecorator('address')(<Input.TextArea />)}
            </Form.Item>
            <Form.Item label="打分">
              {getFieldDecorator('score')(<Rate />)}
            </Form.Item>
            <Form.Item label="商户标签">
              {getFieldDecorator('tags')(<EditableTagGroup />)}
            </Form.Item>
            <Form.Item label="外卖标签">
              {getFieldDecorator('badges')(<ShopBadgesSelect mode="multiple" placeholder="请选择..." />)}
            </Form.Item>
            <Form.Item label="人均消费">
              {getFieldDecorator('costAvg')(<Input prefix="￥" suffix="/人" />)}
            </Form.Item>
            <Form.Item label="首页推荐">
              {getFieldDecorator('isIndex')(
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value={true}> 是 </Radio.Button>
                  <Radio.Button value={false}> 否 </Radio.Button>
                </Radio.Group>
              )}
            </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>
  )
})
