<script setup lang="ts">
import * as R from "ramda";
import { useConfigStore, useUserStore } from "@/store";
import { appUpdate } from "@/utils/update";
import TabbarHome from "@/pages/home/components/tabbar-home/tabbar-home.vue";
import TabbarShop from "@/pages/home/components/tabbar-shop/tabbar-shop.vue";
import TabbarOrder from "@/pages/home/components/tabbar-order/tabbar-order.vue";
import TabbarMine from "@/pages/home/components/tabbar-mine/tabbar-mine.vue";
import TabbarBrowse from "@/pages/home/components/tabbar-browse/tabbar-browse.vue";
import InviteUser from "@/pages/home/components/tabbar-mine/components/invite-user/invite-user.vue";
import CustomerService from "@/pages/home/components/tabbar-mine/components/customer-service/customer-service.vue";
import NotOpen from "@/pages/home/components/tabbar-home/components/not-open.vue";
import { useMessage } from "wot-design-uni";
import { debounce } from "throttle-debounce";
import Config from "@/config";
import { EventEnum } from "@/constant/enums";
import type UseCode from "@/components/use-code/use-code.vue";
import Score from "@/components/filtrate-tool/components/score.vue";
import PriceChoose from "@/components/filtrate-tool/components/price-choose.vue";
import useEventEmit from "@/hooks/useEventEmit";
import {
  appAppointmentTimeQueryAppointmentTimePost,
  appMessageUnreadCountPost,
} from "@/service";
import SwiperList from "@/pages/search/components/swiper-list/swiper-list.vue";
import { getDictFineList } from "@/pages-store/service";
import {getCouponReceiveListApi, receiveAllCouponApi} from "@/pages-user/service";

// useEventEmit(EventEnum.STAR_RATING_FILTER, ()=> {
//   scoreRef.value.onOpen()
// })
// useEventEmit(EventEnum.PRICE_FILTER, ()=> {
//   priceChooseRef.value.onOpen()
// })

const userStore = useUserStore();
const configStore = useConfigStore();
const message = useMessage();
const { t, locale } = useI18n();

function daySuffix(value: unknown) {
  const n = Number(value)
  const isEn = String(locale.value || '').toLowerCase().startsWith('en')
  if (isEn) {
    return n === 1 ? ` ${t('pages-store.store.day')}` : ` ${t('pages-store.store.days')}`
  }
  return t('pages-store.store.days')
}
const tabbarHomeRef = ref<InstanceType<typeof TabbarHome>>();
const tabbarShopRef = ref<InstanceType<typeof TabbarShop>>();
const tabbarOrderRef = ref<InstanceType<typeof TabbarOrder>>();
const tabBarMineRef = ref<InstanceType<typeof TabbarMine>>();
const tabbarBrowseRef = ref<InstanceType<typeof TabbarBrowse>>();
const scoreRef = ref<InstanceType<typeof Score>>();
const priceChooseRef = ref<InstanceType<typeof PriceChoose>>();
const notOpenRef = ref<InstanceType<typeof NotOpen>>();
const showCoupon = ref(false);
const couponList = ref([]);

const inviteUserRef = ref<InstanceType<typeof InviteUser>>();
const useCodeRef = ref<InstanceType<typeof UseCode>>();
const customerServiceRef = ref<InstanceType<typeof CustomerService>>();

// 字体加载状态管理
const fontLoadingState = ref({
  isLoading: false,
  isLoaded: false,
  loadedFonts: new Set(),
  retryCount: 0,
  maxRetries: 3,
});

// 接口调用状态管理
const apiLoadingState = ref({
  isLoadingUserData: false,
  lastLoadTime: 0,
  debounceDelay: 1000,
});

const activeIndex = ref("home");
const tabBarList = ref([
  {
    iconPath: "/static/tabbar/home.png",
    selectedIconPath: "/static/tabbar/homeHL.png",
    text: t("tabBar.home"),
    code: "home",
  },
  {
    iconPath: "/static/tabbar/global.png",
    selectedIconPath: "/static/tabbar/globalHL.png",
    text: t("tabBar.global"),
    code: "global",
  },
  {
    iconPath: "/static/tabbar/browse.png",
    selectedIconPath: "/static/tabbar/browseHL.png",
    text: t("tabBar.browse"),
    code: "browse",
  },
  {
    iconPath: "/static/tabbar/order.png",
    selectedIconPath: "/static/tabbar/orderHL.png",
    text: t("tabBar.order"),
    code: "order",
  },
  {
    iconPath: "/static/tabbar/user.png",
    selectedIconPath: "/static/tabbar/userHL.png",
    text: t("tabBar.mine"),
    code: "mine",
  },
]);

function handleInviteUser() {
  if (inviteUserRef.value) {
    inviteUserRef.value.init();
  }
}

function handleCustomerService() {
  if (customerServiceRef.value) {
    customerServiceRef.value.init();
  }
}

// 组件初始化配置
const tabbarInitConfig = {
  home: {
    ref: tabbarHomeRef,
    methods: ["init", "initData"], // init优先执行，快速显示已有内容
  },
  browse: {
    ref: tabbarBrowseRef,
    methods: ["init", "initData"],
  },
  global: {
    ref: tabbarShopRef,
    methods: [],
    // methods: ['initData', 'init']
  },
  order: {
    ref: tabbarOrderRef,
    methods: ["initData"],
  },
  mine: {
    ref: tabBarMineRef,
    methods: ["init", "initData"],
  },
};

// 统一的组件初始化函数
function initTabbarComponent(tabType: string) {
  const config = tabbarInitConfig[tabType as keyof typeof tabbarInitConfig];
  if (!config) {
    console.warn(`未找到 ${tabType} 对应的初始化配置`);
    return;
  }

  const componentRef = config.ref.value;
  if (!componentRef) {
    console.warn(`${tabType} 组件引用不存在`);
    return;
  }

  // 对于home组件，优先执行init方法以快速显示内容
  if (tabType === "home") {
    // 立即执行init方法，无延迟
    if (typeof componentRef.init === "function") {
      componentRef.init();
    }
    // 然后执行initData方法
    if (typeof componentRef.initData === "function") {
      componentRef.initData();
    }
  } else {
    // 其他组件按原有顺序执行
    config.methods.forEach((method) => {
      if (typeof componentRef[method] === "function") {
        componentRef[method]();
      } else {
        console.warn(`${tabType} 组件不存在 ${method} 方法`);
      }
    });
  }
}

function handleTabbarChange({ value }: { value: string }) {
  initTabbarComponent(value);
}

const scoreRange = ref(""); // 星级评分
const price = ref(""); // 价格范围
function toggleScore() {
  if (scoreRef.value) {
    scoreRef.value.onOpen();
  }
}
function applyScore(value: string) {
  console.log("applyScore", value);
  scoreRange.value = value;
  tabbarHomeRef.value?.init();
}
function togglePrice() {
  if (priceChooseRef.value) {
    priceChooseRef.value.onOpen();
  }
}
function applyPrice(value: string) {
  console.log("applyPrice", value);
  price.value = value;
  nextTick(() => {
    tabbarHomeRef.value?.init();
  });
}

function toggleNotOpen() {
  if (notOpenRef.value) {
    notOpenRef.value.onOpen();
  }
}

function mineChangeOrder() {
  console.log("执行了");
  activeIndex.value = "order";
  handleTabbarChange({ value: "order" });
}

function handleClose() {
  showCoupon.value = false;
}

function receiveAllCoupon() {
  if (couponList.value.length === 0) {
    return handleClose()
  }
  receiveAllCouponApi().then(res => {
    if (res.code === 200) {
      uni.showToast({
        title: t('common.prompt.claimCouponSuccessfully'),
        icon: 'none'
      })
      handleClose()
    }
  })
}

function getFontUrl(fontRelativeUrl: string): string {
  let fontUrl = `url(/static/fonts/${fontRelativeUrl})`;
  // #ifdef APP-PLUS
  fontUrl = `url(${plus.io.convertLocalFileSystemURL(`_www/static/fonts/${fontRelativeUrl}`)})`;
  // #endif
  return fontUrl;
}

// 优化后的字体加载函数
function loadFonts() {
  // 防止重复加载
  if (fontLoadingState.value.isLoading || fontLoadingState.value.isLoaded) {
    return Promise.resolve();
  }

  fontLoadingState.value.isLoading = true;

  const fontConfigs = [
    { name: "UberMoveRegular", file: "UberMoveRegular.ttf", weight: "normal" },
    { name: "UberMoveMedium", file: "UberMoveMedium.otf", weight: "500" },
    { name: "UberMoveBold", file: "UberMoveBold.otf", weight: "700" },
  ];

  const loadPromises = fontConfigs.map((config) => loadSingleFont(config));

  return Promise.allSettled(loadPromises)
    .then((results) => {
      const successCount = results.filter(
        (result) => result.status === "fulfilled"
      ).length;
      const failedCount = results.length - successCount;

      if (successCount > 0) {
        fontLoadingState.value.isLoaded = true;
        console.log(`字体加载完成: ${successCount}/${results.length} 成功`);
      }

      if (
        failedCount > 0 &&
        fontLoadingState.value.retryCount < fontLoadingState.value.maxRetries
      ) {
        fontLoadingState.value.retryCount++;
        console.log(
          `字体加载失败 ${failedCount} 个，准备重试 (${fontLoadingState.value.retryCount}/${fontLoadingState.value.maxRetries})`
        );
        setTimeout(() => {
          fontLoadingState.value.isLoading = false;
          loadFonts();
        }, 1000 * fontLoadingState.value.retryCount);
      }
    })
    .finally(() => {
      fontLoadingState.value.isLoading = false;
    });
}

// 加载单个字体的函数
function loadSingleFont(config: {
  name: string;
  file: string;
  weight: string;
}) {
  return new Promise((resolve, reject) => {
    // 检查是否已加载
    if (fontLoadingState.value.loadedFonts.has(config.name)) {
      resolve(config.name);
      return;
    }

    const fontOptions: any = {
      family: "UberMove",
      source: getFontUrl(config.file),
      success: () => {
        fontLoadingState.value.loadedFonts.add(config.name);
        console.log(`字体加载成功: ${config.name}`);
        resolve(config.name);
      },
      fail: (error: any) => {
        console.error(`字体加载失败: ${config.name}`, error);
        reject(error);
      },
    };

    if (config.weight !== "normal") {
      fontOptions.desc = { weight: config.weight };
    }

    uni.loadFontFace(fontOptions);
  });
}

useNetworkStatusChange(() => {
  if (!userStore.location.location) {
    userStore.getLocation();
  }
  nextTick(() => {
    // tabbarHomeRef.value?.initData()
    // tabbarShopRef.value?.initData()
    // tabbarShopRef.value?.init()
    // tabbarOrderRef.value?.initData()
    // tabBarMineRef.value?.init()
  });
});

onLoad(async () => {
  uni.hideTabBar();

  // 并行执行初始化任务
  const initTasks = [loadFonts(), userStore.getLocation(), getInviteInfo()];

  try {
    await Promise.allSettled(initTasks);
    console.log("页面初始化完成");
  } catch (error) {
    console.error("页面初始化失败:", error);
  }

  // #ifdef APP-PLUS
  setTimeout(() => {
    appUpdate();
  }, 3000);
  // #endif
});

onShow(() => {
  if (configStore.tabbarIndex) {
    activeIndex.value = configStore.tabbarIndex;
  }
  nextTick(() => {
    handleTabbarChange({ value: activeIndex.value });
  });

  if (userStore.isLogin) {
    loadUserDataWithDebounce();

    // 获取用户信息
    userStore.getUserInfo();
    if(+userStore.userInfo.hasPop !== 2) {
      getCouponReceiveListApi().then(res=> {
        if(res.code === 200 && res.data?.length > 0) {
          showCoupon.value = true;
          couponList.value = res.data || [];
        }
      })
    }
    // getCouponReceiveListApi().then(res=> {
    //   showCoupon.value = true;
    //   couponList.value = res.data || [];
    // })
  }
});

// 防抖加载用户数据
const loadUserDataWithDebounce = debounce(1000, () => {
  loadUserData();
});

// 合并的用户数据加载函数
async function loadUserData() {
  if (apiLoadingState.value.isLoadingUserData) {
    return;
  }

  const now = Date.now();
  if (
    now - apiLoadingState.value.lastLoadTime <
    apiLoadingState.value.debounceDelay
  ) {
    return;
  }

  apiLoadingState.value.isLoadingUserData = true;
  apiLoadingState.value.lastLoadTime = now;

  try {
    // 并行执行多个接口调用
    const promises = [getUnreadMessageCount(), userStore.getAppointmentTime()];

    await Promise.allSettled(promises);
    console.log("用户数据加载完成");
  } catch (error) {
    console.error("用户数据加载失败:", error);
  } finally {
    apiLoadingState.value.isLoadingUserData = false;
  }
}

// 获取未读消息数量
function getUnreadMessageCount() {
  return appMessageUnreadCountPost({})
    .then((res) => {
      userStore.unreadMessageCount = res.data || 0;
    })
    .catch((error) => {
      console.error("获取未读消息数量失败:", error);
    });
}

useEventEmit(EventEnum.CHOOSE_ADDRESS, (data) => {
  console.log("设置用户的定位地址信息", data);
  if (data) {
    userStore.userSetLocation = {
      location: data.displayName,
      longitude: data.location.lng,
      latitude: data.location.lat,
    };
  }
});

// 获取邀请信息配置
function getInviteInfo() {
  if (userStore.isLogin) {
    getDictFineList({
      dictType: "invite_poster",
    }).then((res) => {
      console.log("获取邀请信息", res);
      if (res.data.length > 0) {
        res.data.map((item) => {
          if (item.dictValue === "bg_image") {
            Config.shareImage = item.dictLabel;
          }
          if (item.dictValue === "invite_url") {
            Config.shareLink = item.dictLabel;
          }
          if (item.dictValue === "desc_text") {
            Config.shareDesc = item.dictLabel;
          }
          if (item.dictValue === "weixinServiceUrl") {
            Config.weixinServiceUrl = item.dictLabel;
          }
        });
      }
    });

    // 获取支付相关配置（已去掉 stripeKey 覆盖，统一用 config/index.ts 里的 pk_live_ 跑通流程）
    // getDictFineList({
    //   dictType: "app_config",
    // }).then((res) => {
    //   res.data.map((item) => {
    //     if (item.dictValue === "stripeKey") {
    //       Config.stripeKey = item.remark;
    //     }
    //   });
    // });
  }
}
</script>

<template>
  <view class="page">
    <tabbar-home
      ref="tabbarHomeRef"
      :scoreRange="scoreRange"
      :price="price"
      @toggleScore="toggleScore"
      @togglePrice="togglePrice"
      @toggleNotOpen="toggleNotOpen"
      v-show="activeIndex === 'home'"
    />
    <tabbar-shop ref="tabbarShopRef" v-show="activeIndex === 'global'" />
    <tabbar-order ref="tabbarOrderRef" v-show="activeIndex === 'order'" />
    <tabbar-browse
      ref="tabbarBrowseRef"
      @toggleNotOpen="toggleNotOpen"
      v-show="activeIndex === 'browse'"
    />
    <tabbar-mine
      ref="tabBarMineRef"
      v-show="activeIndex === 'mine'"
      @inviteUser="handleInviteUser"
      @customerService="handleCustomerService"
      @changeOrder="mineChangeOrder"
    />
    <wd-tabbar
      custom-class="bg-#fff shadow-[0rpx_-6rpx_24rpx_rgba(0,0,0,0.1)]"
      fixed
      safeAreaInsetBottom
      placeholder
      v-model="activeIndex"
      @change="handleTabbarChange"
      activeColor="#333"
      inactiveColor="#999"
    >
      <wd-tabbar-item
        v-for="item in tabBarList"
        :key="item.code"
        :name="item.code"
        :title="item.text"
      >
        <template #icon>
          <view class="relative center">
            <wd-img
              class="absolute"
              custom-class="animate-in fade-in-50 zoom-in-80"
              height="46rpx"
              width="46rpx"
              v-show="activeIndex === item.code"
              :src="item.selectedIconPath"
            ></wd-img>
            <wd-img
              class="absolute"
              custom-class="animate-in fade-in-50"
              height="46rpx"
              width="46rpx"
              :src="item.iconPath"
              v-show="activeIndex !== item.code"
            ></wd-img>
          </view>
        </template>
      </wd-tabbar-item>
    </wd-tabbar>
  </view>
  <invite-user ref="inviteUserRef" />
  <use-code ref="useCodeRef" />
  <customer-service ref="customerServiceRef" />
  <!-- 星级筛选弹窗 -->
  <score @applyScore="applyScore" ref="scoreRef" />
  <price-choose @applyPrice="applyPrice" ref="priceChooseRef" />
  <not-open ref="notOpenRef" />
  <!-- 优惠券弹窗 -->
  <wd-popup
    v-model="showCoupon"
    position="center"
    custom-style="background:transparent;overflow:visible;padding:0rpx;"
    @close="handleClose"
  >
    <view class="relative w-640rpx h-874rpx">
      <image
        class="w-full h-874rpx absolute top-0 left-0"
        src="/static/images/5005.png"
      />
      <view
        class="w-full h-874rpx absolute top-0 left-0"
      >
        <view
          class="w-full h-250rpx px-74rpx pt-30rpx text-#6d2d00 text-36rpx font-700 leading-[1.35]"
        >
          <view class="">{{ t('pages-store.store.tips-1') }}</view>
          <view class="mt-4rpx">{{ t('pages-store.store.tips-2') }}</view>
        </view>

        <view
          class="w-full"
        >
          <view
            class="text-center text-30rpx text-#b36f2c font-600 tracking-wide flex-center-sb px-70rpx"
            >
            <image
                class="w-92rpx h-5rpx"
                src="@img/5006.png"
            />
            {{ t('pages-store.store.congratulations') }}
            <image
                class="w-92rpx h-5rpx rotate-180"
                src="@img/5006.png"
            />
          </view>

          <scroll-view scroll-y class="mt-32rpx h-420rpx px-62rpx box-border">
            <view
              v-for="item in couponList"
              :key="item.id"
              class="relative mb-24rpx rounded-24rpx border-2rpx border-#f5c78c bg-#fff7ed px-32rpx h-136rpx shadow-[0_8rpx_20rpx_rgba(0,0,0,0.08)]"
            >
              <image
                  class="w-full h-full absolute top-0 left-0"
                  src="/static/images/5007.png"
              />
              <view class="w-full px-32rpx py-10rpx box-border absolute top-0 left-0">
                <view class="text-32rpx font-700 text-#c16a1c">
<!--                  1-折扣券, 2-满减券-->
                  <text v-if="+item.couponType === 1" class="">
                    {{ Number(item.discountValue * 100).toFixed(0) }}% {{ t('pages-store.store.couponOff') }}
                  </text>
                  <text v-if="+item.couponType === 2" class="">
                    ${{ item.discountValue }} {{ t('pages-store.store.couponOff') }}
                  </text>
                </view>
                <view class="mt-4rpx text-24rpx text-#a0611d">
                  {{ t('pages-store.store.validDays') }}: {{ item.validDays }}{{ daySuffix(item.validDays) }}</view>
                <view class="mt-8rpx text-24rpx text-#a0611d">
                  {{ item?.merchantVo?.merchantName }}
                </view>
              </view>
            </view>


            <view v-if="couponList.length === 0" class="pt-60rpx center">
              <image class="w-250rpx h-250rpx" src="@img/16033@2x.png"></image>
            </view>
          </scroll-view>

          <view class="px-70rpx mt-12rpx">
            <view
              class="h-96rpx rounded-full bg-gradient-to-b from-[#7b3f1b] to-[#3f2210] text-#f7e5c6 text-32rpx font-700 center"
              @click="receiveAllCoupon"
            >
              {{ t('pages-store.store.tips-3') }}
            </view>
          </view>
        </view>
      </view>

      <view
        class="absolute left-1/2 -bottom-120rpx -translate-x-1/2 w-88rpx h-88rpx center text-68rpx text-#fff"
        @click="handleClose"
      >
        <view class="i-carbon:close-outline"></view>
      </view>
    </view>
  </wd-popup>
  <!-- 优惠券弹窗 -->
</template>

<style lang="scss"></style>
