/**
 *  翻译数据
 * 
 */
import Storage from '@/common/utils/storage'
import { defineStore } from 'pinia'
import EXEC from "@/common/utils/exec"
import { menusStore } from './menus'

export const langStore = defineStore('lang', {
  state: () => ({
    lang: <any>'cn',
    langList: <any>{},
    langOptions: <any>{}, //api请求回来的语言选择列表
  }),
  getters: {
    getForKey: (state) => {
      return (key:string) => {
        let comp_id = EXEC.comp_id.toLocaleLowerCase()
        let menu_id = menusStore().currentMenu?.id

        /**
         * 优先级：
         * 1, 找[当前公司][当前菜单]
         * 2, 找[当前公司][*]
         * 3, 找[*][当前菜单]
         * 4, 找[*][*]
         */
        let row = '', type='[key]';
        if(state.langList[comp_id] && state.langList[comp_id][menu_id] && state.langList[comp_id][menu_id][key]){ 
          //[当前公司][当前菜单]  
          row = state.langList[comp_id][menu_id][key];
          type = `[${comp_id}][${menu_id}]`
        }
        else if(state.langList[comp_id] && state.langList[comp_id]['*'][key]) { 
          //[当前公司][*]
          row = state.langList[comp_id]['*'][key];
          type = `[${comp_id}][*]`
        }
        else if(state.langList['*'][menu_id] && state.langList['*'][menu_id][key]) { 
          //[*][当前菜单]
          row = state.langList['*'][menu_id][key];
          type = `[*][${menu_id}]`
        }
        else if(state.langList['*']['*'][key]) { 
          //[*][*]
          row = state.langList['*']['*'][key];
          type = `[*][*]`
        }
        return row
      }
    },

  },
  actions: {
    // topBar 右侧选择语言触发
    changeLang(lang:any){
      this.lang = lang || 'cn'
      Storage.set('lang',lang)
    },

    // 保存语言包；indexCreate触发；
    saveLang(result:any){
      let newList = {}
      for(let key1 in result){
        let itemList = {}
        for(let key in result[key1] ){
          Object.assign(itemList, {
            [key.toLocaleLowerCase()]:result[key1][key] 
          })
        }
        Object.assign(newList, {
          [key1.toLocaleLowerCase()]: itemList
        })
      }
      Object.assign(this.langList, {...newList})
    },

    // 保存语言选择包；indexCreate触发；
    saveLangOptions(result:any){
      this.langOptions = result
    },

  }

})
