<template>
  <div class="topBar">
    <t-head-menu v-model="menuValue" height="120px" theme="dark">
      <!-- <template #logo>
        <img alt="logo" height="120px" src="/public/TopLogo.jpg"/>
      </template> -->
      <div style="height: 100%;line-height: 100%;width: 80vw;overflow: auto;display: flex">
        <t-menu-item v-for="router in routerData.userRouterList" 
                     :key="router.path"
                     :selected="router.selected" 
                     :value="router.path"
                     style="height: 100%" 
                     @click="routerTo(router)">
          {{ router.权限模块 }}
        </t-menu-item>
      </div>
      <template #operations>
        <div class="dateTime">
          <div class="date">{{ date }}</div>
          <div class="time">{{ time }}&nbsp;&nbsp;{{ nowWeek }}</div>
        </div>
        <div class="t-demo-menu--dark">
          <!--          <t-button shape="square" variant="text">-->
          <!--            <template #icon>-->
          <!--              <t-icon name="search"/>-->
          <!--            </template>-->
          <!--          </t-button>-->
          <!--          <t-button shape="square" variant="text">-->
          <!--            <template #icon>-->
          <!--              <t-icon name="mail"/>-->
          <!--            </template>-->
          <!--          </t-button>-->
          <!--          <t-button shape="square" variant="text">-->
          <!--            <template #icon>-->
          <!--              <t-icon name="user"/>-->
          <!--            </template>-->
          <!--          </t-button>-->
          <el-button :icon="SwitchButton" circle @click="logout" style="background: transparent; border: none; color: #fff; font-size: 20px;" />
        </div>
      </template>
    </t-head-menu>
  </div>
  <div class="main">
    <router-view/>
  </div>
</template>

<script setup>
import {inject, onMounted, onUnmounted, ref} from 'vue'
import {useAppStore} from '@/store/app.js'
import {storeToRefs} from 'pinia'
import {addDynamicRoutes} from '@/router/index.js'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'
import Cookies from 'js-cookie'
import { SwitchButton } from '@element-plus/icons-vue'

const router = useRouter()
const store = useAppStore()
const CreateData = inject('CreateData')
const ExecDatabase = inject('ExecDatabase')
// storeToRefs 响应式解构赋值 pinia
const {user, isLoading, routerData} = storeToRefs(store)

const menuValue = ref('')
const date = ref('')
const time = ref('')
const nowWeek = ref('')
const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

let checkTimer = null

const checkLoginStatus = () => {
  const loginKey = Cookies.get('loginKey')
  const opName = Cookies.get('lastOpName')
  
  if (!loginKey || !opName) {
    if (checkTimer) {
      clearInterval(checkTimer)
      checkTimer = null
    }
    store.isLoading = false
    router.push('/login')
    return
  }

  var param = []
  param[0] = ['工位号', opName]
  param[1] = ['Key', loginKey]
  var Data = CreateData('11', 'CRRC_登陆_Key_校验', param)
  ExecDatabase(Data).then(response => {
    if (response.data[0].result !== 1) {
      if (checkTimer) {
        clearInterval(checkTimer)
        checkTimer = null
      }
      ElMessage.warning(response.data[0].msg || '登录已失效，请重新登录')
      store.isLoading = false
      // 直接清除数据并跳转，避免递归调用logout
      store.$reset()
      Cookies.remove('loginKey')
      Cookies.remove('userInfo')
      Cookies.remove('lastOpName')
      Cookies.remove('roleType')
      router.push('/login')
    }
  }).catch(error => {
    console.error('登录状态检查失败:', error)
    // 网络错误时不强制退出，避免影响用户体验
  })
}

const updateDateTime = () => {
  const now = new Date()
  date.value = now.toLocaleDateString()
  time.value = now.toLocaleTimeString()
  nowWeek.value = week[now.getDay()]
}

onMounted(() => {
  console.log('store.user.AID', store.user.AID)
  // 立即更新一次时间
  updateDateTime()
  
  setTimeout(() => {
    // 检查Cookie中是否有用户信息
    const userInfo = Cookies.get('userInfo')
    if (userInfo) {
      try {
        const parsedUserInfo = JSON.parse(userInfo)
        // 将Cookie中的用户信息恢复到store
        store.user = {
          ...store.user,
          ...parsedUserInfo
        }
        getRouter()
        // 获取当前实时日期时间 与星期几
        setInterval(updateDateTime, 1000)
        
        // 启动登录状态检查定时器
        checkTimer = setInterval(checkLoginStatus, 30000) // 每30秒检查一次
      } catch (error) {
        console.error('解析用户信息失败:', error)
        router.push({path: '/login'})
      }
    } else if (!store.user.AID) {
      console.log('store.user.AID为空且Cookie中无用户信息，返回主页！')
      router.push({path: '/login'})
    } else {
      getRouter()
      // 获取当前实时日期时间 与星期几
      setInterval(updateDateTime, 1000)
      
      // 启动登录状态检查定时器
      checkTimer = setInterval(checkLoginStatus, 30000) // 每30秒检查一次
    }
  }, 200)
})

onUnmounted(() => {
  if (checkTimer) {
    clearInterval(checkTimer)
  }
})

// 获取权限列表
const getRouter = async () => {
  // 获取权限列表
  var param = []
  param[0] = ['userId', store.user.AID]
  var Data = CreateData('11', '基础表_权限模块_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      for (let item of response.data) {
        item.selected = false
      }
      response.data[0].selected = true
      
      // 从cookie中获取角色类型
      const roleType = Cookies.get('roleType')
      
      // 如果角色类型为1，过滤掉"车体到位"模块
      if (roleType == '1') {
        response.data = response.data.filter(item => item.权限模块 !== '物料平台')
        response.data = response.data.filter(item => item.权限模块 !== 'HMI界面')
      }else{
        response.data = response.data.filter(item => item.权限模块 !== '车体到位')
      }
      
      routerData.value.userRouterList = response.data
      initRouter()
    } else {
      ElMessage.warning('该角色未分配角色模块，请先进行分配!')
    }
  })
}

const initRouter = async () => {
  // 动态添加路由
  await addDynamicRoutes(routerData.value.userRouterList).then(() => {
    menuValue.value = routerData.value.userRouterList[0].path
    routerData.nowRouterPath = routerData.value.userRouterList[0].path
    routerData.nowRouterTitle = routerData.value.userRouterList[0].权限模块
    router.push({path: '/' + routerData.value.userRouterList[0].path})
    store.isLoading = false
  })
}

const routerTo = (item) => {
  const targetRoute = routerData.value.userRouterList.find(r => r.path === item.path)
  if (targetRoute) {
    routerData.nowRouterPath = targetRoute.path
    routerData.nowRouterTitle = targetRoute.权限模块
    routerData.selected = true
    router.push({path: '/' + targetRoute.path})
  }
}

const logout = () => {
  // 清理定时器，防止干扰
  if (checkTimer) {
    clearInterval(checkTimer)
    checkTimer = null
  }
  
  var param = []
  param[0] = ['userId', user.value.AID]
  param[1] = ['opName', user.value.opName]
  var Data = CreateData('11', '基础表_用户角色_退出登录', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      // 先清除所有相关Cookie，再重置pinia数据
      Cookies.remove('loginKey')
      Cookies.remove('userInfo')
      Cookies.remove('lastOpName')
      Cookies.remove('roleType')
      // 重置pinia数据
      store.$reset()
      // 只跳转一次到登录页面
      router.push('/login')
      ElMessage.success('退出登录成功!')
    } else {
      ElMessage.warning('退出登录失败，数据未清空!')
    }
  }).catch(error => {
    console.error('退出登录请求失败:', error)
    // 即使请求失败，也要清理本地数据并跳转
    if (checkTimer) {
      clearInterval(checkTimer)
      checkTimer = null
    }
    // 先清除Cookie，再重置store
    Cookies.remove('loginKey')
    Cookies.remove('userInfo')
    Cookies.remove('lastOpName')
    Cookies.remove('roleType')
    store.$reset()
    router.push('/login')
    ElMessage.warning('网络异常，已强制退出登录!')
  })
}
</script>

<style lang="scss" scoped>
.topBar {
  width: 100vw;
  overflow: hidden;

  .dateTime {
    font-size: .8vw;
    float: right;
    width: 10vw;
    color: #fff;
    text-align: center;

    div {
      height: 20px;
      line-height: 20px;
    }
  }
}

.t-menu__operations {
  .t-button {
    margin-left: 8px;
  }
}

.t-demo-menu--dark {
  .t-button {
    color: #fff;

    &:hover {
      background-color: #4b4b4b;
      border-color: transparent;
      --ripple-color: #383838;
    }
  }
}


/* 滚动条样式 */
::-webkit-scrollbar {
  width: 4px; /*  设置纵轴（y轴）轴滚动条 */
  height: 4px; /*  设置横轴（x轴）轴滚动条 */
}

/* 滚动条滑块（里面小方块） */
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #7ba2cc;
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
  border-radius: 0;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #fff;
}


.main{
  width: 100vw;
  // height去掉topBar
  height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
  background: #f9f9f9;
  
}
</style>
