import { defineStore } from 'pinia'
import { getCurrentLang } from '@/locale/index'
import { getLocaleListApi } from '@/apis/system'


export interface ISystemState {
  locale: string;
  localeList: ILangs[];
  screenWidth: number;
}

export interface ILangs {
  code: string;
  title: string; 
}

export interface ICurrencys {
  code: string;
  title: string;
  symbol: string;
  rate: string | number; 
}



const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    locale: getCurrentLang() as string,
    localeList: [
      { title: '中文（简体）', code: 'zh' },
      { title: 'English', code: 'en' },
    ],
    screenWidth: 1920
  }),

  getters: {
    localeInfo: function (): ILangs {
      const result = this.localeList.find((item: ILangs) => (item.code == this.locale))
      return result ? result : this.localeList[1]
    }
  },

  actions: {
    toggleLocale(localeInfo: ILangs) {
      if (localeInfo) {
        this.locale = localeInfo.code
        localStorage.setItem('locale', localeInfo.code)
      }
    },

    updateScreenWidth(width: number) {
      if (width < 325) {
        this.screenWidth = 325
      }
      else {
        this.screenWidth = width
      }
    },

    fetchLocaleList() {
      type resultType = Object & {
        data: { langs: ILangs[] }
      }
      getLocaleListApi({})
        .then((result: resultType) => {
          console.log('---- result -----', result)
          this.localeList = result.data.langs && result.data.langs.length > 0 ? result.data.langs : this.localeList
        })
        .catch((err: Error) => {

        })
    }
  }
})



export default useSystemStore