import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { useSelector } from 'react-redux'
import withLayout from '@/layout'
import { ScrollView, Input, Image } from '@tarojs/components'
import { getImgURL } from '@/utils/image'
import { fetch } from '@/utils/request'
import login from '@/utils/login'
import { API_EDIT_AGENT } from '@/constants/api'
import '@/assets/css/iconfont.css'
import './index.scss'

export default withLayout(() => {

  const user = useSelector(state => state.user)
  const [UserInfo, setUserInfo] = useState({})
  const [FormData, setFormData] = useState({
    name: '',
    phone: ''
  })

  useEffect(() => {
    setUserInfo(user?.userInfo?.person)
    setFormData({name: user?.userInfo?.person.name, phone: user?.userInfo?.person.phone})
  }, [user])

  const Save = () => {
    fetch({ url: `${API_EDIT_AGENT}?name=${FormData.name}&phone=${FormData.phone}`, method: 'put' }).then(() => {
      Taro.showToast({
        title: '修改成功',
        icon: 'none'
      })
      login({path: '', scene: ''})
    })
  }

  const FormChange = (key, e) => {
    let Data = {...FormData}
    Data[key] = e.detail.value
    setFormData(Data)
  }

  return (
    <view className='Page UserInfo'>

      <ScrollView scroll-y>
        <view className='PageContent'>

          <text>头像</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <view className='Icon'>
                <Image mode='aspectFill' src={getImgURL(UserInfo.avatarurl)}></Image>
              </view>
            </view>
            {/* <text className='iconfont icon-jiantouright'></text> */}
          </view>

          <text>用户名</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Input placeholder='请输入用户名' value={FormData.name} onInput={FormChange.bind(this, 'name')}></Input>
            </view>
          </view>

          <text>手机号码</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Input placeholder='请输入手机号码' value={FormData.phone} onInput={FormChange.bind(this, 'phone')}></Input>
            </view>
          </view>

        </view>

        <view className='Btn'>
          <text onClick={Save}>保存</text>
        </view>
      </ScrollView>

    </view>
  )
})
