import { useCallback } from 'react'
import { useDispatch } from 'react-redux'
import Taro from '@tarojs/taro'
import { dispatchUpdateUserInfo } from '@/actions/user'
import { queryUserPhone } from '@/services/user'
import { UPDATE_USER_INFO } from '@/constants/user'

export default function useAuth(consultant, router, page) {
  const dispatch = useDispatch()

  const updateUserInfo = useCallback((data) => {
    return new Promise((resolve, reject) => {
      const sessionKey = Taro.getStorageSync('sessionKey')
      Object.assign(data, { sessionKey })
      dispatchUpdateUserInfo(data)(dispatch).then(() => {
        resolve()
      }).catch((err) => {
        console.error(err)
        reject(err)
      })
    })
  }, [dispatch])

  const updatePhoneNumber = useCallback((data) => {
    return new Promise((resolve, reject) => {
      debugger
      const sessionKey = Taro.getStorageSync('sessionKey')
      const { id: targetId, recommender } = router.params
      const buildingId = router.path.indexOf('pages/index/buildingInfo/index') > -1 ? targetId : undefined
      const params = {
        sessionKey,
        sceneId: router.scene,
        buildingId,
        targetId,
        targetType: page.type,
        targetName: page.name,
        promoter: recommender,
        ...data,
      }
      queryUserPhone(params).then((res) => {
        dispatch({
          type: UPDATE_USER_INFO,
          payload: {
            phone: res.phoneNumber
          }
        })
        resolve()
      }).catch((err) => {
        console.error(err)
        reject(err)
      })
    })
  }, [dispatch, consultant, router, page])

  return { updateUserInfo, updatePhoneNumber }
}
