<template>

</template>

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

import { useRoute , useRouter } from 'vue-router'
import { lineLogin } from '@/services/auth'

import { showToast } from 'vant'
import { useShopStore } from '@/store/Shop'

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

const shopStore = useShopStore()

const code = route.query.code

if(!code){
    router.replace('/login')
}else{
    axios.post('https://api.line.me/oauth2/v2.1/token',{
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: 'https://' + shopStore.domain + '/m/linelogin/',
        client_id: '1657876696',
        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: shopStore.sso_domain})
            Cookies.set('uid',res.data.uid,{ expires: 365 ,domain: shopStore.sso_domain})
            showToast('登入成功')
            if(route.query.state !== 'login'){
                router.push(route.query.state)
            }else{
                router.push('/user/info')            
            }
        }else if(res.code == 201){
            sessionStorage.setItem('reg',JSON.stringify(response.data))
            router.push({name:'Register',query: {type:'line'}});
        }else{

        }
    })
    .catch(error =>{
        console.log('err',error)
    })
    // let res = await lineLogin(code)
}

</script>