<template>
  <el-dialog
      v-model="dialogVisible"
      title="语言切换"
      width="300px"
      :close-on-click-modal="false"
      append-to-body
      class="lang-switch-dialog"
  >
    <el-form label-width="80px">
      <el-form-item label="切换语言">
        <el-select
            v-model="tempLang"
            placeholder="请选择语言"
            style="width: 100%"
        >
          <el-option
              v-for="item in langOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, ref} from 'vue'
import {useI18n} from 'vue-i18n'
// === 显式引入所有用到的 Element Plus 组件 ===
import {ElButton, ElDialog, ElForm, ElFormItem, ElMessage, ElOption, ElSelect} from 'element-plus'
import request from "@/util/http.js";
import {useAdminStore} from '@/store/index.js';
import {storeToRefs} from "pinia";

const {locale} = useI18n()

// 控制弹窗显示
const dialogVisible = ref(false)

// 真正的当前语言
const currentLang = computed(() => locale.value)

// 临时选择的语言
const tempLang = ref('')

// 语言选项 
const langOptions = [
  {label: '中文(简体)', value: 'zh-CN'},
  {label: '中文(繁體)', value: 'zh-TW'},
  {label: '英语', value: 'en'},
  {label: 'ภาษาไทย', value: 'th'},
  {label: 'Tiếng Việt', value: 'vi'}
]

// 获取语言显示名称
const getLangLabel = (langCode) => {
  const find = langOptions.find(item => item.value === langCode)
  return find ? find.label : langCode
}

// 打开弹窗
const open = () => {
  tempLang.value = currentLang.value
  dialogVisible.value = true
}


// 确认修改
const handleConfirm = async () => {
  locale.value = tempLang.value
  localStorage.setItem('lang', tempLang.value)

  await getMenuTree()

  ElMessage.success(`语言已切换为：${getLangLabel(tempLang.value)}`)
  dialogVisible.value = false
  // 触发页面刷新以重新加载数据
  setTimeout(() => {
    window.location.reload()
  }, 500)
}

defineExpose({
  open
})

const adminStore = useAdminStore();
const {adminData} = storeToRefs(adminStore);
// 切换多语言 菜单改变
const getMenuTree = async function () {
  // 获取菜单树
  try {
    const result = await request({
      url: '/menu/tree',
      data: {
        id: adminData.value.roleId,

      }
    })
    if (result.code === 200){
      adminStore.setMenuTree(result.data)

    }

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


<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
}


/* :deep(.el-dialog__body) {
  height: 220px !important;
  overflow-y: auto !important;
} */
</style>