<template>
  <view class="page-mine">
    <!-- 顶部用户信息区 -->
    <view class="user-section">
      <user-profile
        :avatar="userInfo?.avatar"
        :name="userInfo?.nickname"
        :phone="userInfo?.phone"
        :is-logged-in="userStore.isLoggedIn()"
        @click="handleProfileTap"
      />
    </view>


    <view class="quick-section">
      <tool-grid
        :tools="toolList"
        @item-click="handleToolTap"
      />
    </view>

 




    <!-- 商家服务 -->
    <view class="menu-section">
      <menu-list
        :items="merchantMenuItems"
        @item-click="handleMerchantMenuTap"
      />
    </view>

    <!-- 设置 -->
    <view class="menu-section">
      <menu-list
        :items="settingMenuItems"
        @item-click="handleSettingMenuTap"
      />
    </view>

    <!-- 退出登录 -->
    <view v-if="userStore.isLoggedIn()" class="logout-section">
      <base-button
        type="danger"
        size="large"
        block
        @click="handleLogout"
      >
        退出登录
      </base-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useUserStore } from '@/store/user';
import { useSellerStore } from '@/store/seller';
import { bindInvitation, getInviteStats } from '@/api/user/invite';
import UserProfile from '@/components/business/UserProfile.vue';
import OrderQuickNav from '@/components/business/OrderQuickNav.vue';
import ToolGrid from '@/components/business/ToolGrid.vue';
import MenuList from '@/components/business/MenuList.vue';
import BaseButton from '@/components/base/BaseButton.vue';

const userStore = useUserStore();
const sellerStore = useSellerStore();
const userInfo = computed(() => userStore.userInfo);

// 常用工具列表
const toolList = [
  { key: 'orders', label: '我的订单', icon: 'list', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
  { key: 'wallet', label: '我的钱包', icon: 'rmb-circle', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
  { key: 'coupon', label: '优惠券', icon: 'coupon', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
  { key: 'invite', label: '邀请返现', icon: 'gift', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
];

// 商家服务菜单
const merchantMenuItems = [
  { key: 'merchant-center', label: '商家中心', icon: 'home', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
  { key: 'merchant-entry', label: '商家入驻', icon: 'star', iconColor: '#1A1A1A', bgColor: '#FFFFFF' }
];

// 设置菜单
const settingMenuItems = [
   { key: 'guest', label: '常旅客信息', icon: 'account', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
  { key: 'profile', label: '个人信息', icon: 'account', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
  { key: 'bind-invite', label: '绑定邀请码', icon: 'scan', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
    { key: 'service', label: '联系客服', icon: 'chat', iconColor: '#1A1A1A', bgColor: '#FFFFFF' },
  { key: 'about', label: '关于我们', icon: 'info-circle', iconColor: '#1A1A1A', bgColor: '#FFFFFF' }
];

function handleProfileTap() {
  if (!userStore.isLoggedIn()) {
    goLogin();
  }
}

function goLogin() {
  uni.navigateTo({ url: '/pages/login/index' });
}

function navigateTo(url: string) {
  if (!userStore.isLoggedIn()) {
    goLogin();
    return;
  }
  uni.navigateTo({ url });
}

function handleOrderTap(status: string) {
  navigateTo(`/pages/order/index?status=${status}`);
}

function goAllOrders() {
  navigateTo('/pages/order/index');
}

function handleToolTap(key: string) {
  switch (key) {
    case 'orders':
      goAllOrders();
      break;
    case 'wallet':
      goWallet();
      break;
    case 'invite':
      goInvite();
      break;
    case 'coupon':
      goCoupon();
      break;
    case 'guest':
      goGuest();
      break;
    case 'favorite':
      showComingSoon('收藏');
      break;
    case 'service':
      showComingSoon('客服');
      break;
  }
}

function handleMerchantMenuTap(key: string) {
  console.log(key)
  switch (key) {
    case 'merchant-center':
      goMerchantCenter();
      break;
    case 'merchant-entry':
      goMerchantEntry();
      break;
  }
}

function handleSettingMenuTap(key: string) {
  switch (key) {
    case 'guest':
      goGuest();
      break;
    case 'profile':
      goProfile();
      break;
    case 'bind-invite':
      handleBindInviteCode();
      break;
    case 'service':
      showComingSoon('客服');
      break;
    case 'about':
      goAbout();
      break;
  }
}

function goMerchantEntry() {
  if (!userStore.isLoggedIn()) {
    goLogin();
    return;
  }
  uni.navigateTo({ url: '/pages/seller/register?mode=register' });
}

function goMerchantCenter() {
  if (!sellerStore.isSellerLoggedIn()) {
    uni.navigateTo({ url: '/pages/seller/register?mode=login' });
    return;
  }
  uni.navigateTo({ url: '/pages/seller/home' });
}

function goWallet() {
  if (!userStore.isLoggedIn()) {
    goLogin();
    return;
  }
  uni.navigateTo({ url: '/pages/wallet/index' });
}

function goInvite() {
  if (!userStore.isLoggedIn()) {
    goLogin();
    return;
  }
  uni.navigateTo({ url: '/pages/invite/index' });
}

function goCoupon() {
  if (!userStore.isLoggedIn()) {
    goLogin();
    return;
  }
  uni.navigateTo({ url: '/pages/coupon/my-coupons' });
}

function goGuest() {
  if (!userStore.isLoggedIn()) {
    goLogin();
    return;
  }
  uni.navigateTo({ url: '/pages/guest/index' });
}

function goAbout() {
  uni.navigateTo({ url: '/pages/about/index' });
}

function goProfile() {
  navigateTo('/pages/profile/index');
}

function showComingSoon(feature: string) {
  uni.showToast({
    title: `${feature}功能开发中`,
    icon: 'none',
  });
}

async function handleBindInviteCode() {
  if (!userStore.isLoggedIn()) {
    goLogin();
    return;
  }

  // 先检查是否已经绑定过邀请码
  uni.showLoading({ title: '加载中...' });
  try {
    const response = await getInviteStats();
    uni.hideLoading();

    // 如果已经绑定过，显示提示
    if (response.data.hasInviter) {
      uni.showToast({
        title: '您已绑定过邀请码',
        icon: 'none',
      });
      return;
    }
  } catch (error: any) {
    uni.hideLoading();
    uni.showToast({
      title: '获取绑定状态失败',
      icon: 'none',
    });
    return;
  }

  // 未绑定，显示输入框
  uni.showModal({
    title: '绑定邀请码',
    editable: true,
    placeholderText: '请输入邀请码',
    success: async (res) => {
      if (res.confirm && res.content) {
        const inviteCode = res.content.trim();
        if (!inviteCode) {
          uni.showToast({
            title: '请输入邀请码',
            icon: 'none',
          });
          return;
        }

        uni.showLoading({ title: '绑定中...' });
        try {
          const response = await bindInvitation(inviteCode);
          uni.hideLoading();

          if (response.data.success) {
            uni.showToast({
              title: '绑定成功',
              icon: 'success',
            });
          } else {
            uni.showToast({
              title: response.data.message || '绑定失败',
              icon: 'none',
            });
          }
        } catch (error: any) {
          uni.hideLoading();
          uni.showToast({
            title: error.message || '绑定失败',
            icon: 'none',
          });
        }
      }
    },
  });
}

function handleLogout() {
  uni.showModal({
    title: '提示',
    content: '确定退出登录？',
    success: (res) => {
      if (res.confirm) {
        userStore.logout();
      }
    },
  });
}
</script>

<style lang="scss" scoped>
@import '@/static/styles/design-tokens.scss';
@import '@/static/styles/mixins.scss';

.quick-section{
   margin-top: -$spacing-xl;
}

.page-mine {
  min-height: 100vh;
  background: $bg-page;
}

/* ========== 用户信息区 ========== */
.user-section {
  background: $gradient-primary;
}

/* ========== 菜单区域 ========== */
.menu-section {
  margin: 0 $spacing-2xl $spacing-lg;
}

/* ========== 退出登录 ========== */
.logout-section {
  margin: $spacing-2xl $spacing-2xl $spacing-3xl;
}
</style>
