<template>
  <el-select
    v-model="currentLocale"
    @change="handleChange"
    :size="size"
    :style="style"
    :placeholder="t('common.language')"
  >
    <el-option label="繁體中文" value="zh-TW" />
    <el-option label="Tiếng Việt" value="vi" />
  </el-select>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useI18n } from '@/composables/useI18n'
import { useDynamicTitle } from '@/utils/dynamicTitle'
import { changeLanguages } from "@/api/system/userContact.js"
import useUserStore from '@/store/modules/user'

const props = defineProps({
  size: {
    type: String,
    default: 'default'
  },
  style: {
    type: Object,
    default: () => ({})
  },
  reload: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['language-changed'])

const { locale, setLocale, t } = useI18n()
const currentLocale = ref(locale.value)
const userStore = useUserStore()

onMounted(() => {
  currentLocale.value = locale.value
})

// 监听语言变化
watch(locale, (newLocale) => {
  currentLocale.value = newLocale
})

const handleChange = (value) => {
  // 获取当前登录用户名
  const userName = userStore.name || ''
  
  changeLanguages(value, userName).then(response => {
    // 处理响应
  }).catch(error => {
    console.error('切换语言失败:', error)
  })
  setLocale(value)
  currentLocale.value = value
  // 更新页面标题
  useDynamicTitle()
  // 触发语言切换事件（参考 ruoyi-ui 的实现）
  nextTick(() => {
    emit('language-changed', value)
  })
  // 如果需要刷新页面以应用语言更改（默认不刷新，使用响应式更新）
  if (props.reload) {
    window.location.reload()
  }
}
</script>

<style scoped>
:deep(.el-select) {
  width: 100%;

  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-shadow: none;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);

    &:hover {
      border-color: #c0c4cc;
    }

    &.is-focus {
      border-color: #409eff;
    }
  }

  &:hover .el-input__wrapper {
    border-color: #c0c4cc;
  }

  .el-input__inner {
    color: #606266;
  }
}
</style>

