import { login_wechat_applets } from "@/common/apis/base"
import Storage from "@/common/utils/storage"
import { get_user_comp_config, get_switch_lng, post_switch_operdb, get_user_menu } from "@/common/apis/base"
import { get_sec_storeds } from '@/common/apis/storeds'
import { Socket } from '@/common/utils/socket'
import EXEC from "../exec"
import { langStore } from "@/common/stores/lang"
import { menusStore } from '@/common/stores/menus'



// 加载权限页面
export const indexCreate = async () => {
  return new Promise( async (resolve, reject) => {
    /**
     * 此函数在路由卫士中，判断登陆状态后运行；
     * 1, 获取公司》系统》数据库列表，获取语言列表
     * 2, 获取本地缓存的公司》系统》数据库、语言； 如果不存在，则使用列表第一个； 选择并缓存
     * 3, 获取菜单
     * 4, socket
     */

    // 获取列表； 公司》系统》数据库
    await get_user_comp_config({}).then((result:any) => {
      let res = result['result']
      set_option_comp_system_db(res)
    })  

    // 获取翻译并保存
    let storageLang:any = Storage.get('lang') || 'cn' 
    langStore().changeLang(storageLang)
    await get_switch_lng({lng: storageLang}).then((result:any)=>{
        let res = result['result']
        langStore().saveLang(res)
    })


    // 长连接
    Socket.create()
    
    Storage.remove('Options')
  })
}

// 设置 公司》系统》数据库（权限内容）
const set_option_comp_system_db = async (data:any) => { 
  let list_obj:any = {}
  EXEC.comp_id = Storage.get('comp_id') || ''
  EXEC.comp_name = Storage.get('comp_name') || ''
  EXEC.system_id = Storage.get('system_id') || ''
  EXEC.system_name = Storage.get('system_name') || ''
  EXEC.db_code = Storage.get('db_code') || ''
  EXEC.db_name = Storage.get('db_name') || ''

  for(let comp of data){
    if(!EXEC.comp_id) {
      EXEC.comp_id = comp.comp_id
      EXEC.comp_name = comp.comp_name
      Storage.set('comp_id', EXEC.comp_id)
      Storage.set('comp_name', EXEC.comp_name)
    }
    let compObj:any = {
      comp_id: comp.comp_id,
      comp_name: comp.comp_name,
      value: comp.comp_id,
      text: comp.comp_name,
      systems: {}
    }
    for(let sys of comp.children.systems){
      if(!EXEC.system_id) {
        EXEC.system_id = sys.system_id
        EXEC.system_name = sys.system_name
        EXEC.db_code = sys.db_code
        EXEC.db_name = sys.db_name
        Storage.set('system_id', EXEC.system_id)
        Storage.set('system_name', EXEC.system_name)
        Storage.set('db_code', EXEC.db_code)
        Storage.set('db_name', EXEC.db_name)
      }
      let system = {
        system_id: sys.system_id,
        system_name: sys.system_name,
        system_descr: sys.system_descr,
        theme_color: sys.theme_color,
        value: sys.system_id,
        text: sys.system_name,
      }
      let db = {
        db_code: sys.db_code,
        db_name: sys.db_name,
        value: sys.db_code,
        text: sys.db_name,
      }

      if(!compObj.systems[sys.system_id]){
        Object.assign(compObj.systems, {
          [sys.system_id]: {
            ...system,
            dbs: {
              [sys.db_code]: { ...db },
            }
          }
        })
      }else{
        Object.assign(compObj.systems[sys.system_id].dbs, {
          [sys.db_code]: { ...db },
        })
      }
    }
    Object.assign(list_obj, {
      [comp.comp_id]: { ...compObj }
    })
  }

  EXEC.list_obj = list_obj
  let list_arr:any = []
  for(let compkey in list_obj){
    let comp = list_obj[compkey]
    let compObj:any = {
      value: comp.value,
      text: comp.text,
      children: []
    }
    for(let sysKeyt in comp.systems){
      let sys = comp.systems[sysKeyt]
      let sysObj:any = {
        value: sys.value,
        text: sys.text,
        children: []
      }
      for(let dbKey in sys.dbs){
        let db = sys.dbs[dbKey]
        let dbObj:any = {
          value: db.value,
          text: db.text,
        }
        sysObj.children.push(dbObj)
      }
      compObj.children.push(sysObj)
    }
    list_arr.push(compObj)
  }
  EXEC.list_arr = list_arr
  set_db().then(()=>{
    saveMenus()
  })
}
// 设置 语言包
export const set_db = async () => {
    return new Promise<void>((resolve, reject) => {
      post_switch_operdb({
        db_code: EXEC.db_code ,
      }).then( async (result:any) => {
          let res = result['result']
          EXEC.user_id = res.user_id
          EXEC.user_name = res.user_name
          EXEC.identity_roles_arr = []
          EXEC.identity_roles_obj = {}
          Storage.remove('identity_role')
          if(res.identity_roles){
            for(let item of res.identity_roles){
              let newItem = {
                ...item,
                value: item.identity_role,
                label: item.identity_role_name
              }
              await Object.assign(EXEC.identity_roles_obj, {
                [item.identity_role]: newItem
              })
              await EXEC.identity_roles_arr.push(newItem)
            }
          }else{
            EXEC.identity_roles_obj = {}
            EXEC.identity_roles_arr = []
          }
          
          resolve()
      })
    })
}


export const saveMenus = async () => {

  get_user_menu({}).then((result:any) => {
    save(result['result'])
  })
  function save (resultData:any) {
    /**
     * 1, 处理菜单； 扁平标示， 按钮， 树等等
     * 2, 处理动态路由； 设置meta元数据； 添加动态页面路由， 删除没权限路由； 
     */
    let menus = [], // 菜单树：  
        menus_obj_id = {}, // 扁平菜单：[id]: item  方便组件中根据当前menu_id查找
        menus_obj_path = {}, // 扁平菜单: [path]: item  方便组件中根据当前path查找
        menus_favorite:any = [], // 扁平收藏菜单

        menus_roles = {}

    for(let i in resultData){// 一级菜单层；
        let lv1 = resultData[i]
        let obj1 = {
            id: lv1['menu_id'],
            name: lv1['menu_name'],
            index: [i],
            childrens: <any>[],
        }
        for(let ii in lv1['children']){// 二级菜单层；
            let lv2 = lv1['children'][ii]
            let obj2 = {
                id: lv2['menu_id'],
                name: lv2['menu_name'],
                index: [i, ii],
                childrens: <any>[],
            }
            for(let iii in lv2['children']){ // 三级菜单层； 打开页面
                let lv3 = lv2['children'][iii]
                let obj3 = {
                    id: lv3['menu_id'],
                    name: lv3['menu_name'],
                    index: [i, ii, iii],
                    path: lv3['dynamic_page']=='Y'? `/dynamic/${lv3['dynamic_path']||lv3['menu_id']}` : lv3['button_path'],
                    icon_path: lv3['icon_path'],
                    isDynamic: lv3['dynamic_page']=='Y'?true:false,
                    isFavorite: lv3['is_favorite']=='Y'?true:false, 
                    childrens: <any>[],
                    buttons: <any>[],
                }



                if(lv3['children']){
                    for(let iiii in lv3['children']){  // 颗粒权限： 按钮，块，页签等等；
                      let lv4 = lv3['children'][iiii]
                      let obj4 = {
                        id: lv4['menu_id'],
                        name: lv4['menu_name'],
                        index: [i, ii, iii, iiii],
                        path: lv4['dynamic_page']=='Y'? `/dynamic/${lv4['dynamic_path']||lv4['menu_id']}` : lv4['button_path'],
                        icon_path: lv4['icon_path'],
                        isDynamic: lv4['dynamic_page']=='Y'?true:false,
                        isFavorite: lv4['is_favorite']=='Y'?true:false, 
                        buttons: <any>[],
                      }
                      obj3.childrens.push(obj4)
                      // let type = ''
                      // // func_type : B(button), C(container), F(felid),
                      // if(lv4['func_type'] == 'B' || lv4['func_type'] == 'F'){
                      //     type = 'control'
                      // }else if(lv4['func_type'] == 'C'){
                      //     type = 'container'
                      // }
                      // if(!obj4[type]){
                      //     Object.assign(obj4, {[type]: {}})
                      // }
                      // Object.assign(obj4[type], {
                      //     [lv4['button_path']]: lv4['checked']
                      // })
                    }
                    // Object.assign(menus_roles, { [lv4['menu_id']]: obj4 })
                }


                Object.assign(menus_obj_id, { [lv3['menu_id']]: obj3 })
                Object.assign(menus_obj_path, { [obj3['path']]:obj3 })
                obj2.childrens.push(obj3)


                // 收藏菜单 （扁平）
                // if(obj3.isFavorite)
                // menus_favorite.push(obj3)
            }
            obj1.childrens.push(obj2)
        }
        menus.push(obj1)
    }
    // console.log(menus)
    menusStore().saveMenus({ menus, menus_obj_id, menus_obj_path, menus_favorite:[], menus_roles})

    // get_user_menu_favorites().then((result:any)=>{
    //     let res = result.data.result
    //     menusStore().saveMenus_favorite({menus_favorite:res})
    // })
  }
}