<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{
    //判斷domain是否包含localhost
    let redirect_uri = "";
    if (shopStore.domain.includes("localhost")) {
        redirect_uri = "http://" + shopStore.domain + ":5173/m/linelogin";
    } else {
        redirect_uri = "https://" + shopStore.domain + "/m/linelogin";
    }

    axios.post('https://api.line.me/oauth2/v2.1/token',{
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: redirect_uri,
        client_id: import.meta.env.VITE_APP_LINE_CLIENT_ID,
        client_secret: import.meta.env.VITE_APP_LINE_CLIENT_SECRET,
    },{
        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>