import React, { useEffect, useRef, useState } from 'react'
import { Card, Descriptions, Input, message } from 'antd'
import { fetch, apis } from '@/utils/request'

const getSettings = fetch(apis.searchHouse.setting.get)
const savePhone = fetch(apis.searchHouse.setting.phone)

const EditableField = (props) => {
  const [val, setVal] = useState()

  const handleChange = (e) => {
    setVal(e.target.value)
  }

  useEffect(() => {
    setVal(props.value)
  }, [props.value])

  return (
    <Input.Search
      {...props}
      enterButton="保存"
      onSearch={props.onSubmit}
      onChange={handleChange}
      value={val}
    />
  )
}

export default (props) => {
  const [loading, setLoading] = useState(false)
  const [phone, setPhone] = useState()

  const handlePhoneSubmit = (phone) => {
    if (!phone) return;

    setLoading(true)
    savePhone({ urlData: { phone} }).then(() => {
      setLoading(false)
      setPhone(phone)
      message.success('设置成功')
    }).catch(() => {
      setLoading(false)
    })
  }

  useEffect(() => {
    // 获取客服电话
    setLoading(true)
    getSettings().then((res) => {
      setLoading(false)
      setPhone(res.phone)
    }).catch(() => {
      setLoading(false)
    })
  }, [])

  return (
    <Card loading={loading}>
      <Descriptions column={1} bordered size="middle" style={{maxWidth: '800px'}}>
        <Descriptions.Item label="客服热线">
          <EditableField value={phone} onSubmit={handlePhoneSubmit} />
        </Descriptions.Item>
      </Descriptions>
    </Card>
  )
}
