import { ApiResult } from './../configs/axios';
import { defineStore } from 'pinia'
import FontService from '@/services/FontService'
import { ElLoading } from 'element-plus'
// import type { StorageLike } from 'pinia-plugin-persistedstate';
// import SecureLS from 'secure-ls';
// const ls = new SecureLS({
//     isCompression: false,
//     encryptionSecret: '38c31684-d00d-30dc-82e0-fad9eec46d1d',
// });
// const st: StorageLike = {
//     setItem(key: string, value: string) {
//         ls.set(key, value);
//     },
//     getItem(key: string): string | null {
//         return ls.get(key);
//     },
// };
export interface CustomerFonts {
    fontUrl: string
    fontFamily: string
    label: string
    reduceName:string
    reduceUrl:string
}

export interface FormatFonts {
    label: string,
    value: string,
    reduce: string
}

export interface FontState{
    fonts:CustomerFonts[],
    loaded:string[],
    formatFonts:FormatFonts[],
    restoreLoaded:string[]
}

export const useFontStore = defineStore('fonts',{
    state: ():FontState => ({
        fonts:[],
        loaded:[],
        formatFonts:[],
        restoreLoaded:[]
    }),
    getters:{
        getFonts(state){
            return state.fonts
        }
    },
    actions:{
        async loadAllFonts () {
            try {
                let response  = await FontService.GetAllFontsAsync()
                if(response.data.resultCode == ApiResult.SUCCESS && response.data.data){
                    this.fonts = response.data.data as CustomerFonts[]
                    this.formatFonts = []
                    this.fonts.forEach(x=>{
                        this.formatFonts.push({ label: x.label,value:x.fontFamily,reduce:x.reduceName })
                    })

                    setTimeout(() => {
                        this.loadAllReduceFont()
                    }, 1000);
                }

            } catch (error) {
            }
        },
        async loadAllReduceFont(index:number=-1){
            for (let i = 0; i < this.fonts.length; i++) {
                if(index!=-1 && index!=i) continue
                const f = this.fonts[i];
                if(f.reduceUrl && f.reduceUrl!=''){
                    let newStyle = document.createElement('style');
                    const fontFormat = 'opentype'
                    newStyle.setAttribute("type", "text/css");
                    newStyle.appendChild(document.createTextNode("\
                        @font-face {\
                            font-family: '" + f.reduceName + "';\
                            src: url('"+f.reduceUrl+"') format('"+fontFormat+"');\
                        }\
                    "));
                    document.head.appendChild(newStyle);
                }
                
            }
        },
        async loadFontToDocument(items:string[]){
            const loadingInstance = ElLoading.service({
                lock:true,
                text:'正在加载字体文件'
            })
           
            let fonts = Array.from(new Set(items))
            for (let i = 0; i < fonts.length; i++) {
                fonts[i] = fonts[i].split(',')[0]
            }
            fonts = fonts.filter(x=>this.loaded.indexOf(x)==-1)
            const loadFonts = this.fonts.filter(x=>fonts.indexOf(x.fontFamily)!=-1)
            if(loadFonts && loadFonts.length>0){
                for (let i = 0; i < loadFonts.length; i++) {
                    const item = loadFonts[i];
                    const url = item.fontUrl.indexOf('local')==-1?`url('${item.fontUrl}')`:item.fontUrl
                    const fontFace = new FontFace(item.fontFamily,url);
                        
                    try {
                        fontFace.display = "swap"
                        await fontFace.load();
                        
                    } catch (error) {
                    }
                    document.fonts.add(fontFace)
                    this.loaded.push(item.fontFamily)
                    let newStyle = document.createElement('style');
                    const fontFormat = item.fontUrl.toLowerCase().indexOf('.ttf')!=-1?'truetype':(item.fontUrl.toLowerCase().indexOf('.otf')!=-1?'opentype':`'${item.fontUrl.split('.').reverse()[0]}'`)
                    newStyle.setAttribute("type", "text/css");
                    newStyle.appendChild(document.createTextNode("\
                        @font-face {\
                            font-family: '" + item.fontFamily + "';\
                            src: "+url+" format("+fontFormat+");\
                        }\
                    "));
                    document.head.appendChild(newStyle);
                }
            }
            loadingInstance.close()
            //console.log(loadingInstance)
        },
        async uploadFontAsync(item:CustomerFonts) {
            let data:any = JSON.parse(JSON.stringify(item))
            try {
                const response = await FontService.SetFontAsync(data)
                if(response.data.resultCode == ApiResult.SUCCESS){
                    this.fonts.push(response.data.data)
                    this.formatFonts.push({
                        label:item.label,
                        value:item.fontFamily,
                        reduce:item.reduceName
                    })
                    this.loadAllReduceFont(this.fonts.length-1)
                    return true
                }
            } catch (error) {
                
            }
            return false
        }
    },
    // persist: {
    //     storage: st,
    //     paths:['loaded'],
    //     afterRestore(context) {
    //         console.log('还原了....',context.store.loaded)
    //         context.store.restoreLoaded = JSON.parse(JSON.stringify(context.store.loaded))
    //         context.store.loaded = []
    //         console.log('修改了....',context.store.loaded)
    //     },
    // }
})