<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import request from '@/util/http'
import {useRouter} from 'vue-router'
import API from "@/util/http.js";
import {useAdminStore} from '@/store'
// 方法抽出来 三个地方会用到
import {filterFirstMenu, findFirstThirdLevelMenu, getRoutePath,} from "../utils/menuUtils.js"
import {storeToRefs} from "pinia";

const loading = ref(false) // 登录按钮loading状态

const router = useRouter() // 获取路由实例
//获取当前浏览器地址
var url = window.location.href //上传服务器时打开注释并注释掉下一行
var machineId1 = ref(null)

// 获取machineId
function getMachineId() {
  var parts = url.split('machineId=')
  if (parts.length > 1) {
    machineId1 = parts[1].split('&')[0] // 进一步截取 & 之前的字符串
  }
  // machineId1 = decodeURIComponent(machineId1); //如果machineId需要前端转码可以打开注释
  console.log('机器码获取到了吗:', machineId1)
  form.value.machineId = machineId1
  if (machineId1) {
    // 将 machineId 存储到本地存储中
    localStorage.setItem('machineId', machineId1)
  }
}

const form = ref({account: null, password: '', token: '', machineId: machineId1.value})

const adminRoleId = ref(null)

// pinia 存储用户相关信息
const adminStore = useAdminStore()
//调用方法
const login = async function () {

  if(loading.value) {
    console.log('正在登录，请稍后')
    return
  }

  loading.value = true

  try {
    const result = await request({
      url: '/admin/login',
      data: form.value
    })
    console.log('传给后端的参数', form.value)

    if (result.code === 200) {
      // 本地存储token
      localStorage.setItem('token', result.msg)


      // 存储用户信息
      adminStore.setAdminData(result.data)

      // 本页面使用 adminRoleId
      adminRoleId.value = result.data.roleId

      // 存储菜单树
      const menuTree = await getMenuTree()

      console.log('存储菜单树menuTree', menuTree)
      adminStore.setMenuTree(menuTree)

      // 过滤
      const filteredMenu = filterFirstMenu(adminStore.menuTree)
      console.log('过滤后的菜单树', filteredMenu)
      // 获取第一个可访问的菜单
      const firstMenu = findFirstThirdLevelMenu(filteredMenu)

      console.log('获取到的第一个可访问的菜单的id', firstMenu)

      // 获取第一个可访问的菜单的 path
      const redirectPath = firstMenu ? getRoutePath(firstMenu) : '/noPermission'
      console.log('跳转的路径', redirectPath)
      // 跳转
      router.push(redirectPath)

      ElMessage.success('登录成功')

      // 获取地区

      await selectMarket()
      console.log('请求成功', result)
    } else {
      form.value.password = ''
      form.value.account = ''
      ElMessage.error(result.msg)
      loading.value = false //登录失败时重置loading状态
    }
  } catch (error) {
    console.log('请求失败', error)
    ElMessage.error('登录失败，请检查账号密码')
    loading.value = false // 发生异常时重置loading状态
  }
}
//获取菜单树
const getMenuTree = async function () {
  // 获取菜单树
  try {
    const result = await API({url: '/menu/tree', data: {id: adminRoleId.value}})

    return result.data  // 直接返回接口响应数据
  } catch (error) {
    console.error('菜单数据请求失败：', error)
    // return { code: 500, msg: '获取菜单失败' }
    ElMessage.error('网络异常')
    adminStore.clearState()
  }
}

// 获取地区列表 用于映射
const selectMarket = async function () {
  try {
    const selectMarketResult = await API({ url: '/market/selectMarket' });
    const marketList = {};

    // 递归遍历树形结构（从子节点开始）
    const traverseTree = (nodes) => {
      nodes.forEach(node => {
        // 存储当前节点的 id 和 name
        marketList[node.id] = node.name;
        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          traverseTree(node.children);
        }
      });
    };

    // 关键：跳过第一级节点，直接遍历第一级的子节点
    // 假设 selectMarketResult.data 是根节点数组（第一级）
    selectMarketResult.data.forEach(rootNode => {
      // 只处理第一级节点的子节点（从第二级开始遍历）
      if (rootNode.children && rootNode.children.length > 0) {
        traverseTree(rootNode.children);
      }
    });

    console.log('排除第一级后的地区列表：', marketList);
    adminStore.setMarketList(marketList);

    // return marketList;

  } catch (error) {
    console.error('获取地区树失败：', error);
    return {};
  }
};

onMounted(() => {
  getMachineId()

})

</script>
<template>
  <el-row class="login-page">
    <img :span="12" src="../assets/background.jpg" alt="logo" class="bg" fit="fit"/>
    <el-col :span="6" :offset="3" class="form">
      <!-- 登录表单 -->
      <el-form :model="form" size="large" autocomplete="off">
        <el-form-item>
          <h1 style="color: #409eff">熵盾管理系统 V1.0</h1>
        </el-form-item>
        <el-form-item prop="account" required>
          <el-input v-model="form.account" placeholder="请输入账号" @keyup.enter="login" required></el-input>
        </el-form-item>
        <el-form-item prop="password" @keyup.enter="login" required>
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              required
          />
        </el-form-item>
        <el-form-item class="flex"></el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <button type="button" class="button" @click="login()">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" height="30" width="24">
              <path fill="white"
                    d="M23.15 2.587L18.21 0.210001C17.9308 0.075557 17.6167 0.031246 17.3113 0.083204C17.0058 0.135162 16.724 0.280818 16.505 0.500001L7.04499 9.13L2.92499 6.002C2.73912 5.86101 2.50976 5.78953 2.27669 5.79994C2.04363 5.81035 1.82156 5.902 1.64899 6.059L0.326993 7.261C0.223973 7.35465 0.141644 7.46878 0.0852761 7.59608C0.0289081 7.72339 -0.00025659 7.86106 -0.000350724 8.00028C-0.000444857 8.1395 0.0285336 8.27721 0.0847294 8.40459C0.140925 8.53197 0.2231 8.64621 0.325993 8.74L3.89899 12L0.325993 15.26C0.2231 15.3538 0.140925 15.468 0.0847294 15.5954C0.0285336 15.7228 -0.000444857 15.8605 -0.000350724 15.9997C-0.00025659 16.1389 0.0289081 16.2766 0.0852761 16.4039C0.141644 16.5312 0.223973 16.6454 0.326993 16.739L1.64999 17.94C1.82256 18.097 2.04463 18.1887 2.27769 18.1991C2.51076 18.2095 2.74012 18.138 2.92599 17.997L7.04599 14.869L16.506 23.499C16.7248 23.7182 17.0064 23.8639 17.3117 23.9159C17.6171 23.9679 17.931 23.9235 18.21 23.789L23.152 21.412C23.4062 21.2893 23.6207 21.0973 23.7707 20.8581C23.9207 20.619 24.0002 20.3423 24 20.06V3.939C24 3.65647 23.9203 3.37967 23.7699 3.14048C23.6195 2.90129 23.4046 2.70943 23.15 2.587ZM18.004 17.448L10.826 12L18.004 6.552V17.448Z"></path>
            </svg>
            <p class="text">{{loading ? '登录中...' : '登录'}}</p>
          </button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">
.bg {
  border-radius: 0 20px 20px 0;
  height: 110vh;
  width: 50%;
  object-fit: cover;
}

.background {
  color: #fffdfd;
  text-align: center;
  font-size: 24px;
  background-color: #08193d;
}

.form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  user-select: none;

  .title {
    margin: 0 auto;
  }

  .button {
    width: 100%;
  }

  .flex {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}

/* From Uiverse.io by kamehame-ha */
.button {
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px 15px;
  gap: 15px;
  background-color: #1b95e6;
  outline: 3px #1b95e6 solid;
  outline-offset: -3px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  transition: 400ms;
}

.button .text {
  color: white;
  font-weight: 700;
  font-size: 1em;
  transition: 400ms;
}

.button svg path {
  transition: 400ms;
}

.button:hover {
  background-color: transparent;
}

.button:hover .text {
  color: #007acc;
}

.button:hover svg path {
  fill: #007acc;
}

.container {
  width: 100%;
  height: 100%;
  background: linear-gradient(#000 1px, #0000 0),
  linear-gradient(90deg, #000, #0000, #000),
  linear-gradient(in oklch longer hue -2deg, #a00, #a00);
  background-size: 100% 2px, 100% 100%, 100% 100%;
}
</style>