import { defineStore } from 'pinia'
import { requestGuestLogin, requestLogin, passwordLogin, requestGoogleLogin, requestIdPasswordLogin } from '@/api/login.js'
import { requestUserInfo, requestReportOnline } from '@/api/user.js'
import { getVipInfo } from '@/api/vip.js'
import { requestServiceList } from '@/api/home.js'
import { useAppStore } from './useAppStore'
import { getAgentInfoApi, getAgentV2Home } from '@/api/earn.js'
import { reportAdjustAdid } from '@/module/third/adjust.js'

const userInfoStoreKey = 'APP_USER_INFO_STORE_KEY'
const vipInfoStoreKey = 'APP_VIP_INFO_STORE_KEY'
const serviceInfoStoreKey = 'APP_SERVICE_INFO_KEY'
const signStoreKey = 'APP_SIGN_STORE_KEY'
const uidStoreKey = 'APP_UID_STORE_KEY'
const serviceUrlStoreKey = 'APP_SERVICE_URL_STORE_KEY'
const minVipLevelStoreKey = 'APP_MIN_VIP_LEVEL_STORE_KEY'

export const useUserStore = defineStore({
    id: 'user',
    state: () => ({
        sign: '',
        uid: '',
        newUserFlag: false,
        userInfo: {},
        vipInfo: {},
        serviceInfo: {},
        currentVipLevel: 0,
        serviceUrl: '',
        minVipLevel: 6,
        isOneClickRegister: false,
        password: null,
        isChangePassword: 0,
        tgLink: '',
        tgInitData: '',
        agentInfo: {},
        guested: false
    }),
    getters: {
        isLogin: (state) => {
            if (!state.sign || !state.uid) {
                return false
            } else {
                return true
            }
        },
        isUserLogin: (state) => {
            return false
        }
    },
    actions: {
        async getAgentInfoV2() {
            const { code, data } = await getAgentV2Home()
            if (code == 200) {
                this.agentInfo = data || {}
            }
        },
        async getUserInfo() {
            const {data} = await requestUserInfo({})
            this.userInfo = data
        },
        async getUserTotalInfo() {
            const appStore = useAppStore()
            const resList = await Promise.all([requestUserInfo(), getVipInfo()])

            if (!Array.isArray(resList)) {
                return false
            }
            if (resList[0].code === 200) {
                this.userInfo = resList[0].data || {}

                if (this.userInfo.regChannel) {
                    appStore.channelId = this.userInfo.regChannel
                }
            }
            if (resList[1].code === 200) {

                this.vipInfo = resList[1].data || {}
                this.currentVipLevel = this.vipInfo.currentVipConfig.level || 0
            }
            this.saveToLocal()
            this.getServiceInfo()
            this.getAgentInfo()
            return true
        },
        // 暂时合并处理
        // 	async getUserInfo () {
        // 		const { code, data } = await requestUserInfo()
        // 		if (code !== 200) { return false }
        // 		this.userInfo = data || {}

        // 		this.saveToLocal()
        // 		return true
        // 	},
        // 	async getUserVipInfo () {
        // 		const { code, data } = await getVipInfo()
        // 		if (code !== 200) { return false }
        // 		this.vipInfo = data || {}

        // 		this.saveToLocal()
        // 		return true
        // 	},

        async guestLogin() {
            const appStore = useAppStore()
            // #ifdef H5
            const initData = localStorage.getItem('TgInitData')
            // #endif
            const params = {
                deviceName: appStore.systemInfo.deviceModel,
                systemVersion: appStore.systemInfo.SDKVersion,
                appVersion: appStore.systemInfo.appVersion,
                referralCode: appStore.inviteCode,
                // #ifdef H5
                tgAuth: initData || ''
                // #endif
            }
            const { code, data } = await requestGuestLogin(params)
            if (code !== 200) {
                this.logout()
                this.sign = ''
                this.uid = ''
                this.newUserFlag = false
                this.guested = true
                this.saveToLocal()
                uni.reLaunch({
                    url: '/pages/Login/Login'
                })
                // uni.switchTab({
                // 	url: '/pages/home/home'
                // })
                return Promise.reject(false)
            }
            this.sign = data.sign || ''
            this.uid = data.uid || ''
            this.newUserFlag = data.newUserFlag || false
            this.password = data.password || null
            this.saveToLocal()

            // reportAdjustAdid()
            await this.getUserTotalInfo()
            return data
        },
        getInitData() {
            const initData = localStorage.getItem('TgInitData')
            console.log(initData);
            this.tgInitData = initData
        },
        /**
         * 手机号 + 验证码登陆
         */
        async optLogin({ phoneNumber, verifyCode }) {
            if (!phoneNumber || !verifyCode) {
                return false
            }
            const appStore = useAppStore()
            const { code, data } = await requestLogin({
                deviceName: appStore.systemInfo.deviceModel,
                systemVersion: appStore.systemInfo.SDKVersion,
                appVersion: appStore.systemInfo.appVersion,
                referralCode: appStore.inviteCode,
                mobile: phoneNumber,
                verificationCode: verifyCode
            })
            if (code !== 200) {
                return false
            }
            this.sign = data.sign || ''
            this.uid = data.uid || ''
            this.newUserFlag = data.newUserFlag || false
            this.saveToLocal()

            // reportAdjustAdid()
            await this.getUserTotalInfo()
            return true
        },
        async passwordLogin({ phoneNumber, password }) {
            if (!phoneNumber || !password) {
                return false
            }
            const appStore = useAppStore()
            const { code, data } = await passwordLogin({
                referralCode: appStore.inviteCode,
                mobile: phoneNumber,
                password: password
            })
            if (code !== 200) {
                return false
            }
            this.sign = data.sign || ''
            this.uid = data.uid || ''
            this.newUserFlag = data.newUserFlag || false
            this.saveToLocal()

            // reportAdjustAdid()
            await this.getUserTotalInfo()
            return true
        },
        async idPasswordLogin({ phoneNumber, password }) {
            if (!phoneNumber || !password) {
                return false
            }
            const appStore = useAppStore()
            const { code, data } = await requestIdPasswordLogin({
                referralCode: appStore.inviteCode,
                userId: phoneNumber,
                password: password
            })
            if (code !== 200) {
                return false
            }
            this.sign = data.sign || ''
            this.uid = data.uid || ''
            this.newUserFlag = data.newUserFlag || false
            this.saveToLocal()

            // reportAdjustAdid()
            await this.getUserTotalInfo()
            return true
        },
        async googleLogin(options) {
            if (!options || !options.id) {
                return false
            }
            const appStore = useAppStore()
            const { code, data } = await requestGoogleLogin({
                referralCode: appStore.inviteCode,
                googleToken: options.accessToken,
                googleId: options.id,
                email: options.email,
                name: options.name,
                familyName: options.family_name,
                givenName: options.given_name,
                avatar: options.picture
            })
            if (code !== 200) { return false }
            this.sign = data.sign || ''
            this.uid = data.uid || ''
            this.newUserFlag = data.newUserFlag || false
            this.saveToLocal()

            // reportAdjustAdid()
            await this.getUserTotalInfo()
            return true
        },
        async getServiceInfo() {
            const { code, data } = await requestServiceList()
            if (code !== 200) { return }
            this.serviceInfo = data || {}
            if (data.mobile && data.mobile.length) {
                const tg = data.mobile.find(item => item.mobileName == 'Telegram')
                if (tg) {
                    this.tgLink = tg.mobileNumber[0]
                }
                const faq = data.mobile.find(item => item.mobileName == 'WebCS')
                if(faq) {
                    const appStore = useAppStore()
                    appStore.FAQ = faq.mobileNumber[0]
                }
                const getObjWithName = (list, name) => {
                    for (let i = 0; i < list.length; i++) {
                        if (name === list[i].mobileName) {
                            return list[i]
                        }
                    }
                    return null
                }

                let vipLevel = 0
                if (this.vipInfo.currentVipConfig && this.vipInfo.currentVipConfig.level) {
                    vipLevel = this.vipInfo.currentVipConfig.level
                }

                const vipCS = getObjWithName(data.mobile, 'VipCS')
                const vipWebCS = getObjWithName(data.mobile, 'VipWebCS')
                const webCS = getObjWithName(data.mobile, 'WebCS')

                let url = ''
                if (vipLevel > vipCS.minVipLevel) {
                    if (vipCS && vipCS.mobileNumber && vipCS.mobileNumber.length) {
                        url = vipCS.mobileNumber[0]
                    } else if (vipWebCS && vipWebCS.mobileNumber && vipWebCS.mobileNumber.length) {
                        url = vipWebCS.mobileNumber[0]
                    }
                } else {
                    if (webCS && webCS.mobileNumber && webCS.mobileNumber.length) {
                        url = webCS.mobileNumber[0]
                    }
                }

                this.minVipLevel = vipCS.minVipLevel || 6
                this.serviceUrl = url
            }
            this.saveToLocal()
        },
        async getAgentInfo() {
            const { code, data } = await getAgentInfoApi()
            if (code == 200) {
                const appStore = useAppStore()
                appStore.inviteLink = data.referralUrl
            }
        },
        async reportOnline(id) {
            const { code } = await requestReportOnline({
                placeId: id
            })
        },
        startReportOnline() {
            setInterval(() => {
                if (this.isLogin) {
                    this.getUserTotalInfo()
                }
            }, 30000)


            if (this.isLogin) {
                this.reportOnline(1)
            }
            setInterval(() => {
                if (this.isLogin) {
                    this.reportOnline(1)
                }
            }, 1 * 60 * 1000)
        },
        logout() {
            uni.removeStorageSync(userInfoStoreKey)
            uni.removeStorageSync(vipInfoStoreKey)
            uni.removeStorageSync(serviceInfoStoreKey)
            uni.removeStorageSync(signStoreKey)
            uni.removeStorageSync(uidStoreKey)
            uni.removeStorageSync(serviceUrlStoreKey)
            uni.removeStorageSync(minVipLevelStoreKey)
            this.asyncFromLocal()
        },
        asyncFromLocal() {
            const userInfo = uni.getStorageSync(userInfoStoreKey)
            this.userInfo = userInfo || {}

            const vipInfo = uni.getStorageSync(vipInfoStoreKey)
            this.vipInfo = vipInfo || {}

            const serviceInfo = uni.getStorageSync(serviceInfoStoreKey)
            this.serviceInfo = serviceInfo || {}

            const sign = uni.getStorageSync(signStoreKey)
            this.sign = sign || ''

            const uid = uni.getStorageSync(uidStoreKey)
            this.uid = uid || ''

            const serviceUrl = uni.getStorageSync(serviceUrlStoreKey)
            this.serviceUrl = serviceUrl || ''

            const minVipLevel = uni.getStorageSync(minVipLevelStoreKey)
            this.minVipLevel = minVipLevel || ''
        },
        saveToLocal() {
            uni.setStorageSync(userInfoStoreKey, this.userInfo)
            uni.setStorageSync(vipInfoStoreKey, this.vipInfo)
            uni.setStorageSync(serviceInfoStoreKey, this.serviceInfo)
            uni.setStorageSync(signStoreKey, this.sign)
            uni.setStorageSync(uidStoreKey, this.uid)
            uni.setStorageSync(serviceUrlStoreKey, this.serviceUrl)
            uni.setStorageSync(minVipLevelStoreKey, this.minVipLevel)
        }
    }
})