<template>
  <view class="cwg-system">
    <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" :size="14" />
      </view>
    </cwg-dropdown>
  </view>
</template>

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

const props = defineProps({
  iconColor: {
    type: String,
    default: '#97A1C0'
  },
  textColor: {
    type: String,
    default: '#97A1C0'
  }
})

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(() =>
  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[]) => {
  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() {
  const cached = getCache()
  if (cached && cached.timestamp && Date.now() - cached.timestamp < CACHE_DURATION) {
    applySystemList(cached.data || [])
    return
  }

  try {
    const res: any = await customApi.getSystemList({})
    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
}

function switchSystem(item: SystemItem) {
  if (!item || !item.sysCode) return
  if (item.sysCode === currentSystemCode.value) return

  uni.showModal({
    title: '系统提示',
    content: '是否切换系统？',
    confirmText: '确认',
    cancelText: '取消',
    success: async (res) => {
      if (!res.confirm) return
      await confirmSwitchSystem(item)
    },
  })
}

async function confirmSwitchSystem(item: SystemItem) {
  try {
    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)}`
      console.log(baseUrl)
      // #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)
}

onMounted(() => {
  getSystemList()
})
</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: 80px;
  gap: px2rpx(4);
}

.current-system-name {
  font-size: px2rpx(14);
  color: v-bind('props.textColor');
}

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

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