<template>
  <view class="page-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{paddingTop: statusBarHeight + 'px'}">
      <view class="navbar-content">
        <view class="navbar-title">
          <uv-icon name="account-fill" color="#FFFFFF" size="20"></uv-icon>
          <text class="title-text">我的</text>
        </view>
      </view>
    </view>

    <!-- 页面内容区域 -->
    <scroll-view class="content-scroll" scroll-y="true">
      <custom-service></custom-service>

      <!-- 用户信息与钱包合并卡片 -->
      <view class="user-wallet-card">
        <!-- 用户信息区域 -->
        <view class="user-section" @click="handleUserClick">
          <view class="user-avatar-wrapper">
            <image class="user-avatar" src='/static/iconfont/me.svg'></image>
          </view>
          <text class="user-phone">{{ user.mobilePhone || '未登录' }}</text>
        </view>

        <!-- 分割线 -->
        <view class="divider"></view>

        <!-- 钱包信息区域 -->
        <view class="wallet-section" @click="toPage({path: '/pages-user/wallet/index'})">
          <view class="wallet-header">
            <view class="wallet-title">
              <uv-icon name="red-packet" size="22" color="#C6171E"></uv-icon>
              <text class="wallet-title-text">钱包余额</text>
            </view>
            <uv-icon name="arrow-right" size="14" color="#C0C4CC"></uv-icon>
          </view>

          <view class="wallet-body">
            <view class="wallet-balance">
              <view class="balance-value">
                <text class="balance-symbol">¥</text>
                <text class="balance-amount">{{ ((user.balance || 0) / 100).toFixed(2) }}</text>
                <text class="balance-unit">元</text>
              </view>
            </view>

            <view class="wallet-actions">
              <view class="action-btn action-recharge" @click.stop="toPage({path: '/pages-user/wallet/recharge'})">
                <text>充值</text>
              </view>
              <view class="action-btn action-detail" @click.stop="toPage({path: '/pages-user/wallet/index'})">
                <text>明细</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 功能菜单列表 -->
      <view class="menu-section">
        <view class="section-title">
          <view class="title-dot"></view>
          <text>功能服务</text>
        </view>

        <view class="menu-list">
          <view
            class="menu-item"
            v-for="(item, index) in menu"
            :key="index"
            @click="toPage(item)"
          >
            <view class="menu-left">
              <view class="menu-icon-box" :class="'menu-icon-box--' + item.color">
                <image v-if="item.iconType === 'image'" class="menu-icon" :src="item.icon" mode="aspectFit"></image>
                <uv-icon v-else :name="item.icon" size="22" :color="item.iconColor || '#C6171E'"></uv-icon>
              </view>
              <text class="menu-text">{{ item.title }}</text>
            </view>
            <uv-icon name="arrow-right" size="16" color="#C0C4CC"></uv-icon>
          </view>
        </view>
      </view>

      <!-- 退出登录按钮 -->
      <view class="logout-wrapper" v-if="isLogin">
        <view class="logout-btn" @click="logoutUser">
          <text>退出登录</text>
        </view>
      </view>

      <!-- 底部占位 -->
      <view style="height: 140rpx;"></view>
    </scroll-view>

    <!-- 底部导航栏 -->
    <tab-bar :index="2"/>
  </view>
</template>

<script setup lang="ts">
import {onHide, onLoad, onShow} from "@dcloudio/uni-app";
import {ref} from "vue";
import TabBar from "@/components/tab-bar/index.vue";
import {checkLogin, clearToken, loadUserInfo} from "@/utils/auth"
import {get} from "@/utils/https";

const statusBarHeight = ref(0)
const user = ref<any>({
  id: 0,
  avatar: "",
  mobilePhoneFormat: '',
  balance: 0,
});
const isLogin = ref(false)
const menu = ref([
  {
    title: "我的车辆",
    path: "/pages-user/profile/index",
    icon: '/static/iconfont/car.svg',
    iconType: 'image',
    color: 'red',
  },
  {
    title: "我的订单",
    path: "/pages-order/list/index",
    icon: 'order',
    iconColor: '#C6171E',
    color: 'red',
  },
  // {
  //   title: "联系我们",
  //   path: "/pages-user/contact/index",
  //   icon: '/static/user/contact.png'
  // },
  {
    title: "洗车指导",
    path: "/pages-user/faq/index",
    icon: 'question-circle',
    iconColor: '#C6171E',
    color: 'red',
  },
  {
    title: "故障反馈",
    path: "/pages-user/feedback/index",
    icon: 'warning',
    iconColor: '#C6171E',
    color: 'red',
  },
]);


const toPage = (item: any) => {
  checkLogin().then(() => {
    uni.navigateTo({
      url: item.path,
    });
  }).catch(e => {
    console.error("handleMenuClick 校验，跳转登录页", e)
    uni.navigateTo({
      url: '/pages-user/login/index'
    })
  })

};

const handleUserClick = () => {
  if (!isLogin.value || !user.value.mobilePhone) {
    uni.navigateTo({
      url: '/pages-user/login/index'
    })
  }
};

const logoutUser = () => {
  uni.showModal({
    title: "温馨提示",
    content: "确定退出登录吗？",
    confirmColor: "#C6171E",
    confirmText: "确定退出",
    cancelText: "手滑了",
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({
          title: "退出中",
        });

        get(`/user/logout`).then(() => {
          uni.hideLoading();
          uni.showToast({
            icon: "success",
            title: "已退出",
          });
          isLogin.value = false;
          getApp<any>().globalData.user = {};
          getApp<any>().globalData.manualLogout = true;
          clearToken();
          setTimeout(() => {
            uni.exitMiniProgram()
          }, 1500);

        })
      }
    },
  });
};

onLoad(() => {
  const systemInfo = uni.getSystemInfoSync();
  statusBarHeight.value = systemInfo.statusBarHeight || 0;
});

const addListener = () => {
  uni.$on('login', function (data) {
    isLogin.value = data.isLogin;
    if (data.isLogin) {
      user.value = getApp<any>().globalData.user;
    }
  })

  uni.$on('logout', function (data) {
    isLogin.value = false;
    user.value = {}
  })
}

const removeListener = () => {
  uni.$off('logout');
  uni.$off('login');
}

onShow(() => {
  let gd = getApp<any>().globalData;
  if (gd.refresh) {
    if (gd.user?.id) {
      refreshUserProfile()
    }
  } else {
    if (gd.user?.id) {
      if (new Date().getTime() - new Date(gd.user.lastLoginTime).getTime() > 300 * 1000) {
        refreshUserProfile()
      } else {
        isLogin.value = true;
        user.value = gd.user;
      }
    }
  }
  addListener();
});

const refreshUserProfile = () => {
  isLogin.value = true;
  loadUserInfo().then(val => {
    if (val && val.id) {
      user.value = val;
    }
    getApp<any>().globalData.refresh = false;
  })
}

onHide(() => {
  removeListener();
})
</script>

<style lang="scss" scoped>
page {
  background: $uni-bg-color-page;
}

.page-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(180deg, $uni-color-primary 0%, $uni-color-primary-light 25%, $uni-bg-color-page 45%);
  display: flex;
  flex-direction: column;
}

// 自定义导航栏
.custom-navbar {
  position: relative;
  z-index: 100;

  .navbar-content {
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .navbar-title {
      display: flex;
      align-items: center;
      gap: 12rpx;

      .title-text {
        color: $uni-text-color-inverse;
        font-size: 36rpx;
        font-weight: $uni-font-weight-semibold;
        letter-spacing: 2rpx;
      }
    }
  }
}

// 内容滚动区域
.content-scroll {
  flex: 1;
  height: 100%;
  width: 100%;
}

// 用户信息与钱包合并卡片
.user-wallet-card {
  margin: 30rpx 30rpx 24rpx;
  @include card-interactive(24rpx);
  overflow: hidden;

  // 用户信息区域
  .user-section {
    padding: 24rpx 32rpx;
    display: flex;
    align-items: center;
    gap: 20rpx;

    .user-avatar-wrapper {
      flex-shrink: 0;

      .user-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        background: rgba($uni-color-primary, 0.08);
        padding: 10rpx;
        box-sizing: border-box;
      }
    }

    .user-phone {
      font-size: 30rpx;
      font-weight: $uni-font-weight-semibold;
      color: $uni-text-color;
    }
  }

  // 分割线
  .divider {
    height: 1rpx;
    background: $uni-border-color-light;
    margin: 0 32rpx;
  }

  // 钱包区域
  .wallet-section {
    padding: 28rpx 32rpx 24rpx;

    .wallet-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .wallet-title {
        display: flex;
        align-items: center;
        gap: 8rpx;
        font-size: 26rpx;
        font-weight: $uni-font-weight-semibold;
        color: $uni-text-color;

        .wallet-title-text {
          font-size: 30rpx;
        }
      }
    }

    .wallet-body {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .wallet-balance {
      .balance-value {
        display: flex;
        align-items: baseline;
        gap: 4rpx;

        .balance-symbol {
          font-size: 28rpx;
          color: $uni-text-color-dark;
          font-weight: $uni-font-weight-semibold;
        }

        .balance-amount {
          font-size: 44rpx;
          color: $uni-text-color-dark;
          font-weight: $uni-font-weight-bold;
          line-height: 1;
        }

        .balance-unit {
          font-size: 24rpx;
          color: $uni-text-color-hint;
          margin-left: 2rpx;
        }
      }
    }

    .wallet-actions {
      display: flex;
      gap: 16rpx;
      flex-shrink: 0;

      .action-btn {
        padding: 12rpx 36rpx;
        border-radius: 40rpx;
        font-size: 24rpx;
        font-weight: $uni-font-weight-medium;
        text-align: center;

        &.action-recharge {
          background: $uni-color-primary;
          color: #fff;
        }

        &.action-detail {
          background: rgba($uni-color-primary, 0.08);
          color: $uni-color-primary;
        }
      }
    }
  }
}

// 菜单区域
.menu-section {
  margin: 0 30rpx 24rpx;

  .section-title {
    display: flex;
    align-items: center;
    gap: 12rpx;
    padding: 0 12rpx;
    margin-bottom: 20rpx;
    font-size: 28rpx;
    font-weight: $uni-font-weight-semibold;
    color: $uni-text-color;

    .title-dot {
      width: 10rpx;
      height: 10rpx;
      background: $uni-color-primary;
      border-radius: 50%;
    }
  }

  .menu-list {
    @include card-interactive(24rpx);
    overflow: hidden;
  }

  .menu-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid $uni-border-color-light;

    &:last-child {
      border-bottom: none;
    }

    .menu-left {
      display: flex;
      align-items: center;
      gap: 24rpx;

      .menu-icon-box {
        width: 72rpx;
        height: 72rpx;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .menu-icon {
          width: 42rpx;
          height: 42rpx;
        }

        &--red {
          background: rgba($uni-color-primary, 0.08);
        }

        &--blue {
          background: rgba(33, 150, 243, 0.08);
        }

        &--green {
          background: rgba(76, 175, 80, 0.08);
        }

        &--orange {
          background: rgba(255, 152, 0, 0.08);
        }
      }

      .menu-text {
        font-size: 28rpx;
        color: $uni-text-color;
      }
    }
  }
}

// 退出按钮
.logout-wrapper {
  margin: 40rpx 30rpx;

  .logout-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88rpx;
    @include card-interactive(44rpx);
    font-size: 28rpx;
    color: $uni-color-error;
    font-weight: $uni-font-weight-semibold;
  }
}
</style>
