<template>
  <view class="component-switch-lang">
    <uni-popup
      ref="langsPopup"
      type="bottom"
      border-radius="10px 10px 0 0"
    >
      <view class="langs-popup">
        <view class="title">
          <text>{{ $t('xuanZeYuYan') }}</text>
          <view
            class="close iconfont"
            @tap="langsPopup.close()"
          >
            &#xe60e;
          </view>
        </view>
        <view class="langs-con">
          <radio-group @change="switchLang">
            <label
              v-for="(item, index) in langsInfo.langItemList"
              :key="index"
              class="langs-item"
            >
              <view>
                {{ item.name }}
              </view>
              <radio
                v-show="currentLang?.name === item.name"
                :value="item.name"
                :checked="currentLang?.name === item.name"
                color="#082ba6"
              />

            </label>
          </radio-group>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { i18n } from '@/locale'
onMounted(() => {
  getLangs()
})
const langsInfo = ref({})
const currentLang = ref()
const getLangs = () => {
  const params = {
    url: '/sys/lang',
    method: 'GET'
  }
  http.request(params).then(({ data: res }) => {
    langsInfo.value = res
    // 当前语言
    const clientLang = uni.getStorageSync('bbcMsLang')
    currentLang.value = res.langItemList.find(item => item.language === clientLang)
  })
}
const langsPopup = ref()
const onShowLangs = () => {
  langsPopup?.value.open()
}

const switchLang = ({ detail }) => {
  const selectLang = langsInfo.value.langItemList.find(item => item.name === detail.value)
  uni.setStorageSync('bbcMsLang', selectLang.language)
  uni.setStorageSync('bbcMsLangKey', selectLang.lang)
  i18n.global.locale.value = selectLang.language
  uni.setLocale(selectLang.language)
  uni.reLaunch({
    url: '/' + getCurrentPages()[getCurrentPages().length - 1].route
  })
}

defineExpose({
  onShowLangs
})
</script>

<style lang="scss" scoped>
.component-switch-lang {
  color: #333;
  .langs-popup {
    background-color: #fff;
    padding-bottom: calc(100rpx + var(--mall4j-safe-area-inset-bottom));
    font-size: 28rpx;
    border-radius: 10px 10px 0 0;
    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20rpx;
      position: relative;
      font-weight: bold;
      .close {
        position: absolute;
        right: 36rpx;
        top: 25rpx;
      }
    }
    .langs-con {
      padding: 20rpx;
      .langs-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        border-bottom: 1px solid #eee;
        &:last-child {
          border-bottom: none;
        }
      }
    }
  }
}
</style>
