<template>

</template>

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

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

import { Toast } from 'vant'

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

const code = route.query.code

if(!code){
    router.replace('/login')
}else{
    const client_id = process.env.VUE_APP_LINE_CLINE_ID
    const redirect_uri = `${process.env.VUE_APP_BASE_URL}/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: process.env.VUE_APP_DOMAIN})
            Cookies.set('uid', res.data.uid,{ expires: 365 ,domain: process.env.VUE_APP_DOMAIN})
            Toast('登入成功')

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

</script>