import Taro, { useRouter } from '@tarojs/taro'
import { alert } from '@/common/common'
import { MpuserwechatBinding } from '@/api/login/login'
import useUserInfo from '@/use/useUserInfo'

export default () => {
  const { fetchData: loginFetch } = MpuserwechatBinding()
  const { setToken, setSessionKey, setUserInfo, userInfo } = useUserInfo()

  const UseGetCode = () => {
    Taro.login({
      async success(res) {
        const code = res.code
        if (code) {
          console.log(`获取用户登录凭证：${code}`)
          const state = await loginFetch({ js_code: code, user_id: userInfo.userInfo.user_id })
          if (state.data) {
            // setToken(state.data.token)
            setSessionKey(state.data.session_key)
            // setUserInfo({ ...userInfo.userInfo, token: state?.data?.token || '' })
            alert.none('链接成功，可开始接收服务信息啦！')
          }
          else {
            return alert.none(`${state?.msg}`)
          }
        }
        else {
          console.log(`获取用户登录态失败：${res.errMsg}`)
          return alert.error(`${res?.errMsg}`)
        }
      },
    })
  }

  return {
    UseGetCode,
  }
}
