import { useEffect, useState } from "react"
import { WX_APPID } from "@/common/constant"
import useUserInfo from "./useUserInfo"


export default () => {
    const {setToken, setSessionKey, setUserInfo} = useUserInfo()

    const [loginState, setLoginState] = useState({
        session_key: '',
        token: '',
        userInfo: ''
    })

    const getToken = () => {
        Taro.login({
            success: function (res) {
                if (res.code) {
                    console.log('number::', res.code)
                    Taro.request({
                        url: 'https://dev.zzfzyc.com/lymarket/v1/mall/login',
                        method: 'POST',
                        data: {
                            js_code: res.code,
                        },
                        header: {
                            platform: 6,
                            Appid: WX_APPID
                        },
                        success: (e) => {
                            let {data} = e.data
                            setLoginState({
                                ...loginState,
                                session_key: data.session_key,
                                token: data.token
                            })
                            setToken(data.token)
                            setLoginState(data.session_key)
                        }
                    })
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            },
            fail: function(e) {
               console.log('e::',e)
            }
        })
    }

    const getUserInfo =  () => {
        Taro.getUserProfile({
            desc: '用于完善会员资料',
            success: (res) => {
                Taro.request({
                    url: 'https://dev.zzfzyc.com/lymarket/v1/mall/user/decrypt',
                    method: 'POST',
                    data: {
                        session_key: loginState.session_key,
                        raw_data: res.rawData,
                        signature: res.signature,
                        encrypted_data: res.encryptedData,
                        iv: res.iv
                    },
                    header: {
                        platform: 6,
                        Authorization: loginState.token,
                        Appid: WX_APPID
                    },
                    success: (e) => {
                        setUserInfo({})
                    },
                    fail: (e) => {
                        console.log(e)
                    }
                })
            }
        })
        
        
    }

    return {
        getToken,
        getUserInfo
    }
}