// {
// 	"SDKVersion": "",
// 	"appId": "__UNI__C134CA0",
// 	"appLanguage": "zh-Hans",
// 	"appName": "UniSpinz777",
// 	"appVersion": "1.0.0",
// 	"appVersionCode": "100",
// 	"browserName": "chrome",
// 	"browserVersion": "123.0.0.0",
// 	"deviceId": "17109142510822530668",
// 	"deviceModel": "PC",
// 	"deviceOrientation": "portrait",
// 	"devicePixelRatio": 2,
// 	"deviceType": "pc",
// 	"hostLanguage": "zh-CN",
// 	"hostName": "chrome",
// 	"hostTheme": "light",
// 	"hostVersion": "123.0.0.0",
// 	"language": "zh-CN",
// 	"model": "PC",
// 	"osName": "macos",
// 	"osVersion": "10.15.7",
// 	"pixelRatio": 2,
// 	"platform": "macos",
// 	"safeArea": {
// 		"bottom": 451,
// 		"height": 451,
// 		"left": 0,
// 		"right": 993,
// 		"top": 0,
// 		"width": 993
// 	},
// 	"safeAreaInsets": {
// 		"bottom": 0,
// 		"left": 0,
// 		"right": 0,
// 		"top": 0
// 	},
// 	"screenHeight": 1050,
// 	"screenWidth": 1680,
// 	"statusBarHeight": 0,
// 	"system": "macOS 10.15.7",
// 	"ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
// 	"uniCompileVersion": "3.99",
// 	"uniPlatform": "web",
// 	"uniRuntimeVersion": "3.99",
// 	"version": "",
// 	"windowBottom": 0,
// 	"windowHeight": 451,
// 	"windowTop": 0,
// 	"windowWidth": 993
// }

//
// 孟加拉
// currencySign: '৳',
// phoneNumberPrefix: '+880',
// timeZone: 'GMT+5.5',

// 印尼
// currencySign: 'RP',
// phoneNumberPrefix: '+62',
// timeZone: 'GMT+5.5',

import { defineStore } from 'pinia'
import { requestAppConfig, requestAppLanguages, requestAppUpdate } from '@/api/app'
import GlobalConfig from '@/config/global.config.js'
import { get } from 'lodash'
import { versionCompare } from '@/module/utils/util'

const webBrowserNameList = ['chrome', 'edge', 'safari', 'firefox']
const isNativeStoreKey = 'APP_IS_NATIVE_STORE_KEY'
const appStatusBarHeightKey = 'APP_STATUS_BAR_HEIGHT_KEY'
const isCoatStoreKey = 'APP_IS_COAT_STORE_KEY'
const inviteCodeStoreKey = 'APP_INVITE_CODE_STORE_KEY'
const h5NoStoreKey = 'APP_H5_NO_STORE_KEY'
const channelIdKey = 'CHANNEL_ID_KEY'

export const useAppStore = defineStore({
    id: 'app',
    state: () => ({
        appDownloadHomeVisible: true,
        appName: import.meta.env.VITE_APP_NAME,
        appVersion: '1.0.0',
        appDownloadUrl: import.meta.env.VITE_APP_DOWNLOAD_URL,
        appId: process.env.APP_ID || import.meta.env.VITE_APP_ID || 101,
        appTheme: import.meta.env.VITE_APP_THEME || 'red',
        appDescription: '',
        appLocale: import.meta.env.VITE_APP_LOCALE || 'en',
        isNative: false,
        appStatusBarHeight: 0,
        isCoat: false,
        h5No: import.meta.env.VITE_APP_H5_NO || 1,
        channelId: "",
        inviteCode: '',
        adjustAdid: '',
        roibestLinkId: '',
        inviteLink: '',
        hasShowActivity: false,
        useEarnV2: false,
        earnV2TabIndex: 0,
        deviceId: '',
        gaid: '',

        // lk7数据
        lk7data: '',
        showLk7Update: false,

        // #ifdef H5-306
        currencySign: '৳',
        phoneNumberPrefix: '+880',
        timeZone: 'GMT+5.5',
        // #endif
        // #ifndef H5-306
        currencySign: process.env.APP_CURRENCY_SIGN || '₹',
        phoneNumberPrefix: process.env.APP_PHONE_NUMBER_PREFIX || '+91',
        timeZone: '',
        // #endif

        mcId: '',
        appConfig: {},
        faqUrl: '',
        manualRechargeUrl: '',
        systemInfo: {},
        deviceInfo: {},
        windowInfo: {},
        fbc: '',
        fbp: '',
        uniKey: '',
        FAQ: 'https://direct.lc.chat/18923505/',
        progress: 0,
        updateReady: false,
        installSuccess: "",
        androidId: '',
        updateData: {
            updateText: '',
            updateType: 0
        },
        packageName: 'uni.UNIFECBD22',//101 Spinz777
        // packageName: 'uni.UNIFECBD22', //102 
        // packageName: 'com.kllksgqoCasw3d.game',//103 Winzz777
    }),
    // 	"dependencies": [
    //       {
    //           "id": "com.google.android.gms:play-services-ads-identifier",
    //           "source": "implementation com.google.android.gms:play-services-ads-identifier:18.0.1"
    //       }
    //   ],
    getters: {
        startImgUrls: (state) => {
            const urlPrefix = GlobalConfig.appImageStartPrefix
            const urls = {
                logo: urlPrefix + '/splash_logo.png',
                loginLogo: urlPrefix + '/splash_logo.png',
                headerLogo: urlPrefix + '/logo.png'
            }
            return urls
        },
        isShowAppDownload: (state) => {
            // if (state.appDownloadHomeVisible === false
            // 	|| !state.appDownloadUrl
            // 	|| state.isNative
            // 	|| state.systemInfo.uniPlatform === 'app') {
            // 	return false
            // }
            // return true
            if (state.isNative) {
                return false
            }
            return state.appDownloadHomeVisible
        },
        isMobile: (state) => {
            if (state.deviceInfo && state.deviceInfo.deviceType === 'PC') {
                return false
            } else {
                return true
            }
        },
        isMobileView: (state) => {
            if (state.windowInfo && state.windowInfo.windowWidth > 768) {
                return false
            } else {
                return true
            }
        },
        headerStyle: (state) => {
            const windowInfo = state.windowInfo
            
            let statusBarHeight = windowInfo.safeAreaInsets ? windowInfo.safeAreaInsets.top : 0
            if (state.systemInfo.uniPlatform === 'app' && statusBarHeight === 0) {
                statusBarHeight = 44
            } else if (state.isNative) {
                statusBarHeight = state.appStatusBarHeight || 44
            }
            // pwa写死
            const pwaNo = []
            if (pwaNo.includes(process.env.APP_H5_NO) || state.isCoat) {
                statusBarHeight = 10
            }

            return {
                statusBarHeight: statusBarHeight,
                navigateBarHeight: 50,
                height: statusBarHeight + 50
            }
        },
        requestLocale: (state) => {
            const map = [
                {
                    locale: 'en',
                    requestLocale: 'en'
                },
                {
                    locale: 'ja',
                    requestLocale: 'jp'
                },
                {
                    locale: 'ind',
                    requestLocale: 'id'
                },
            ]
            const obj = map.find(el => {
                return state.appLocale.includes(el.locale) || el.locale.includes(state.appLocale)
            })
            if (obj) {
                return obj.requestLocale
            }
            return 'en'
        }
    },
    actions: {
        setUpdateReady(bool) {
            this.updateReady = bool
        },
        async getInfo() {
            // const systemInfo = uni.getSystemInfoSync()
            // this.systemInfo = systemInfo
            // console.log('systemInfo', systemInfo)
            // if(systemInfo.uniPlatform === 'app') {
            // 	this.isNative = true
            // }
            // uni.showModal({
            // 	content: JSON.stringify(this.systemInfo)
            // })

            const windowInfo = uni.getWindowInfo()
            this.windowInfo = windowInfo
            console.log('windowInfo', windowInfo)


            console.log('current language', this.systemInfo.language, 'current device', this.systemInfo.deviceModel, 'screen', windowInfo
                .screenHeight, windowInfo.screenWidth)


            const { code, data } = await requestAppConfig()
            console.log('appConfig', data);

            if (code === 200) {
                const appConfig = data || {}

                this.useEarnV2 = data.agentVersionV2 || false
                // if(appDownloadUrl) {
                // 	this.appDownloadUrl = appDownloadUrl
                // }
                if (appConfig.config) {
                    const config = JSON.parse(data.config)
                    this.manualRechargeUrl = config.manual_recharge_url || ''
                    this.faqUrl = config.faq_url || ''
                }
                this.appConfig = appConfig
            }
            this.getConfigData()
        },
        async getConfigData() {
            const { code, data } = await requestAppLanguages()
            if (code === 200) {
            }
        },
        windowSizeChange() {
            const windowInfo = uni.getWindowInfo()
            this.windowInfo = windowInfo
            console.log('screen', windowInfo.windowHeight, windowInfo.windowWidth)
        },
        asyncFromLocal() {
            const isNative = uni.getStorageSync(isNativeStoreKey)
            this.isNative = isNative || false

            const appStatusBarHeight = uni.getStorageSync(appStatusBarHeightKey)
            this.appStatusBarHeight = appStatusBarHeight || 0

            const isCoat = uni.getStorageSync(isCoatStoreKey)
            this.isCoat = isCoat || false

            const inviteCode = uni.getStorageSync(inviteCodeStoreKey)
            this.inviteCode = inviteCode || ''

            const h5No = uni.getStorageSync(h5NoStoreKey)
            this.h5No = h5No || import.meta.env.VITE_APP_H5_NO || 1
            console.log('useAppStore h5No:', h5No);

            const channelId = uni.getStorageSync(channelIdKey)
            if (channelId) {
                this.channelId = channelId
            }
            // this.channelId = channelId || ''
        },
        saveToLocal() {
            uni.setStorageSync(isNativeStoreKey, this.isNative)
            uni.setStorageSync(appStatusBarHeightKey, this.appStatusBarHeight)
            uni.setStorageSync(isCoatStoreKey, this.isCoat)
            uni.setStorageSync(inviteCodeStoreKey, this.inviteCode)
            console.log('saveToLocal h5No:', this.h5No);
            
            uni.setStorageSync(h5NoStoreKey, this.h5No)
            uni.setStorageSync(channelIdKey, this.channelId)
        },
        removeFromLocal() {
            uni.removeStorageSync(isNativeStoreKey)
            uni.removeStorageSync(appStatusBarHeightKey)
            uni.removeStorageSync(isCoatStoreKey)
            uni.removeStorageSync(inviteCodeStoreKey)
            uni.removeStorageSync(h5NoStoreKey)
        },
        setProgress(progress) {
            this.progress = progress
        },
        // #ifdef APP-PLUS
        getAppUpdate() {
            let _this = this
            return new Promise((resolve, reject) => {
                plus.runtime.getProperty(plus.runtime.appid, async function (widgetInfo) {
                    console.log("widgetInfo:", widgetInfo)
                    const { data } = await requestAppUpdate({ versionCode: widgetInfo.version })
                    console.log("appVersion:", data)
                    if (versionCompare(data.version, widgetInfo.version) > -1) {
                        console.log("can update");
                        
                        if(data.updateType === 0) {
                            resolve()
                        } else {
                            _this.setUpdateReady(true)
                            _this.updateData = data;
                            resolve()
                        }
                    } else {
                        resolve()
                    }
                })
            })
        },
        // #endif
    }
})