<template>
  <div id="user">
    <div class="section-common section-top">
      <div class="bar">
        <div class="language">
          <el-dropdown trigger="click" @command="chooseLang">
            <div class="language-selector">
              <img v-if="currentFlag" :src="currentFlag" alt="flag" class="flag-icon" />
              <span class="menu">
                {{ langList[language]?.name || language }}
                <el-icon><ArrowDown /></el-icon>
              </span>
            </div>

            <template #dropdown>
              <el-dropdown-menu class="language-dropdown">
                <el-dropdown-item
                  v-for="lang in languageOptions"
                  :key="lang.code"
                  :command="lang.code"
                  :class="{ 'is-active': lang.code === language }"
                >
                  <div class="language-option">
                    <span>{{ lang.name }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <div class="rbt-separator d-none d-xl-block"></div>

          <div class="header-info d-none d-xl-block">
            <ul class="social-share-transparent">
              <li>
                <a
                  href="https://www.facebook.com/people/CWG-Markets-Promotions/100064027417838/"
                  target="_blank"
                >
                  <i class="bi bi-facebook"></i>
                </a>
              </li>
              <li>
                <a href="https://www.linkedin.com/company/cwg-markets-ltd/" target="_blank">
                  <i class="bi bi-linkedin"></i>
                </a>
              </li>
              <li>
                <a href="https://www.instagram.com/cwgmarkets/" target="_blank">
                  <i class="bi bi-instagram"></i>
                </a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <el-row class="section-common section-bottom">
      <el-col :span="12" class="section-common section-left">
        <div>
          <div>
            <Loop />
          </div>
          <div class="des">
            <span>
              {{ t('newSignin.item12') }} </span
            ><br />
            <span>
              {{ t('newSignin.item12_1') }} </span
            ><br />
            <span>
              {{ t('newSignin.item10') }} </span
            ><br />
            <span>
              {{ t('newSignin.item11') }} </span
            ><br />
            <span>{{ t('newSignin.item13') }}</span>
            <a
              :href="`https://www.${ho}.com/doc/Risk-Disclosures-and-Acknowledgements-2020-08.pdf`"
              target="_blank"
            >
              {{ t('newSignin.item13_1') }}
            </a>
            <span>{{ t('newSignin.item13_2') }}</span>
            <div>{{ t('newSignin.item13_3') }}</div>
            <span>{{ t('newSignin.item13_4') }}</span>
          </div>
        </div>
      </el-col>

      <el-col :span="12" class="section-common section-right">
        <router-view />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted, inject } from 'vue'
  import { useRoute } from 'vue-router'
  import { useI18n } from 'vue-i18n'
  import { ArrowDown } from '@element-plus/icons-vue'
  import axios from 'axios'
  import Loop from './Loop.vue'
  import Service from '@/service/login'
  import Config from '@/config/index'
  import { useStore } from 'vuex'
  import { langList, languageOptions } from '@/utils/const/langues'

  const { t, locale } = useI18n()
  const route = useRoute()
  const { Code } = Config
  const store = useStore()

  // 注入reload方法（如果有）
  const reload = inject('reload')
  const Session = inject('session')
  const pigeon = inject('pigeon')

  // 响应式数据
  const ho = ref('')
  const language = ref('')

  // 计算当前国旗图标
  const currentFlag = computed(() => {
    const lang = langList[language.value]
    return lang ? lang.flag : '/src/assets/images/lang_EN.jpg'
  })
  console.log(languageOptions)

  // 方法
  const chooseLang = async (key) => {
    if (key !== language.value) {
      // await switchLanguage(key)
      locale.value = key
      language.value = key
      Session.Set('lang', key)
      axios.defaults.headers.common['Language'] = sessionStorage.getItem('lang')
      setTimeout(() => {
        // 使用注入的reload方法或刷新页面
        if (reload) {
          reload()
        } else {
          // 如果没有注入reload方法，可以手动刷新或更新组件
          window.location.reload()
        }
      })
    }
  }

  const getCountryCode = async () => {
    try {
      const res = await Service.CodeById({})
      if (res.code === Code.StatusOK) {
        let lang = 'en'

        switch (res.msg) {
          case 'CN':
            lang = 'cn'
            break
          case 'VN':
            lang = 'vn'
            break
          default:
            lang = 'en'
        }

        setLanguage(lang)
      }
    } catch (error) {
      console.error('获取国家编码失败:', error)
      setLanguage('en')
    }
  }

  const switchLanguage = async (lang) => {
    try {
      await Service.switchLanguage({ lang })
    } catch (error) {
      console.error('切换语言失败:', error)
    }
  }

  const setLanguage = (lang) => {
    locale.value = lang
    language.value = lang
    Session.Set('lang', lang)
    axios.defaults.headers.common['Language'] = sessionStorage.getItem('lang')

    if (reload) {
      reload()
    }
  }

  const toHome = () => {
    // 如果有store，可以这样使用
    store.commit('isActiveTab', '0')
  }

  // 初始化
  onMounted(() => {
    ho.value = window.location.host.split('.')[1] || ''

    // 处理电子邮件广告参数
    if (route.query.emailAdvertisement && !sessionStorage.getItem('lang')) {
      setLanguage('cn')
    }

    // 从存储中恢复语言设置
    const savedLang = localStorage.getItem('lang')
    if (savedLang) {
      setLanguage(savedLang)
    } else {
      language.value = locale.value
      Session.Set('lang', locale.value)
      axios.defaults.headers.common['Language'] = sessionStorage.getItem('lang')
      // getLanguage()
    }
  })
</script>

<style lang="scss" scoped>
  #user {
    height: 100%;
    @include font_gray_1();
    background-image: url(../../../assets/images/login-bg.gif);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    overflow-y: scroll;

    &:before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
      background-color: #000000;
      opacity: 0.6;
    }

    .section-common {
      // height: 100%;
    }

    .section-top {
      width: 100%;
      position: relative;
      z-index: 1;

      .bar {
        position: relative;
        z-index: 1;
        padding: 20px 100px;
        box-sizing: border-box;

        .language {
          display: flex;
          justify-content: end;
          align-items: center;

          .language-selector {
            display: flex;
            align-items: center;
            cursor: pointer;

            .flag-icon {
              width: 15px;
              height: 10px;
              margin: 0 4px;
              object-fit: cover;
            }

            .menu {
              cursor: pointer;
              color: #fff;
              display: flex;
              align-items: center;

              .el-icon {
                margin-left: 4px;
              }
            }
          }

          .rbt-separator {
            position: relative;
            padding: 0 20px;

            &::after {
              position: absolute;
              content: '';
              height: 20px;
              width: 1px;
              background: #fff;
              top: 50%;
              transform: translateY(-50%);
            }
          }

          .social-share-transparent {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-end;
            margin: -10px;

            li {
              margin: 0;
              position: relative;
            }

            a {
              font-size: 14px;
              color: #fff;
              display: flex;
              align-items: center;
              justify-content: center;
              width: 30px;
              height: 30px;
              border-radius: 100%;
              position: relative;
              z-index: 1;

              &:hover::before {
                opacity: 1;
                transform: scale(1);
              }

              &::before {
                background: #f6f6f6;
                position: absolute;
                content: '';
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
                opacity: 0;
                transform: scale(0.8);
                border-radius: 100%;
                z-index: -1;
                transition: all 0.3s ease;
              }

              &:hover {
                color: #e61f1e;
              }

              .el-icon {
                font-size: 16px;
              }
            }
          }
        }
      }
    }

    .section-bottom {
      max-width: 1320px;
      min-height: calc(100% - 54px);
      position: relative;
      z-index: 1;
      flex: auto;
      display: flex;
      flex-wrap: wrap;
    }

    .section-left {
      position: relative;
      display: flex;
      align-items: center;

      .des {
        text-align: start;
        line-height: 20px;
        color: #fff;
        font-size: 12px;
        margin-top: 30px;

        a {
          color: #e61f1e;
        }
      }
    }

    .section-right {
      box-sizing: border-box;
      overflow: auto;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .language-dropdown {
      position: sticky;
      top: 50px;
      max-height: calc(100vh - 80px);
      overflow-y: auto;
      scrollbar-width: none;

      &::-webkit-scrollbar {
        display: none;
      }

      .language-option {
        display: flex;
        align-items: center;
        gap: 8px;

        .flag-icon-small {
          width: 20px !important;
          height: 14px;
          object-fit: cover;
          border-radius: 2px;
        }
      }

      .el-dropdown-item.is-active {
        background-color: #f5f7fa;
        color: #409eff;
      }
    }
  }

  @media screen and (max-width: 768px) {
    #user {
      height: 100%;
      overflow-y: auto;

      .section-top {
        height: 54px;

        .bar {
          padding: 20px;
        }
      }

      .section-bottom {
        width: 100%;
      }

      .section-left {
        display: none;
      }

      .section-right {
        height: auto;
        width: 100%;
        padding-top: 48px;
        overflow: hidden;
        background-color: #fff;
      }
    }
  }

  @media screen and (max-width: 768px) {
    #user .el-carousel__indicators {
      transform: initial;
      left: 48px !important;
      bottom: 48px;
    }

    #user .el-carousel__button {
      width: 8px;
      height: 8px;
      border-radius: 8px;
      @include bg_gray_1();
    }

    #user .is-active > .el-carousel__button {
      width: 20px;
      @include bg_main();
    }
  }

  :deep(.el-dropdown-menu__item:not(.is-disabled):hover) {
    background-color: #fdecee;
    color: #ef6579;
  }
</style>
