<template>
  <view class="cwg-system" v-if="systemMenuList.length">
    <cwg-dropdown :menu-list="systemMenuList" @menuClick="handleMenuClick">
      <view class="pc-header-btn">
        <text class="current-system-name">{{ currentSystemName }}</text>
        <cwg-icon name="crm-chevron-down" :color="iconColor" darkColor="#000" :size="14" />
      </view>
    </cwg-dropdown>
  </view>
  <cwg-global-popup/>
</template>

<script setup lang="ts">
import { computed, ref, onMounted,onUnmounted,nextTick} from 'vue'
import { useI18n } from 'vue-i18n'
import Config from '@/config/index'
import { customApi } from '@/service/custom'
import { userToken } from "@/composables/config";
import { usePopup } from '@/hooks/usePopup'

const { confirm } = usePopup()

const props = defineProps({
  iconColor: {
    type: String,
    default: '#97A1C0'
  },
  textColor: {
    type: String,
    default: '#97A1C0'
  },
  // 事件来源标识，用于区分不同组件的事件监听
  eventSource: {
    type: String,
    default: ''
  }
})

const { Code } = Config
const { locale } = useI18n()

type SystemItem = {
  sysCode: string
  sysUrl: string
  sysName?: string
  sysNameEn?: string
  localSystem?: number
}

const systemList = ref<SystemItem[]>([])
const currentSystemCode = ref<string | null>(null)

const systemMenuList = computed(() =>{
  return systemList.value.map((item) => ({
    ...item,
    label: getSystemDisplayName(item),
  }))
})

const currentSystemName = computed(() => {
  if (!currentSystemCode.value || systemList.value.length === 0) {
    return '系统切换'
  }
  const currentSystem = systemList.value.find((item) => item.sysCode === currentSystemCode.value)
  if (!currentSystem) return '系统切换'

  return getSystemDisplayName(currentSystem)
})

const CACHE_KEY = 'systemListCache'
// 4 * 60 * 60 * 1000
const CACHE_DURATION = 14400000

const getCache = () => {
  const cached = uni.getStorageSync(CACHE_KEY)
  if (!cached) return null
  try {
    return typeof cached === 'string' ? JSON.parse(cached) : cached
  } catch (e) {
    return null
  }
}

const setCache = (data: any) => {
  uni.setStorageSync(CACHE_KEY, JSON.stringify({ data, timestamp: Date.now() }))
}

const applySystemList = (data: any[]) => {
  // console.log(data,props.eventSource)
  systemList.value = Array.isArray(data) ? data : []
  if (systemList.value.length > 0) {
    const localSystem = systemList.value.find((item) => item && item.localSystem === 1)
    currentSystemCode.value = localSystem ? localSystem.sysCode : null
  } else {
    currentSystemCode.value = null
  }
}

async function getSystemList(type = false) {
  const cached = getCache()
  // console.log('system',type,props.eventSource)
  // top-window组件中，没有token不去请求接口
  if (props.eventSource === 'top') {
    if (!userToken.value) return
  }
  // if (!type){
    if (cached && cached.timestamp && Date.now() - cached.timestamp < CACHE_DURATION) {
      applySystemList(cached.data || [])
      return
    }
  // }

  try {
    const res: any = await customApi.getSystemList({})
    // console.log('res',res)
    if (res && res.code === Code.StatusOK) {
      const data = res.data || []
      applySystemList(data)
      setCache(data)
    } else {
      uni.showToast({ title: (res && (res.msg || res.message)) || '获取系统列表失败', icon: 'none' })
    }
  } catch (e) {
    uni.showToast({ title: '获取系统列表失败', icon: 'none' })
  }
}

function getSystemDisplayName(item: SystemItem) {
  if (!item) return ''
  if (locale.value === 'en') return item.sysNameEn || item.sysName || item.sysCode
  return item.sysName || item.sysNameEn || item.sysCode
}

async function switchSystem(item: SystemItem) {
  if (!item || !item.sysCode) return
  if (item.sysCode === currentSystemCode.value) return
  const result = await confirm({
    title: '系统提示',
    content: '是否切换系统？',
    confirmText: '确认',
    cancelText: '取消',
  })
  if (result){
    await confirmSwitchSystem(item)
  }
  // uni.showModal({
  //   title: '系统提示',
  //   content: '是否切换系统？',
  //   confirmText: '确认',
  //   cancelText: '取消',
  //   success: async (res) => {
  //     if (!res.confirm) return
  //
  //   },
  // })
}

async function confirmSwitchSystem(item: SystemItem) {
  try {
    if (props.eventSource === 'login'){
      const baseUrl = `${item.sysUrl}/#/signin`
      // #ifdef H5
      window.location.replace(baseUrl)
      // #endif

      // #ifndef H5
      uni.showToast({ title: '仅支持在H5端切换系统', icon: 'none' })
      // #endif
    }else{
      const res: any = await customApi.switchSystem({ sysCode: item.sysCode })
      if (res && res.code === Code.StatusOK) {
        const accessToken = res.data
        const token = typeof accessToken === 'string' ? accessToken : String(accessToken || '')
        const baseUrl = `${item.sysUrl}/#/signin?sysLoginToken=${btoa(token)}`
        // #ifdef H5
        window.location.replace(baseUrl)
        // #endif

        // #ifndef H5
        uni.showToast({ title: '仅支持在H5端切换系统', icon: 'none' })
        // #endif
      } else {
        uni.showToast({ title: (res && (res.msg || res.message)) || '切换系统失败', icon: 'none' })
      }
    }

  } catch (e) {
    uni.showToast({ title: '切换系统失败', icon: 'none' })
  }
}

function handleMenuClick({ value }: { value: any }) {
  switchSystem(value)
}

const isInit = ref(false)

onMounted(() => {
  if (isInit.value) return
  isInit.value = true

  getSystemList()

  uni.$on('updateSystemList', (source) => {
    // console.log(source)
    // 如果指定了事件来源，只处理来自该来源的事件
    // if (props.eventSource && source !== props.eventSource) return
    getSystemList(true)
  })
})
onUnmounted(() => {
  uni.$off('updateSystemList')
})
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.cwg-system {
  @media screen and (max-width: 991px) {
    :deep(.cwg-dropdown-menu-container) {
      right: px2rpx(-20) !important;
      //max-width: px2rpx(400);
    }
  }
}

.pc-header-btn {
  display: flex;
  align-items: center;
  cursor: pointer;
  width: px2rpx(80);
  gap: px2rpx(4);
}

.current-system-name {
  font-size: px2rpx(14);
  color: var(--bs-emphasis-color);
}

:deep(.cwg-dropdown-menu-container .menu .menu-item) {
  min-height: px2rpx(36);
}

:deep(.cwg-dropdown) {
  overflow: visible !important;
}
</style>
