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

export default withLayout(() => {

  const { dispatch } = store

  const user = useSelector(state => state.user)
  const [UserInfo, setUserInfo] = useState({})
  const [UserRole, setUserRole] = useState(null) // 1-普通用户 2-经纪人 3-置业顾问 4-驻场管理
  const [FormData, setFormData] = useState({
    name: '',
    phone: '',
    description: ''
  })

  useEffect(() => {
    if (user?.userInfo?.person?.personId) {
      const person = user.userInfo.person
      setUserRole(person.personType === ROLE_CODE.CHANNEL_AGENT ? 2 : person.personType === ROLE_CODE.CONSULTANT ? 3 : person.personType === ROLE_CODE.MARKETING ? 4 : 1)
    }
  }, [user])

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

  const Save = () => {
    let params = ''
    if(UserRole === 3) {
      params = `name=${FormData.name}&phone=${FormData.phone}&description=${FormData.description}`
    } else {
      params = `name=${FormData.name}&phone=${FormData.phone}`
    }
    fetch({ url: `${API_EDIT_AGENT}?${params}`, method: 'put' }).then(() => {
      Taro.showToast({
        title: '修改成功',
        icon: 'none'
      })
      dispatch({ type: UPDATE_USER_INFO, payload: { name: FormData.name, phone: FormData.phone, description: FormData.description } })
      // login({ path: '', scene: '' })
    })
  }

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

  const ToUploadImg = () => {
    if (UserRole - 0 === 3) {
      Taro.chooseImage({
        count: 1,
        success: function (res) {
          if (res.errMsg === 'chooseImage:ok') {
            Taro.showToast({ title: '正在上传...', icon: 'loading', mask: true, duration: 10000 })
            uploadFiles(res.tempFilePaths).then((subRes) => {
              fetch({ url: API_UPDATE_PHOTO, payload: { photoUrl: subRes[0] }, method: 'put' }).then(() => {
                Taro.hideToast()
                Taro.showToast({ title: '修改成功', icon: 'none', duration: 2000 })
                dispatch({ type: UPDATE_USER_INFO, payload: { userPhoto: subRes[0] } })
              })
            })
          }
        }
      })
    }
  }

  return (
    <view className='Page UserInfo'>

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

          <text>头像</text>
          <view className='FormLine flex-h' onClick={ToUploadImg}>
            <view className='flex-item'>
              <view className='Icon'>
                <Image mode='aspectFill' src={getImgURL(UserInfo.userPhoto || 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>

          {
            true &&
            <Block>
              <text>简介</text>
              <view className='FormLine flex-h'>
                <view className='flex-item'>
                  <Textarea auto-height placeholder='请输入简介' value={FormData.description} onInput={FormChange.bind(this, 'description')} />
                </view>
              </view>
            </Block>
          }

        </view>

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

    </view>
  )
})
