import { toRefs, shallowReadonly, ShallowRef } from 'vue'
import { AppTheme } from '@/constants/theme'
import { VueStore } from '../base'
import WebStorage from '@/utils/storage/base'
import plus from '@/utils/h5plus'

interface StoreState {
    appTheme: ShallowRef<AppTheme>;
}

const store = new (class extends VueStore<StoreState>{
    constructor() {
        const storage = new WebStorage<AppTheme>(localStorage, 'appTheme', AppTheme.Light)
        const state: StoreState = {
            appTheme: storage.getRef()
        }

        super(state)
        document.addEventListener('DOMContentLoaded', this.loadTheme, false)
    }

    /**
     * 加载主题
     */
    private loadTheme = () => {
        const theme = this.state.appTheme
        this.setStatusBarTheme(theme)
        document.documentElement.setAttribute('theme', theme)
        document.removeEventListener('DOMContentLoaded', this.loadTheme)
    }

    /**
     * 设置状态栏主题色
     * @param theme 
     */
    private setStatusBarTheme = (theme: AppTheme) => {
        switch (theme) {
            case AppTheme.Default:
            case AppTheme.Dark: {
                plus.setStatusBarStyle('light')
                break
            }
            default: {
                plus.setStatusBarStyle('dark')
            }
        }
    }

    actions = {
        /** 设置主题 */
        setTheme: (key: keyof typeof AppTheme) => {
            const theme = AppTheme[key]
            this.setStatusBarTheme(theme)
            document.documentElement.setAttribute('theme', theme)
            this.state.appTheme = theme
        }
    }
})

export function useThemeStore() {
    return shallowReadonly({
        ...toRefs(store.state),
        ...store.actions,
        ...store.methods,
    })
}