<template>
  <view class="container">
    <!-- 顶部标题 -->
    <view class="header">
      <view class="header-title">管理您的账户信息和服务</view>
    </view>

    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-info">
        <image
          class="avatar"
          src="/static/imgs/avatar.png"
          mode="aspectFill"
        ></image>
        <view class="user-details">
          <view class="username">
            {{ userStore.userInfo.username }}
            <u-icon
              name="checkmark-circle-fill"
              color="#ffa500"
              size="16"
            ></u-icon>
          </view>
          <view class="user-id">用户ID: {{ userStore.userInfo.id }}</view>
          <view class="membership">
            会员等级:
            <span v-if="memberInfo.is_vip">
              {{ memberInfo.plan?.name }} (有效期至:
              {{
                memberInfo.end_at
                  ? dayjs(memberInfo.end_at * 1000).format("YYYY-MM-DD")
                  : ""
              }})
            </span>
            <span v-else>无</span>
          </view>
        </view>
      </view>
      <view class="edit-btn" @click="editProfile">
        <text>点击编辑资料</text>
      </view>
    </view>

    <!-- 账户余额 -->
    <view class="balance-card">
      <div>
        <view class="balance-header">
          <view class="balance-label">账户余额</view>
        </view>
        <view class="balance-amount">
          ¥{{ memberInfo.wallet_balance || 0 }}
        </view>
      </div>
      <uv-button
        type="primary"
        color="#fff"
        customStyle="color:#000;width:90px"
        shape="circle"
        @click="recharge"
      >
        充值
      </uv-button>
    </view>

    <!-- 会员套餐 -->
    <view class="membership-section">
      <view class="membership-grid">
        <view
          class="membership-item"
          :class="{ active: selectedPlan === item.id }"
          v-for="item in planList"
          :key="item.id"
          @click="selectPlan(item)"
        >
          <view class="tag" v-if="item.tags">{{ item.tags }}</view>
          <view class="plan-name">{{ item.name }}</view>
          <view class="plan-price">¥{{ item.price }}</view>
          <view class="desc">{{ item.desc }}</view>
        </view>
        <!--        <view
          class="membership-item"
          :class="{ active: selectedPlan === 'season' }"
          @click="selectPlan('season')"
        >
          <view class="tag">最受欢迎</view>
          <view class="plan-name">包季会员</view>
          <view class="plan-price">¥300</view>
          <view class="plan-discount">立减¥60</view>
        </view>
        <view
          class="membership-item"
          :class="{ active: selectedPlan === 'yearly' }"
          @click="selectPlan('yearly')"
        >
          <view class="tag">年度首享</view>
          <view class="plan-name">包年会员</view>
          <view class="plan-price">¥1000</view>
          <view class="plan-discount">立减¥440</view>
        </view> -->
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-section">
      <uv-button type="primary" @click="goToPayment">前往支付</uv-button>
      <!-- <view class="agreement">
        购买前请仔细阅读
        <text class="link" @click="showAgreement">《会员服务协议》</text>
      </view> -->
    </view>

    <view class="app-section">
      <!-- 缓存 -->
      <!-- 			<view class="profile-item" @click="clearCache">
				<view class="item-label">缓存</view>
				<view class="item-content">
					<text class="item-value">{{ cacheSize }}</text>
					<uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
				</view>
			</view> -->

      <!-- 用户协议 -->
      <view class="profile-item" @click="templateApply">
        <view class="item-label">模板申请</view>
        <view class="item-content">
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>
      <view class="profile-item" @click="viewUserAgreement">
        <view class="item-label">用户协议</view>
        <view class="item-content">
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>

      <!-- 关于我们 -->
      <view class="profile-item" @click="viewAbout">
        <view class="item-label">关于我们</view>
        <view class="item-content">
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>
      <view class="profile-item" @click="addRequirement">
        <view class="item-label">新增需求</view>
        <view class="item-content">
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>
<!--      <view class="profile-item" @click="bugFeedback">
        <view class="item-label">bug反馈</view>
        <view class="item-content">
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view> -->
      <view class="profile-item" @click="logout">
        <view class="item-label">退出登录</view>
        <view class="item-content">
          <uv-icon name="arrow-right" size="16" color="#ccc"></uv-icon>
        </view>
      </view>
    </view>

    <!-- <view class="logout-section">
      <uv-button
        type="error"
        @click="logout"
        :loading="logoutLoading"
      >
        退出登录
      </uv-button>
    </view> -->
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onShow, onPullDownRefresh } from "@dcloudio/uni-app";
import HeaderCustom from "/components/HeaderCustom/HeaderCustom.vue";
import { useAuthStore, useUserStore } from "@/store";
import RPC from "@/utils/request";
import dayjs from "dayjs";

const modal = ref(null);
const authStore = useAuthStore();
const userStore = useUserStore();

const balance = ref(null);
// const getBalance = () => {
// 	RPC.post('/wallet/balance', {
// 		user_id: userStore.userInfo.id
// 	}).then(res => {
// 		balance.value = res.balance_cents || 0
// 	})
// }
const memberInfo = ref({});
const getMemberInfo = () => {
  uni.showLoading();
  RPC.post("/membership/user/info", {
    user_id: userStore.userInfo.id,
  })
    .then((res) => {
      memberInfo.value = res || {};
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const viewUserAgreement = () => {
  uni.navigateTo({
    url: "/pagesA/user-agreement/user-agreement",
  });
};
const templateApply = () => {
  uni.navigateTo({
    url: "/pagesA/template-apply/template-apply",
  });
};

// 新增需求
const addRequirement = () => {
  uni.navigateTo({
    url: "/pagesA/add-requirement/add-requirement",
  });
};
const bugFeedback = () => {
  uni.navigateTo({
    url: "/pagesA/bug-feedback/bug-feedback",
  });
};

// 响应式数据
const selectedPlan = ref("");
const planList = ref([]);
const getPlanList = () => {
  RPC.post("/membership_plan/list", {
    page: 1,
    limit: -1,
    orderby: [
      {
        sort: "asc",
      },
    ],
  }).then((res) => {
    planList.value = (res.rows || []).filter((item) => item.enabled);
    selectedPlan.value = planList.value[0] ? planList.value[0].id : "";
  });
};
// 选择会员套餐
const selectPlan = (plan) => {
  selectedPlan.value = plan.id;
};

// 编辑资料
const editProfile = () => {
  uni.navigateTo({
    url: "/pagesA/edit-profile/edit-profile",
  });
};

// 充值
const recharge = () => {
  uni.navigateTo({
    url: "/pagesA/recharge/recharge",
  });
};

// 跳转到支付页面
const goToPayment = () => {
  if (!selectedPlan.value) {
    uni.showToast({
      title: "请选择会员套餐",
      icon: "none",
    });
    return;
  }

  // 获取选中的套餐信息
  const selectedPlanInfo = planList.value.find(
    (plan) => plan.id === selectedPlan.value
  );

  // 跳转到支付页面，传递套餐信息
  uni.navigateTo({
    url: `/pagesA/payment/payment?planId=${
      selectedPlan.value
    }&planName=${encodeURIComponent(selectedPlanInfo?.name || "")}&planPrice=${
      selectedPlanInfo?.price || 0
    }`,
  });
};

// 显示协议
const showAgreement = () => {
  uni.navigateTo({
    url: "/pagesA/user-agreement/user-agreement",
  });
};

// 页面挂载时获取套餐列表
onMounted(() => {
  //   getPlanList();
});

// 页面显示时获取会员信息
onShow(() => {
  getPlanList();
  getMemberInfo();
});
onPullDownRefresh(() => {
  getPlanList();
  // getBalance()
  getMemberInfo();
  uni.stopPullDownRefresh();
});

const logoutLoading = ref(false);

const logout = () => {
  uni.showModal({
    title: "退出登录",
    content: "确定要退出登录吗？",
    success: (res) => {
      if (res.confirm) {
        logoutLoading.value = true;

        // 模拟退出登录
        setTimeout(() => {
          authStore.signOut();
          logoutLoading.value = false;

          // 清除用户信息和token
          // authStore.logout()

          uni.showToast({
            title: "已退出登录",
            icon: "success",
          });

          // 跳转到登录页
          uni.reLaunch({
            url: "/pages/login/login",
          });
        }, 1000);
      }
    },
  });
};
</script>

<style lang="scss" scoped>
.container {
  font-size: 14px;
  background: linear-gradient(180deg, #7b9cdb 0%, #f8f8f8 40%);
  min-height: 100vh;
  //   padding-bottom: 120px;

  /* #ifdef H5 */
  //   padding-bottom: 170px;
  /* H5环境下需要更多空间 (底部按钮高度 + tabBar高度 + 间距) */
  /* #endif */
}

.header {
  padding: 20px 16px 16px;

  .header-title {
    color: white;
    font-size: 18px;
    font-weight: 500;
  }
}

.user-card {
  margin: 0 16px 16px;
  background: white;
  border-radius: 12px;
  padding: 16px;
  position: relative;

  .user-info {
    display: flex;
    align-items: center;
    // margin-bottom: 12px;

    .avatar {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      margin-right: 12px;
      overflow: hidden;

      .img {
        width: 100%;
        height: 100%;
      }
    }

    .user-details {
      flex: 1;

      .username {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 18px;
        font-weight: bold;
        color: #333;
        margin-bottom: 4px;
      }

      .user-id {
        font-size: 12px;
        color: #999;
        margin-bottom: 2px;
      }

      .membership {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .edit-btn {
    text-align: right;
    color: #4285f4;
    font-size: 14px;
    position: absolute;
    top: 10px;
    right: 20px;
  }
}

.balance-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 16px 16px;
  background: linear-gradient(135deg, #4285f4 0%, #6fa8f5 100%);
  border-radius: 12px;
  padding: 16px;
  color: white;

  .balance-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;

    .balance-label {
      font-size: 14px;
      opacity: 0.9;
    }
  }

  .balance-amount {
    font-size: 28px;
    font-weight: bold;
  }
}

.membership-section {
  margin: 0 16px 16px;

  .membership-grid {
    display: flex;
    justify-content: space-between;
    gap: 8px;
    overflow-x: auto;

    .membership-item {
      width: 24%;
      flex-shrink: 0;
      background: white;
      border-radius: 12px;
      padding: 12px 8px;
      text-align: center;
      position: relative;
      border: 2px solid transparent;
      transition: all 0.3s;
      overflow: hidden;

      &.active {
        border-color: #4285f4;
        background-color: #f0f7ff;
      }

      .tag {
        position: absolute;
        top: 0px;
        left: 0;
        padding: 2px 8px;
        border-radius: 0 0 10px 0;
        font-size: 10px;
        color: white;
        background: #ff3333;
      }

      .plan-name {
        font-size: 14px;
        color: #333;
        margin: 12px 0 2px;
      }

      .plan-price {
        font-size: 20px;
        font-weight: bold;
        color: #ff3333;
        margin-bottom: 2px;
      }

      .plan-discount {
        font-size: 12px;
        color: #999;
      }

      .desc {
        color: #999;
        font-size: 12px;
      }
    }
  }
}

.bottom-section {
  //   position: fixed;
  //   bottom: 0;
  //   left: 0;
  //   right: 0;
  background: white;
  //   padding: 16px;
  margin: 16px;
  border-top: 1px solid #e5e5e5;

  /* #ifdef H5 */
  bottom: 50px;
  /* H5环境下给tabBar留出空间 */
  /* #endif */

  .agreement {
    text-align: center;
    font-size: 12px;
    color: #999;
    margin-top: 12px;

    .link {
      color: #4285f4;
    }
  }
}

.app-section {
  background: white;
  border-radius: 12px;
  margin: 16px;
  overflow: hidden;

  .profile-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

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

    .item-label {
      font-size: 16px;
      color: #333;
      font-weight: 500;
    }

    .item-content {
      display: flex;
      align-items: center;
      gap: 8px;

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }

      .item-value {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.logout-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  border-top: 1px solid #e5e5e5;

  /* #ifdef H5 */
  bottom: 50px;
  /* H5环境下给tabBar留出空间 */
  /* #endif */
}
</style>