<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">
          <view class="user-avatar-wrapper">
            <image class="user-avatar" src='/static/iconfont/me.svg'></image>
          </view>

          <view class="user-info">
            <view class="user-phone">{{ user.mobilePhone || '未登录' }}</view>
            <view class="user-tip">欢迎使用Yeswash洗车</view>
          </view>
        </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="bag" size="18" color="#C6171E"></uv-icon>
              <text>我的钱包</text>
            </view>
            <uv-icon name="arrow-right" size="14" color="#C0C4CC"></uv-icon>
          </view>

          <view class="wallet-balance">
            <text class="balance-label">账户余额 (元)</text>
            <view class="balance-value">
              <text class="balance-symbol">¥</text>
              <text class="balance-amount">{{ ((user.balance || 0) / 100).toFixed(2) }}</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 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">
                <image class="menu-icon" :src="item.icon" mode="aspectFit"></image>
              </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">
          <uv-icon name="error-circle" color="#DD524D" size="18"></uv-icon>
          <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 {computed, ref} from "vue";
import TabBar from "@/components/tab-bar/index.vue";
import LoginBar from "@/components/login-bar/index.vue";
import {checkLogin, clearToken, loadUserInfo} from "@/utils/auth"
import {get} from "@/utils/https";
import {getServicePhone} from "@/utils/common";

const statusBarHeight = ref(0)
const user = ref<any>({
  id: 0,
  avatar: "",
  mobilePhoneFormat: '',
  balance: 0,
});
const isLogin = ref(false)
const service = ref("15012341234");
const menu = ref([
  {
    title: "绑定车辆",
    path: "/pages-user/profile/index",
    icon: '/static/user/profile.png'
  },
  {
    title: "我的订单",
    path: "/pages-order/list/index",
    icon: '/static/user/faq.png'
  },
  {
    title: "联系我们",
    path: "/pages-user/contact/index",
    icon: '/static/user/contact.png'
  },
  {
    title: "洗车指导",
    path: "/pages-user/faq/index",
    icon: '/static/iconfont/default/guide.svg'
  },
  {
    title: "纠错上报",
    path: "/pages-user/feedback/index",
    icon: '/static/user/feedback.png'
  },
]);


const toPage = (item: any) => {
  checkLogin().then(() => {
    let {title, path} = item;
    let servicePhone = getServicePhone();
    if (path.includes('contact')) {
      uni.makePhoneCall({
        phoneNumber: servicePhone,
        fail: (error) => {
        }
      });
      return;
    }

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

};

const loginListen = () => {

}

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;
      }
    }
  }
  let currentPages = getCurrentPages();
  if (currentPages.length > 1) {
    let lastPage = currentPages[currentPages.length - 2]
  }

  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: 32rpx;
    display: flex;
    align-items: center;
    gap: 24rpx;

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

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

    .user-info {
      flex: 1;

      .user-phone {
        font-size: 32rpx;
        font-weight: $uni-font-weight-semibold;
        color: $uni-text-color;
        margin-bottom: 8rpx;
      }

      .user-tip {
        font-size: 24rpx;
        color: $uni-text-color-hint;
      }
    }
  }

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

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

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

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

    .wallet-balance {
      margin-bottom: 28rpx;

      .balance-label {
        font-size: 24rpx;
        color: $uni-text-color-hint;
        margin-bottom: 12rpx;
        display: block;
      }

      .balance-value {
        display: flex;
        align-items: baseline;
        justify-content: center;
        gap: 6rpx;

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

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

    .wallet-actions {
      display: flex;
      justify-content: center;
      gap: 20rpx;

      .action-btn {
        padding: 14rpx 48rpx;
        border-radius: 40rpx;
        font-size: 26rpx;
        font-weight: $uni-font-weight-medium;

        &.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: 28rpx 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;
        background: rgba($uni-color-primary, 0.08);
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;

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

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

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

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