import { ApiResult } from './../configs/axios';
import { defineStore } from 'pinia'
import FontService from '@/services/FontService'
import { ElLoading } from 'element-plus'

export interface CustomerFonts {
    fontUrl: string
    fontFamily: string
    label: string
}

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

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

export const useFontStore = defineStore('fonts',{
    state: (): FontState => ({
        fonts:[],
        loaded:[],
        formatFonts:[]
    }),
    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 })
                    })
                }

            } catch (error) {
                console.log('初始化字体信息失败')
            }
        },
        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];
                    try {
                        const url = item.fontUrl.indexOf('local')==-1?`url('${item.fontUrl}')`:item.fontUrl
                        const fontFace = new FontFace(item.fontFamily,url);
                        fontFace.display = "swap"
                        await fontFace.load();
                        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.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);
                    } catch (error) {
                        console.log('加载字体报错',error)
                    }
                }
            }
            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(item)
                    this.formatFonts.push({
                        label:item.label,
                        value:item.fontFamily
                    })
                    return true
                }
            } catch (error) {
                
            }
            return false
        }
    }
})