import {defineStore} from "pinia";
import {getAllUnitData, getLeftNavBarMenu, getParaConfig} from "@/service/login";
import {getSafeRankHomeTableData} from "@/service/zsk/base-rule/safe-rank";
import {showMessage} from "@/unit/element-ui/tip";
import router from "@/router";
import {getUserRouter} from "@/router/getUserRouter";
import {closeShowLoading, showLoading} from "@/data/element-loading/element-loader";






export const useRootStore = defineStore('root',{
 state() {
  return {
   userInfo:{},
   allUnitArr:[],
   toHomeCounter:0,
   realAllUnitArr:[],
   paraArr:[],
   pageType:'',
   safeLevelArr:[],
   leftMenuList:[]
  }
 },
 actions:{
  getUserMenu(menu) {

   this.leftMenuList =  menu
   const matchRoutes = []


   getUserRouter(menu,matchRoutes,{})

   console.log(matchRoutes,'routes',menu)
   matchRoutes.forEach(route => {
    router.addRoute(route.meta.parent[0].path,{
     ...route
    })
   })
   router.isReady().then(res =>{

    router.push({
     path:router.currentRoute.value.fullPath,

    })
    closeShowLoading()



   })





  },
  async getLoginUserInfo(payload){
   this.userInfo = payload
   localStorage.setItem('loginUserInfo',JSON.stringify(payload))
   this.getAllUnit()
   this.getParaConfig()
   this.getAllSafeLevelArr()

   try {
    showLoading({
     fullscreen:true
    })
    const res = await getLeftNavBarMenu()
    const menus =  res.msg[0].Rows[0].childList


    this.getUserMenu(menus)
   }catch {
    closeShowLoading()
    // showMessage({
    //  type:'error',
    //  message:'获取菜单信息失败'
    // })
    router.push('/login')
   }
  },
  getAllUnit() {
   getAllUnitData().then(res => {
    this.realAllUnitArr = res.msg[0].Rows.map(i => ({
     ...i,
     label:i.NAME,
     value:i.CODE,
    }))
   })
   console.log(this.userInfo.role,'this.userInfo.role')


  },
  getParaConfig() {
   getParaConfig().then(res => {
    this.paraArr  = res.msg[0].Rows.map(i => ({
     ...i,
     value:i.CODE,
     label:i.NAME,
    }))
   })
  },
  getAllSafeLevelArr() {
   getSafeRankHomeTableData({
    "pageIndex": 1,
    "pageSize": 1000,
   }).then(res => {
    this.safeLevelArr = (res.msg[0].Rows || []).map(i => ({
     ...i,
     value:i.SAFE_LEVEL_ID,
     label:i.SAFE_LEVEL,
    }))
   })
  },
  async userMenu() {
   const userInfo = localStorage.getItem('dataWatchLoginUserInfo')
   if (userInfo){
    this.userInfo = JSON.parse(userInfo)
    await this.getLoginUserInfo(JSON.parse(userInfo))
   }
  },



 },
 getters:{
  allSelectUnit(){
   return [
    {
     value:'',
     label:'全部'
    }
   ].concat(this.realAllUnitArr)
  },
  isUserVisiter(){
   return this.userInfo.ptjk_username &&  ['wbgszz','fzyjywf','fzyjywyw'].includes(this.userInfo.ptjk_username)
  }
 }
})
