<template>
  <div class="header_container">
    <div class="header_content">
      <div class="header_title">
        <img alt="" :src="schoolLogo" class="header_icon" v-if="schoolLogo" />
        <img src="@/assets/school/default_logo.svg" alt="" class="header_icon" v-else />
        <div class="top_title_blod">{{systemTitle}}</div>
        <img class="version_icon" src="@/assets/icon/version.webp" alt="">
      </div>
      <div class="header_menu">
        <el-menu :default-active="activeMenuName" class="el-menu-wrap" mode="horizontal" :router="true"
          background-color="#2E64FA" text-color="#fff" active-text-color="#fff">
          <el-menu-item :index="item.externalLink" v-for="(item, index) in menuList" :key="index">
            {{ item.menuName }}
          </el-menu-item>
        </el-menu>
      </div>
      <div class="header_right">
        <el-dropdown trigger="click" @command="UserCommand" placement="bottom-end">
          <span class="userName">
            {{ userInfo.nickname }}
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="setPassWord">修改密码</el-dropdown-item>
              <el-dropdown-item command="loginOut">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="page_dialog">
      <el-dialog v-model="dialogShow" title="修改密码" width="450px">
        <el-form
          :model="editPassWordData"
          label-width="80px"
          :rules="editPassWordDataRules"
          ref="editPassWordForm"
        >
          <el-form-item label="原密码" prop="passWord">
            <el-input v-model="editPassWordData.passWord" type="password" show-password placeholder="请输入原密码" />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassWord">
            <el-input v-model="editPassWordData.newPassWord" type="password" show-password placeholder="请输入新密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmNewPassWord">
            <el-input v-model="editPassWordData.confirmNewPassWord" type="password" show-password placeholder="请输入确认新密码" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button class="button_border_gray cancel" @click="dialogShow = false">取 消</el-button>
          <el-button class="button_background" :loading="submitLoading" @click="confirmPassWord(editPassWordForm)">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>

import { ArrowDown } from '@element-plus/icons-vue'
import { ref, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { loginOut, changePassWord } from '@/api/login'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
// 1. 引入 Pinia store
import { useUserStore } from '@/store/user'

// 2. 初始化 store
const userStore = useUserStore()

// 3. 获取路由实例
const route = useRoute()
const router = useRouter()

// 修改 schoolLogo 计算属性，直接从 store 获取
const schoolLogo = computed(() => userStore.schoolLogo)

const systemTitle=ref('选择题智能判分系统');

const menuList=ref([
  {
    menuName: '选择题智能批阅',
    externalLink: '/main/choice'
  },
  {
    menuName: '填空题AI批阅',
    externalLink: '/main/fillblank'
  },
  {
    menuName: '作文题A批阅',
    externalLink: '/main/essay'
  },
])
// 使用计算属性根据当前路由自动设置激活菜单
const activeMenuName = computed(() => {
  const currentPath = route.path
  // 查找匹配的菜单项
  const matchedMenu = menuList.value.find(item => item.externalLink === currentPath)
  return matchedMenu ? matchedMenu.externalLink : ''
})

// const menuSelect=(menuName: string) => {
//   activeMenuName.value = menuName
// }
const userInfo = computed(() => {
  const user = localStorage.getItem('userInfo')
  if (user) {
    return JSON.parse(user)
  }
  return null
})
const dialogShow = ref(false)
interface EditPassWordData {
  passWord: string
  newPassWord: string
  confirmNewPassWord: string
}
const editPassWordData = reactive<EditPassWordData>({
  passWord: '',
  newPassWord: '',
  confirmNewPassWord: ''
}) // 修改密码弹窗数据

const editPassWordForm = ref<FormInstance>()
const editPassWordDataRules = reactive<FormRules<EditPassWordData>>({
  passWord: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassWord: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmNewPassWord: [
    { required: true, message: '请输入确认新密码', trigger: 'blur' }
  ]
})
const UserCommand = (command: string) => {
  console.log(command)
  if(command == 'setPassWord') {
    setPassWord()
  }else if(command == 'loginOut') {
    loginOutFn()
  }
}
// 打开修改密码弹窗
const setPassWord = () => {
  dialogShow.value = true
}
// 退出登录
const loginOutFn = async () => {
  console.log(userInfo.value.username)
  const res = await loginOut(userInfo.value.userid)
  if(res.code == 200) {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    router.push('/login')
  }else {
    ElMessage.error(res.msg)
  }
}
const submitLoading = ref(false)
// 修改密码提交
const confirmPassWord = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const res = await changePassWord({
          oldPassword: editPassWordData.passWord,
          newPassword: editPassWordData.newPassWord,
          confirmNewPassword: editPassWordData.confirmNewPassWord,
        })
        if(res.code == 200) {
          ElMessage.success(res.msg)
          dialogShow.value = false
          // 清除本地存储信息
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          // 跳转登录页面
          router.push('/login')
        }else {
          ElMessage.error(res.msg)
        }
      }catch {}finally {
        submitLoading.value = false
      }
    }
  })
}
</script>
 
<style lang="scss" scoped>



.header_content {
  // margin: 0 auto;
  box-sizing: border-box;
  height: 60px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;

  .header_title {
    min-width: 430px;
    width: auto;
    display: inline-flex;
    align-items: center;
    margin-right: 60px;

    .top_title_blod {
      font-size: 26px;
      font-weight: 500;
      color: #fff;
      text-align: center;
      vertical-align: middle;
      margin: 0 10px;
    }

    img.header_icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
    }

    img.project_title {
      width: 207px;
      height: 27px;
    }

    img.version_icon {
      width: 75px;
    }
  }

  @media screen and (max-width: 1400px) {
    padding: 0 10px;

    .header_logo {
      min-width: auto;
      width: auto;
      display: inline-flex;
      align-items: center;
      margin-right: 10px;

      .top_title_blod {
        font-size: 16px;
        font-weight: 500;
        color: #fff;
        text-align: center;
        vertical-align: middle;
        margin: 0 10px;
      }

      img.header_icon {
        width: 48px;
        height: 48px;
        border-radius: 50%;
      }

      img.project_title {
        width: 207px;
        height: 27px;
      }

      img.version_icon {
        width: 75px;
      }
    }
  }

  .header_menu {
    flex: 1;
    :deep(.el-menu-wrap)
    {
      height: 60px;
      border-bottom: none !important;

      //覆盖菜单样式
      .el-menu-item{
        font-size: 18px;
        border-bottom: 0;
        padding: 0 20px;
      }
    }


    @media screen and (max-width: 1400px) {
      .el-menu-item {
        padding: 0 10px;
      }
    }
  }

  .el-menu-wrap {
    height: 60px;

    li {
      font-size: 18px;
      border-bottom: 0;

      &.report {
        padding: 0 50px 0 20px;
      }

      &.is-active {
        font-weight: bold;
        background-color: rgba(0, 0, 0, 0.2) !important;
      }
    }

    li {
      position: relative;

      .versions {
        position: absolute;
        right: -5px;
        top: 8px;
        width: 25px;
        height: 15px;
        border-radius: 25px;
        border: 1px solid #FFFFFF;
        box-sizing: border-box;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        z-index: 12;

        span {
          display: inline-flex;
          justify-content: center;
          align-items: center;
          box-sizing: border-box;
          line-height: normal;
          transform: scale(0.9);

          &:first-child {
            font-size: 10px;
            margin-right: 2px;
            line-height: 15px;
            font-weight: normal;
          }

          &:nth-child(2) {
            font-size: 10px;
          }
        }
      }
    }
  }

  //屏幕小于1400px
  @media screen and (max-width: 1400px) {
    .el-menu-wrap {
      height: 60px;

      li {
        font-size: 14px;
        border-bottom: 0;

        &.is-active {
          font-weight: bold;
          background-color: rgba(0, 0, 0, 0.2) !important;
        }
      }
    }
  }

  //屏幕大于1400px
  @media screen and (min-width: 1401px) {}

}

.header_right {
  width: auto;
  line-height: 30px;

  .user_name {
    font-size: 15px;
    color: #fff;
    cursor: pointer;

    i {
      margin-left: 10px;
    }
  }
}


</style>