<template>

</template>

<script setup>
import axios from 'axios'
import Cookies from 'js-cookie'

import { useRoute , useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { linelogin } from '@/api/index'

import { Toast } from 'vant'

const route = useRoute()
const router = useRouter()

const store = useStore()

const code = route.query.code

if(!code){
    router.replace('/login')
}else{
    const client_id = process.env.VUE_APP_LINE_CLINE_ID
    const redirect_uri = `https://${store.state.domain}/home/linelogin`
        
    axios.post('https://api.line.me/oauth2/v2.1/token',new URLSearchParams({
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: redirect_uri,
        client_id: client_id,
        client_secret: '2a7930d6143a00ff421812b942cde200'
    }),{
        headers: {
            'content-type': 'application/x-www-form-urlencoded'
        }
    }).then(async (response) => {
        let res = await linelogin({token:response.data.id_token})
        if(res.code == 200){
            Cookies.set('token', res.data.token,{ expires: 365 ,domain: store.state.sso_domain})
            Cookies.set('uid', res.data.uid,{ expires: 365 ,domain: store.state.sso_domain})
            Toast('登入成功')

            router.push('/')
        }else if(res.code == 201){
            sessionStorage.setItem('reg',JSON.stringify(response.data))
            router.push('/register')
        }
    })
    .catch(error =>{
        Toast('登入失敗')
        router.push('/login')
    })
    // let res = await lineLogin(code)
}

</script>