import {defineStore} from "pinia";
import {login} from "@/pages-login/service";
import {useUserStore} from "@/store";
import * as R from "ramda";
import Config from "@/config";
import {LoginType} from "@/constant/enums";


export const useLogicStore = defineStore('login-logic', () => {
        const {defaultAreaCode} = useAreaCode()
        const registerForm = ref({
            type: "",
            email: '',
            confirmEmail: '',
            firstName: '',
            surname: '',
            phone: '',
            loginPwd: '',
            newPwd: '',
            areaCode: defaultAreaCode.value,
            captcha: "",
        })

        const loginForm = ref({
            type: "",
            email: '',
            areaCode: defaultAreaCode.value,
            phone: '',
            code: '',
            password: '',
            tripartiteLoginIdentify: '',
        })

        const forgetPasswordForm = ref({
            email: '',
            loginPwd: '',
            captcha: "",
            phone: '',
            areaCode: defaultAreaCode.value,
        })

        function navigateTo(url: string) {
            uni.navigateTo({
                url,
            })
        }

        function reset() {
            registerForm.value = {
                type: "",
                email: '',
                confirmEmail: '',
                firstName: '',
                surname: '',
                phone: '',
                loginPwd: '',
                newPwd: '',
                areaCode: defaultAreaCode.value,
                captcha: "",
            }
            loginForm.value = {
                type: "",
                email: '',
                areaCode: defaultAreaCode.value,
                phone: '',
                code: '',
                password: '',
                tripartiteLoginIdentify: '',
            }
            forgetPasswordForm.value = {
                email: '',
                loginPwd: '',
                captcha: "",
                phone: '',
                areaCode: defaultAreaCode.value,
            }
        }

        function resetRegisterForm() {
            registerForm.value = {
                type: "",
                email: '',
                confirmEmail: '',
                firstName: '',
                surname: '',
                phone: '',
                loginPwd: '',
                newPwd: '',
                areaCode: defaultAreaCode.value,
                captcha: "",
            }
        }

        const userStore = useUserStore()
        const {t} = useI18n()

        function appleLogin() {
            return new Promise((resolve, reject) => {
                uni.login({
                    provider: 'apple',
                    success: (res) => {
                        uni.getUserInfo({
                            provider: 'apple',
                            success: async (info) => {
                                // 获取用户信息成功, info.authResult保存用户信息
                                console.log('info', info)
                                const params = {
                                    type: LoginType.APPLE,
                                    email: info.userInfo?.email || '',
                                    tripartiteLoginIdentify: info?.userInfo?.openId ?? '',
                                }

                                try {
                                    const loginRes = await login(params)
                                    console.log('loginRes', loginRes)
                                    userStore.token = loginRes.data.token
                                    nextTick(() => {
                                        userStore.getUserInfo();
                                    })
                                    await uni.showToast({title: t('pages-login.login-successfully'), icon: "none"});
                                    const pages = getCurrentPages()
                                    setTimeout(R.ifElse(() => pages.length > 1, () => uni.navigateBack({delta: 1}), () => uni.switchTab(
                                        {
                                            url: Config.indexPath
                                        }
                                    )), 1000);
                                    resolve(true)
                                } catch (err: any) {
                                    console.log('err', err)
                                    if (R.equals(+err.code, 711)) {
                                        registerForm.value = {
                                            email: info.userInfo?.email || '',
                                            areaCode: '',
                                            phone: '',
                                            code: '',
                                            password: '',
                                            type: LoginType.APPLE,
                                            tripartiteLoginIdentify: info?.userInfo?.openId ?? '',
                                        }
                                        navigateTo('/pages-login/pages/sign-up/index')
                                    }
                                }
                            },
                            fail: (err: any) => {
                                console.log('err', err)

                            },
                        })
                    },
                    fail: (err: any) => {
                        console.log('err', err)
                        // 登录授权失败
                        uni.showToast({title: t('common.appleLoginFailed'), icon: 'none'})
                    },
                })
            })
        }

        function facebookLogin() {
            return new Promise((resolve, reject) => {
                uni.login({
                    provider: 'apple',
                    success: (res) => {
                        uni.getUserInfo({
                            provider: 'apple',
                            success: async (info) => {
                                // 获取用户信息成功, info.authResult保存用户信息
                                console.log('info', info)
                                const params = {
                                    userType: 1,
                                    // 1 验证码 2 密码 3 一键登录 4 微信登录 5 小程序登录 6 苹果登录
                                    type: 6,
                                    openid: info?.userInfo?.openId ?? '',
                                }
                                try {
                                    const loginRes = await login(params)
                                    console.log('loginRes', loginRes)
                                    userStore.token = loginRes.data.token
                                    resolve(true)
                                } catch (err: any) {
                                    console.log('err', err)
                                }
                            },
                            fail: (err: any) => {
                                console.log('err', err)

                            },
                        })
                    },
                    fail: (err: any) => {
                        console.log('err', err)
                        // 登录授权失败
                        uni.showToast({title: '登录授权失败', icon: 'none'})
                    },
                })
            })
        }

        function googleLogin() {
            return new Promise((resolve, reject) => {
                uni.login({
                    provider: 'google',
                    success: (res) => {
                        uni.getUserInfo({
                            provider: 'google',
                            success: async (info) => {
                                // 获取用户信息成功, info.authResult保存用户信息
                                console.log('info', info)
                                const params = {
                                    userPort: 2,
                                    type: LoginType.GOOGLE,
                                    email: info.userInfo.email,
                                    tripartiteLoginIdentify: info.userInfo.openid,
                                }
                                try {
                                    const loginRes = await login(params)
                                    console.log('loginRes', loginRes)
                                    userStore.token = loginRes.data.token

                                    nextTick(() => {
                                        userStore.getUserInfo();
                                    })
                                    await uni.showToast({title: t('pages-login.login-successfully'), icon: "none"});
                                    const pages = getCurrentPages()
                                    setTimeout(R.ifElse(() => pages.length > 1, () => uni.navigateBack({delta: 1}), () => uni.switchTab(
                                        {
                                            url: Config.indexPath
                                        }
                                    )), 1000);

                                    resolve(true)
                                } catch (err: any) {
                                    if (R.equals(+err.code, 711)) {
                                        registerForm.value = {
                                            email: info.userInfo.email,
                                            areaCode: '+1',
                                            phone: '',
                                            code: '',
                                            password: '',
                                            type: LoginType.GOOGLE,
                                            tripartiteLoginIdentify: info.userInfo.openid,
                                            userPort: 2,
                                        }
                                        navigateTo('/pages-login/pages/sign-up/index')
                                    }
                                }
                            },
                            fail: (err: any) => {
                                console.log('err', err)
                            },
                        })
                    },
                    fail: (err: any) => {
                        console.log('err', err)
                        // 登录授权失败
                        uni.showToast({title: t('common.googleLoginFailed'), icon: 'none'})
                    }
                })
            })
        }

        function wechatLogin() {
            return new Promise((resolve, reject) => {
                uni.login({
                    provider: 'weixin',
                    success: (res) => {
                        const {code} = res
                        uni.getUserInfo({
                            provider: 'weixin',
                            success: async (info) => {
                                // 获取用户信息成功, info.authResult保存用户信息
                                console.log('info', info)
                                const params = {
                                    userType: 1,
                                    // 1 验证码 2 密码 3 一键登录 4 微信登录 5 小程序登录 6 苹果登录
                                    type: 6,
                                    openid: info?.userInfo?.openId ?? '',
                                }
                                try {
                                    const loginRes = await login(params)
                                    console.log('loginRes', loginRes)
                                    userStore.token = loginRes.data.token
                                    resolve(true)
                                } catch (err: any) {
                                    console.log('err', err)
                                }
                            },
                            fail: (err: any) => {
                                console.log('err', err)

                            },
                        })
                    },
                    fail: (err: any) => {
                        console.log('err', err)
                        // 登录授权失败
                        uni.showToast({title: '微信登录授权失败', icon: 'none'})
                    }
                })
            })
        }

        return {
            registerForm,
            loginForm,
            forgetPasswordForm,
            reset,
            appleLogin,
            facebookLogin,
            googleLogin,
            wechatLogin,
            resetRegisterForm,
        }

    }
)
