<template>
  <view class="my-container">
    <view v-if="cfgStatus.showDetail" class="wheel-selector-fixed">
      <WheelSelector :options="wheelOptions" :selectedIndex="wheelSelectedIndex"
        :bgImg="$baseUrl + 'my/track/track.png'" :iconNormal="$baseUrl + 'my/track/icon_stage_nor.png'"
        :iconSelected="$baseUrl + 'my/track/icon_stage_sel.png'"
        @update:selectedIndex="(val) => (wheelSelectedIndex = val)" @change="handleWheelChange" />
    </view>
    <view class="bg-container"
      v-if="cfgStatus.isRegister" 
      :data-log="{
      xcxClick: '我的页面点击',
      pageName: '我的页面',
      buttonName: '个人信息修改',
    }" @click="handleUploadBackground">
      <image class="bg-img" :src="localBackgroundImg || babyInfo?.content?.backgroundImg || $baseUrl + 'my/default_bg.png'
        " mode="widthFix" lazy-load="false" binderror="" bindload="" />
      <image class="banner_cover" :src="$baseUrl + 'my/cover_white.png'" mode="aspectFill" />
    </view>

    <view v-if="!cfgStatus.isRegister" class="bg-container" @click="clickRegisterShield" />

    <!-- 用户信息区域 -->
    <view class="user-info" :style="{ 'min-height': cfgStatus.showDetail ? '343rpx' : '168rpx' }">
      <view class="user-header">
        <view class="avatar-container">
          <button 
            v-if="canChooseAvatar"
            class="avatar-wrapper" 
            :data-log="{
              xcxClick: '我的页面点击',
              pageName: '我的页面',
              buttonName: '个人信息修改',
            }" 
            open-type="chooseAvatar" 
            @chooseavatar="onChooseAvatar">
            <image class="avatar" :src="localAvatarUrl || babyInfo?.content?.babyAvatar ||
              $baseUrl + 'common/default_avatar.png'
              " mode="widthFix" />
          </button>
          <view 
            v-else
            class="avatar-wrapper" 
            :data-log="{
              xcxClick: '我的页面点击',
              pageName: '我的页面',
              buttonName: '个人信息修改',
            }" 
            @click="handleAvatarClick">
            <image class="avatar" :src="localAvatarUrl || babyInfo?.content?.babyAvatar ||
              $baseUrl + 'common/default_avatar.png'
              " mode="widthFix" />
          </view>
        </view>
        <button v-if="!cfgStatus.isRegister" type="primary" class="avatar-container" @click="clickRegisterShield" />
        <image class="avatar-modify" :src="$baseUrl + 'my/icon_modify.png'" mode="aspectFit" lazy-load="false" />

        <view class="user-detail">
          <view class="user-detail-nickname" :data-log="{
            xcxClick: '我的页面点击',
            pageName: '我的页面',
            buttonName: '宝宝信息切换',
          }">
            <text class="nickname" @click="handleEditProfile">{{
              babyInfo?.babyStage === 0
                ? "备孕"
                : babyInfo?.babyStage === 1
                  ? "孕中"
                  : babyInfo.babyName || "暂无昵称"
            }}</text>
            <view class="user-detail-nickname-icon-wrapper" @click="handleChangeBaby">
              <image class="user-detail-nickname-icon" :src="$baseUrl + 'registerLayer/icon_arrow_yellow.png'"
                mode="aspectFit" />
            </view>
          </view>
          <!-- 积分账户 -->
          <view class="integral-account" @click="handleEditProfile">
            <text class="integral-account-text"> 账号： </text>
            <text class="integral-account-value">
              {{ userStore.memberInfo?.mobile || '' }}</text>
          </view>

          <BabySwitcher v-if="showBabySwitcher" :show="showBabySwitcher" :babyList="babyInfo.allBabyBaseInfo || []"
            :addIcon="$baseUrl + 'my/baby_add_btn.png'" @close="showBabySwitcher = false" @select="onSelectBaby"
            @add="onAddBaby" />
        </view>

        <view class="integralContainer" @click="handleIntegralClick">
          <image class="integralIcon" src="https://course.feihe.com/momclub-picture/my/integralBg.png"
            mode="aspectFit" />
          <text class="integralText0">{{ points || "0" }}</text>
          <text class="integralText1">积分</text>
        </view>
      </view>
      <!-- user desc -->
      <view v-if="cfgStatus.showDetail" class="user-desc">
        <view class="desc-top">
          <text class="desc-title">宝宝变化</text>
          <text class="desc-age">
            {{ wheelOptions[wheelSelectedIndex]?.label }}
          </text>
        </view>

        <view class="desc-content">
          <text class="desc-text">{{
            wheelOptions[wheelSelectedIndex]?.desc.length > 46
              ? cfgStatus.openBabyCardDesc
                ? wheelOptions[wheelSelectedIndex]?.desc
                : wheelOptions[wheelSelectedIndex]?.desc.slice(0, 46) + "..."
              : wheelOptions[wheelSelectedIndex]?.desc
          }}
          </text>
          <text v-if="wheelOptions[wheelSelectedIndex]?.desc.length > 46" class="desc-more" @click="handleOpenClick">{{
            cfgStatus.openBabyCardDesc ? "点击收起" : "点击展开" }}</text>
        </view>
      </view>
    </view>

    <!-- 添加宝宝信息模块 -->
    <view class="add-baby-info-module"
      v-if="cfgStatus.isRegister && (!babyInfo?.allBabyBaseInfo || babyInfo.allBabyBaseInfo.length === 0)">
      <image class="add-baby-info-bg" :src="$baseUrl + 'homepage/Q3Res/addBabyInfoBg2.png'"></image>
      <view class="add-baby-info-btn-container">
        <image class="add-baby-info-btn" :src="$baseUrl + 'homepage/Q3Res/addBabyInfoBtn2.png'"
          @tap="handleAddBabyInfoClick"></image>
      </view>
    </view>

    <!-- 完成任务模块 -->
    <view class="task-module"
      v-if="cfgStatus.isRegister && (babyInfo?.allBabyBaseInfo && babyInfo.allBabyBaseInfo.length > 0)">
      <image class="task-guide-bg" :src="$baseUrl + 'homepage/Q3Res/my_taskGuideBg.png'"></image>
      <image class="task-do-btn" :src="$baseUrl + 'homepage/Q3Res/my_taskDoBtn.png'" @tap="handleTaskClick"></image>
    </view>

    <!-- 工具 -->
    <view class="tool-container" v-if="toolList?.length > 0">
      <text class="tool-title"> 工具 </text>
      <view class="tool-list">
        <template v-for="item in toolList" :key="item.title">
          <view v-if="!item.hidden" class="tool-item" @click="handleToolClick(item)">
            <image class="tool-icon" :src="item.bgUrl?.includes('http') ? item.bgUrl : $baseUrl + item.bgUrl"
              mode="aspectFit" />
            <!-- || item.title == '产检提醒' || item.title == '喂养记录' || item.title == '生长测评' -->
            <button v-if="(item.title == '医生问诊') && !cfgStatus.isRegister" class="tool-btn-register" type="primary"
              open-type="getPhoneNumber" @getphonenumber="getRealtimePhoneNumber" />
          </view>
        </template>
      </view>
    </view>

    <view class="vip-active-area" v-if="pageCfgStore?.contentCfg?.activeInfo?.length > 0">
      <text class="vip-title">精彩活动</text>
      <swiper class="vip-active-swiper" :indicator-dots="pageCfgStore?.contentCfg?.activeInfo?.length > 1"
        :autoplay="true" :circular="true" indicator-color="#dfddd9" indicator-active-color="#b27c1e"
        :indicator-top="32">
        <swiper-item v-for="(item, index) in pageCfgStore?.contentCfg?.activeInfo" :key="index">
          <image class="vip-active-img" :src="item?.bgUrl?.includes('http') ? item?.bgUrl : $baseUrl + `${item?.bgUrl}`"
            mode="aspectFit" @click="handleVipActiveClick(index, item)" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-container">
      <view class="menu-item" @click="navigateToWithLogin('/v3/orderList/orderList')" :data-log="{
        xcxClick: '我的页面点击',
        pageName: '我的页面',
        buttonName: '我的订单'
      }">
        <image class="menu-icon" :src="$baseUrl + 'homepage/Q3Res/myIcon_myOrder.png'" mode="aspectFit" />
        <text class="menu-title">我的订单</text>
        <image class="menu-arrow" :src="$baseUrl + 'homepage/Q3Res/rightArrowBtn.png'" mode="aspectFit" />
      </view>
      <view class="menu-item" @click="navigateToWithLogin('/v3/addressList/addressList')" :data-log="{
        xcxClick: '我的页面点击',
        pageName: '我的页面',
        buttonName: '收货地址管理'
      }">
        <image class="menu-icon" :src="$baseUrl + 'homepage/Q3Res/myIcon_address.png'" mode="aspectFit" />
        <text class="menu-title">收货地址管理</text>
        <image class="menu-arrow" :src="$baseUrl + 'homepage/Q3Res/rightArrowBtn.png'" mode="aspectFit" />
      </view>
      <view class="menu-item" @click="navigateToCouponWithLogin()" :data-log="{
        xcxClick: '我的页面点击',
        pageName: '我的页面',
        buttonName: '我的优惠券'
      }">
        <image class="menu-icon" :src="$baseUrl + 'homepage/Q3Res/myIcon_myCupon.png'" mode="aspectFit" />
        <text class="menu-title">我的优惠券</text>
        <image class="menu-arrow" :src="$baseUrl + 'homepage/Q3Res/rightArrowBtn.png'" mode="aspectFit" />
      </view>
      <view class="menu-item" @click="navigateToWithLogin('/v3/more/index')" :data-log="{
        xcxClick: '我的页面点击',
        pageName: '我的页面',
        buttonName: '更多'
      }">
        <image class="menu-icon" :src="$baseUrl + 'homepage/Q3Res/myIcon_more.png'" mode="aspectFit" />
        <text class="menu-title">更多</text>
        <image class="menu-arrow" :src="$baseUrl + 'homepage/Q3Res/rightArrowBtn.png'" mode="aspectFit" />
      </view>
    </view>

    <!-- 协议 -->
    <!-- <view class="protocol-container">
      <image :src="$baseUrl + 'my/protocol.png'" mode="aspectFit" />
      <view class="hot-member" :data-log="{
        xcxClick: '我的页面点击',
        pageName: '我的页面',
        buttonName: '会员规则',
      }" @click="handleHot" data-type="member"></view>
      <view class="hot-privacy" :data-log="{
        xcxClick: '我的页面点击',
        pageName: '我的页面',
        buttonName: '隐私协议',
      }" @click="handleHot" data-type="privacy"></view>
    </view> -->
  </view>
  <RegisterLayer v-model="showRegisterLayer" @confirm="onRegisterConfirm" @cancel="onRegisterCancel" />

  <!-- 生日弹窗  type  3 钻石、4 星光、5 星耀 -->
  <!-- <popup-shengri v-if="isTip" type="3" @close="isTip = false"></popup-shengri> -->


  <!-- 精选好卷弹窗 isUnlock  // 是否解锁 商品兑换券  type  1 黄金、2 铂金、3 钻石、4 星光、5 星耀 -->
  <!-- <popup-jingxuan v-if="isTip" type="1" isUnlock="true" @close="isTip = false"></popup-jingxuan> -->

  <!-- 新人礼券弹窗  type 1 黄金、2 铂金、3 钻石、4 星光、5 星耀-->
  <!-- <popup-xinren v-if="isTip" type="1" @close="isTip = false"></popup-xinren> -->

</template>

<style scoped>
/* 功能菜单样式 */
.menu-container {
  width: 702rpx;
  margin: 0 auto;
  margin-bottom: 100rpx;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eeeeee;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 35rpx;
}

.menu-title {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
}

.menu-arrow {
  width: 14rpx;
  height: 23rpx;
}

/* 任务模块样式 */
.task-module {
  width: 702rpx;
  margin: 0 auto;
  padding: 20rpx 0;
  position: relative;
}

.task-guide-bg {
  width: 698rpx;
  height: 96rpx;
  display: block;
}

.task-do-btn {
  width: 160rpx;
  height: 60rpx;
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  display: block;
}
</style>

<script setup>
import { ref, onMounted, getCurrentInstance, computed, watch } from "vue";
import RegisterLayer from "../components/RegisterLayer.vue";
import BabySwitcher from "../components/BabySwitcher.vue";
import WheelSelector from "../components/WheelSelector.vue";
import { useUserStore } from "@/stores/user";
import { usePageCfgStore } from "@/stores/pageCfg";
import { jump, JumpType } from "@/utils";
import { getHealthField } from "@/api/common";
import { hideLoading, showLoading } from "../utils";
import md from "../md.js";
import { onShow } from '@dcloudio/uni-app';
import { useIntegralStore } from "../stores/integral.js";
import { useGlobalStore } from "../stores/global.js";
import { uploadImage } from "../api/common.js";
import { saveBabyExtra } from "../api/user.js";

const { proxy } = getCurrentInstance();
const $baseUrl = proxy.$baseUrl;
const integralStore = useIntegralStore();
const globalStore = useGlobalStore();
const userStore = useUserStore();
const pageCfgStore = usePageCfgStore();
const cfgStatus = ref({
  openBabyCardDesc: false,
  showDetail: false,
  isRegister: true,
});

const wheelOptions = ref([]);
const wheelSelectedIndex = ref(0);

const toolList = computed(() => pageCfgStore?.toolList || []);

const babyInfo = computed(() => userStore?.babyInfo || {});

// 判断是否可以使用选择头像功能
const canChooseAvatar = computed(() => {
  return cfgStatus.value.isRegister && 
         userStore.babyInfo?.allBabyBaseInfo && 
         userStore.babyInfo?.allBabyBaseInfo?.length > 0;
});

const showRegisterLayer = ref(false);
const showBabySwitcher = ref(false);

const points = ref(0);

const babyId = ref(0);

// 本地头像 URL，用于临时显示上传后的头像
const localAvatarUrl = ref('');

// 本地背景图片 URL，用于临时显示上传后的背景图
const localBackgroundImg = ref('');

const handleTaskClick = async () => {
  // 添加点击埋点
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "做任务赚更多积分",
    componentContent: "去做任务"
  });

  // 检查登录状态
  if (!cfgStatus.value.isRegister) {
    // 未登录，跳转到登录注册页面
    jump({
      type: JumpType.INNER,
      url: "/pages/activity/register",
    });
    return;
  }

  // 已登录，正常执行任务逻辑
  await integralStore.getSigninAndTaskInfo(false);
  globalStore.showTaskPop(integralStore?.signinAndTaskInfo?.data?.taskTodo);
}

const handleHot = (e) => {
  const type = e.currentTarget.dataset.type;
  md.sensorLog(e);

  console.log("handleHot", type);
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "查看协议",
    componentContent: type === "member" ? "会员规则" : "隐私协议"
  })
  if (type === "member") {

    navigateTo("/pages/webview/webview?type=MEMBER_URL");
  } else if (type === "privacy") {
    navigateTo("/pages/webview/webview?type=PRIVACY_URL");
  }
};

function clickRegisterShield() {
  jump({
    type: JumpType.INNER,
    url: "/pages/activity/register",
  })
}

// 页面跳转
const navigateToCoupon = () => {
  const url = 'subPackages/shopMainProcess/coupons/couponList';
  const type = JumpType.MINI;
  const extra = {
    appId: 'wx4205ec55b793245e',	//星妈优选小程序
    extraData: {},
    envVersion: 'release',
    embedded: true,
  };

  jump({
    type: type,
    url: url,
    extra: extra
  });
};

// 需要登录的优惠券页面跳转
const navigateToCouponWithLogin = () => {
  // 添加点击埋点
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "我的优惠券"
  });

  // 检查登录状态
  if (!cfgStatus.value.isRegister) {
    // 未登录，跳转到登录注册页面
    jump({
      type: JumpType.INNER,
      url: "/pages/activity/register",
    });
    return;
  }

  // 已登录，正常跳转
  navigateToCoupon();
};

const navigateTo = (url) => {
  uni.navigateTo({
    url,
    animationDuration: 0,
    fail: (err) => {
      console.error("页面跳转失败:", err);
      uni.showToast({
        title: "页面跳转失败",
        icon: "none",
      });
    },
  });
};

// 需要登录的页面跳转
const navigateToWithLogin = (url) => {
  console.warn('navigateToWithLogin', url);
  console.warn('cfgStatus.value.isRegister', cfgStatus.value.isRegister);

  // 添加点击埋点 - 根据 URL 判断是哪个菜单项
  let componentContent = '';
  if (url.includes('/v3/orderList/orderList')) {
    componentContent = '我的订单';
  } else if (url.includes('/v3/addressList/addressList')) {
    componentContent = '收货地址管理';
  } else if (url.includes('/v3/more/index')) {
    componentContent = '更多';
  }

  if (componentContent) {
    md.sensorComponentLogTake({
      xcxComponentClick: "true",
      pageName: "我的页面",
      componentName: "拓展工具",
      componentContent: componentContent
    });
  }

  // 检查登录状态
  if (!cfgStatus.value.isRegister) {
    // 未登录，跳转到登录注册页面
    jump({
      type: JumpType.INNER,
      url: "/pages/activity/register",
    });
    return;
  }

  // 已登录，正常跳转
  navigateTo(url);
};

const handleToolClick = async (item) => {
  md.sensorLogTake({
    xcxClick: "我的页面点击",
    pageName: "我的页面",
    buttonName: item.title,
  });
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "工具",
    componentContent: item.title
  })
  // 跳转产检提醒页面判断

  // let listData = userStore.babyInfo ? userStore.babyInfo.allBabyBaseInfo : []

  if (item.title === "医生问诊") {
    if (!cfgStatus.value.isRegister) return;

    const res = await getHealthField();

    if (!res.success) {
      uni.showToast({
        title: "获取健康字段失败",
        icon: "none",
      });
      return;
    }

    const { sign, timestamp, appId, partnerUserId, env } = res.data;

    jump({
      type: JumpType.MINI,
      url: "/pages/partner/redirect",
      extra: {
        appId: "wx81ecfb5aa3fb512f",
        envVersion: env,
        extraData: {
          sign, // 参考 4.请求参数
          timestamp, // 参考 4.请求参数
          appId, // 参考 4.请求参数
          partnerUserId, // 参考 4.请求参数
          targetApp:
            "/h5/partner/shining-like-a-start/landing-free-consult?sysType=CRF",
        },
      },
    });
  }
  // 三个工具校验是否授权
  else if (item.title === "生长测评" || item.title === "喂养记录" || item.title === "产检提醒") {
    // if (!cfgStatus.value.isRegister) return;
    jump({ type: item.link.type, url: item.link.url });
  }
  else {
    jump({ type: item.link.type, url: item.link.url });
    // const extra = item.link.extra;
    // if(extra && extra.babyId){
    //   jump({ type: item.link.type, url: item.link.url+'?babyId='+extra.babyId});
    // }else{
    //   jump({ type: item.link.type, url: item.link.url});
    // }
  }
};

// 编辑个人资料
const handleEditProfile = (e) => {


  if (!userStore.userInfo ||
    JSON.stringify(userStore.userInfo) === "{}"
  ) {
    return;
  }

  md.sensorLog(e);
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "资料编辑"
  })

  // 检查登录状态
  if (!cfgStatus.value.isRegister) {
    // 未登录，跳转到登录注册页面
    jump({
      type: JumpType.INNER,
      url: "/pages/activity/register",
    });
    return;
  }

  if(!userStore.babyInfo?.allBabyBaseInfo || userStore.babyInfo?.allBabyBaseInfo?.length === 0) {
    navigateTo("/pages/person/person?type=add");
    return;
  }

  const type = userStore.babyInfo?.allBabyBaseInfo?.length == 0 ? "add" : "edit";
  babyId.value = userStore.babyInfo?.allBabyBaseInfo?.find(
    (item) => item.selected
  )?.id;

  if (type === "edit") {
    babyId.value = userStore.babyInfo?.allBabyBaseInfo.find(
      (item) => item.selected
      )?.id;
    navigateTo(`/pages/person/person?type=${type}&id=${babyId.value}`);
  } else {
    navigateTo(`/pages/person/person?type=${type}`);
  }

};

// 头像点击事件（当不满足选择头像条件时）
const handleAvatarClick = (e) => {
  md.sensorLog(e);
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "资料编辑"
  })
  // 检查登录状态
  if (!cfgStatus.value.isRegister) {
    // 未登录，跳转到登录注册页面
    jump({
      type: JumpType.INNER,
      url: "/pages/activity/register",
    });
    return;
  }

  if(!userStore.babyInfo?.allBabyBaseInfo || userStore.babyInfo?.allBabyBaseInfo?.length === 0) {
    navigateTo("/pages/person/person?type=add");
    return;
  }
  
};

// 选择头像
const onChooseAvatar = async (e) => {

  showLoading('上传中...');
  md.sensorLog(e);
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "资料编辑"
  })

  
  
  try {
    const fs = uni.getFileSystemManager();
    const base64 =
      "data:image/jpeg;base64," + fs.readFileSync(e.detail.avatarUrl, "base64");
    const res = await uploadImage(base64);
    
    if (res.success) {
      // 立即更新本地显示的头像
      localAvatarUrl.value = res.data.url;
      
      // 获取当前选中的宝宝信息并更新到服务器
      const selectedBaby = userStore.babyInfo?.allBabyBaseInfo?.find(
        (item) => item.selected
      );
      
      console.log("selectedBaby-===", selectedBaby);
      if (selectedBaby) {

        // const updateData = {
        //   id: selectedBaby.id,
        //   babyAvatar: res.data.url,
        // };
        
        // const updateRes = await updateBabyInfo(updateData);

        console.log("userStore.babyInfo?.content?.id====", userStore.babyInfo?.content);  
        const updateData = {
          id: userStore.babyInfo?.content?.id,
          babyAvatar: res.data.url
        }

        const updateRes = await saveBabyExtra(updateData);
        
        if (updateRes.success) {
          // 刷新用户信息
          await userStore.loadBabyInfo();
          // 清空本地临时头像，使用更新后的 babyInfo
          localAvatarUrl.value = '';
          
          uni.showToast({
            title: "头像更新成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: updateRes.message || "更新失败",
            icon: "none",
          });
        }
      } else {
        uni.showToast({
          title: "未找到宝宝信息",
          icon: "none",
        });
      }
    } else {
      uni.showToast({
        title: res.message,
        icon: "none",
      });
    }
  } catch (error) {
    console.error("头像选择失败:", error);
    uni.showToast({
      title: "头像选择失败",
      icon: "none",
    });
  } finally {
    hideLoading();
  }
};

const onRegisterConfirm = async () => {
  await pageCfgStore.fetchCfg();
  // 只调用一次initData，loadMemberInfo已在initData内部处理
  initData();
  showRegisterLayer.value = false;
};
const onRegisterCancel = () => {
  showRegisterLayer.value = false;
};

const handleWheelChange = (val) => {
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "月龄定位器",
    componentContent: babyInfo.value.babyStage == 2
      ? "月龄滑动切换-" + val
      : "孕周滑动切换-" + val
  });
}

const initExposure = () => {

  // 添加宝宝信息引导模块曝光埋点
  if (cfgStatus.value.isRegister && (!babyInfo.value?.allBabyBaseInfo || babyInfo.value?.allBabyBaseInfo?.length === 0)) {
    md.sensorComponentLogTake({
      xcxComponentExposure: "true",
      pageName: "我的页面",
      componentName: "添加宝宝信息引导",
      componentContent: "添加宝宝信息引导"
    });
  }

  // 添加做任务赚更多积分模块曝光埋点
  if (!cfgStatus.value.isRegister || (babyInfo.value?.allBabyBaseInfo && babyInfo.value?.allBabyBaseInfo?.length > 0)) {
    md.sensorComponentLogTake({
      xcxComponentExposure: "true",
      pageName: "我的页面",
      componentName: "做任务赚更多积分",
      componentContent: "去做任务"
    });
  }


  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "资料编辑"
  });

  toolList.value.forEach((item, index) => {
    md.sensorComponentLogTake({
      xcxComponentExposure: "true",
      pageName: "我的页面",
      componentName: "工具",
      componentContent: item.title
    });
  });
  if (pageCfgStore?.contentCfg?.activeInfo?.length > 0) {
    pageCfgStore.contentCfg.activeInfo.forEach((item, index) => {
      md.sensorComponentLogTake({
        xcxComponentExposure: "true",
        pageName: "我的页面",
        componentName: "精彩活动",
        componentContent: "精彩活动-" + item.title
      });
    });
  }
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "查看协议",
    componentContent: "会员规则"
  });
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "查看协议",
    componentContent: "隐私协议"
  });

  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "月龄定位器",
    componentContent: babyInfo.value.babyStage == 2 ? "月龄滑动切换" : "孕周滑动切换"
  });

  // 添加拓展工具菜单曝光埋点
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "我的订单"
  });
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "收货地址管理"
  });
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "我的优惠券"
  });
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "更多"
  });




}

onShow(async () => {
  console.log('onShow')
  await userStore.loadMemberInfo();
  points.value = userStore.memberInfo?.points;
  console.log('userStore.memberInfo=', userStore.memberInfo)


  // 添加拓展工具菜单曝光埋点
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "我的订单"
  });
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "收货地址管理"
  });
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "我的优惠券"
  });
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "拓展工具",
    componentContent: "更多"
  });

  console.warn("AAAAAAAA")
})

// 获取用户信息
const initData = async () => {
  // 确保加载会员信息以获取手机号
  await userStore.loadMemberInfo();
  points.value = userStore.memberInfo?.points;

  if (
    userStore?.userInfo?.memberId &&
    userStore?.userInfo?.memberId == "not_login"
  ) {
    cfgStatus.value.isRegister = false;
    cfgStatus.value.showDetail = false;
    return;
  }
  const __showDetail = [1, 2].includes(babyInfo.value.babyStage);

  cfgStatus.value.isRegister = true;
  // 已出生或孕中显示
  cfgStatus.value.showDetail = __showDetail;



  if (__showDetail) {
    wheelOptions.value =
      babyInfo.value.babyStage == 2
        ? pageCfgStore.wheelOptionsYL
        : pageCfgStore.wheelOptionsYZ;
    const index = wheelOptions.value.findIndex(
      (item) => item.label == babyInfo.value.babyAge
    );
    wheelSelectedIndex.value = index > 0 ? index : 0;
  }
};

const handleIntegralClick = () => {
  md.sensorLogTake({
    xcxClick: "我的页面-首屏页面点击",
    pageName: "我的页面-首屏",
    buttonName: "积分明细",
  });
  const urlStr = 'https://mom.feihe.com/member/mine/newPointDetail?crmId={crmid}&appCode=XMH';
  const url = urlStr.replace("{crmid}", userStore.babyInfo?.memberId);
  console.log('积分明细链接：==', url)

  jump({
    type: 3,
    url: url
  })
}

const getRealtimePhoneNumber = async (e) => {
  console.log("获取手机号码", e);

  if (e.detail.errMsg !== "getPhoneNumber:ok") {
    uni.showToast({
      title: "请授权使用手机号",
      icon: "none",
    });
    return;
  }
  await userStore.phoneCallback(e.detail, async () => {
    // 简化回调，避免重复调用接口
    showLoading();
    await pageCfgStore.fetchCfg();
    // 只调用一次initData，loadMemberInfo已在initData内部处理
    initData();
    hideLoading();
  });
};

const handleChangeBaby = (e) => {
  if (!cfgStatus.value.isRegister) {
    return;
  }

  md.sensorLog(e);
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "展开"
  })
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "新增"
  })
  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "状态切换"
  })

  showBabySwitcher.value = true;
};




async function onSelectBaby(baby) {
  // 处理宝宝切换逻辑
  showBabySwitcher.value = false;

  showLoading();
  await userStore.changeBabySelected(baby.id);

  hideLoading();
  console.log("onSelectBaby", baby);
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "状态切换"
  })
}

function handleAddBabyInfoClick() {
  // 添加点击埋点
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "添加宝宝信息引导",
    componentContent: "添加宝宝信息引导"
  });
  // 显示RegisterLayer弹窗
  showRegisterLayer.value = true;
}

function onAddBaby() {
  md.sensorLogTake({
    xcxClick: "我的页面点击",
    pageName: "我的页面",
    buttonName: "新增入口",
  });
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "新增"
  })

  // 跳转到新增宝宝页面
  showBabySwitcher.value = false;
  navigateTo("/pages/person/person?type=add");
}

const handleOpenClick = () => {
  md.sensorLogTake({
    xcxClick: "我的页面点击",
    pageName: "我的页面",
    buttonName: cfgStatus.value.openBabyCardDesc ? "收起" : "展开",
  });
  cfgStatus.value.openBabyCardDesc = !cfgStatus.value.openBabyCardDesc;
};

// 上传背景图片
const handleUploadBackground = async (e) => {
  md.sensorLog(e);


  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "资料编辑",
    componentContent: "资料编辑"
  })

  // 检查登录状态
  if (!cfgStatus.value.isRegister) {
    // 未登录，跳转到登录注册页面
    jump({
      type: JumpType.INNER,
      url: "/pages/activity/register",
    });
    return;
  }

  if(!userStore.babyInfo?.allBabyBaseInfo || userStore.babyInfo?.allBabyBaseInfo?.length === 0) {
    navigateTo("/pages/person/person?type=add");
    return;
  }

  
  // 唤起图片选择器
  uni.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      showLoading('上传中...');
      try {
        const tempFilePath = res.tempFilePaths[0];
        const fs = uni.getFileSystemManager();
        const base64 =
          "data:image/jpeg;base64," + fs.readFileSync(tempFilePath, "base64");

        const uploadRes = await uploadImage(base64);

        if (uploadRes.success) {
          // 立即更新本地显示的背景图
          localBackgroundImg.value = uploadRes.data.url;
          
          // 获取当前选中的宝宝信息并更新到服务器
          const selectedBaby = userStore.babyInfo?.allBabyBaseInfo?.find(
            (item) => item.selected
          );
          
          if (selectedBaby) {
            // const updateData = {
            //   id: selectedBaby.id,
            //   backgroundImg: uploadRes.data.url,
            // };
            
            // const updateRes = await updateBabyInfo(updateData);
            console.log("userStore.babyInfo?.content?.id====", userStore.babyInfo);  
            const updateData = {
              id:userStore.babyInfo?.content?.id,
              backgroundImg: uploadRes.data.url
            }

            const updateRes = await saveBabyExtra(updateData);
            
            if (updateRes.success) {
              // 刷新用户信息
              await userStore.loadBabyInfo();
              // 清空本地临时背景图，使用更新后的 babyInfo
              localBackgroundImg.value = '';
              
              uni.showToast({
                title: "背景更新成功",
                icon: "success",
              });
            } else {
              uni.showToast({
                title: updateRes.message || "更新失败",
                icon: "none",
              });
            }
          } else {
            uni.showToast({
              title: "未找到宝宝信息",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: uploadRes.message || "上传失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("背景图片上传失败:", error);
        uni.showToast({
          title: "背景图片上传失败",
          icon: "none",
        });
      } finally {
        hideLoading();
      }
    },
    fail: (err) => {
      console.error("选择图片失败:", err);
      uni.showToast({
        title: "选择图片失败",
        icon: "none",
      });
    }
  });
};

// 页面加载
onMounted(async () => {
  md.sensorLogTake({
    xcxPage: "我的页面浏览",
    pageName: "我的页面",
  });
  showLoading();
  await userStore.loadMemberInfo();
  points.value = userStore.memberInfo?.points;

  await pageCfgStore.fetchCfg();

  console.log("pageCfgStore.contentCfg====", pageCfgStore.contentCfg);
  initData();
  initExposure();



  hideLoading();


  babyId.value = userStore.babyInfo?.allBabyBaseInfo?.find(
    (item) => item.selected
  )?.id;

  // const a = {
  //   "bgUrl": "my/shengzhangTools.png",
  //   "desc": "生长测评",
  //   "link": {
  //     "type": 1,
  //     "url": "/pages/shengzhangTools/shengzhangTools"
  //   },
  //   "title": "生长测评"
  // }
  // const b = {
  //   "bgUrl": "my/icon_feed.png",
  //   "desc": "喂养记录",
  //   "link": {
  //     "extra": { babyId: babyId.value },
  //     "type": 1,
  //     "url": "/pages/feedingIndex/feedingIndex"
  //   },
  //   "title": "喂养记录"
  // }
  // const c = {
  //   "bgUrl": "my/icon_remind.png",
  //   "desc": "产检提醒",
  //   "link": {
  //     "extra": { babyId: babyId.value },
  //     "type": 1,
  //     "url": "/pages/postnatalCheckUp/postnatalCheckUp"
  //   },
  //   "title": "产检提醒"
  // }

  // toolList.value.push(a);
  // toolList.value.push(b);
  // toolList.value.push(c);
});

watch([() => userStore.userInfo, () => userStore.babyInfo], () => {
  console.log("userInfo/babyInfo变化", userStore.userInfo, userStore.babyInfo);
  initData();
  babyId.value = userStore.babyInfo?.allBabyBaseInfo?.find(
    (item) => item.selected
  )?.id;
});

watch(() => userStore.memberInfo, () => {
  console.log('userStore.memberInfo变化', userStore.memberInfo)
  points.value = userStore.memberInfo?.points;
})

//会员活动点击事件
const handleVipActiveClick = (index, item) => {
  let buttonName = '';
  switch (index) {
    case 0:
      buttonName = '第一张焦点图';
      break;
    case 1:
      buttonName = '第二张焦点图';
      break;
  }

  md.sensorLogTake({
    xcxClick: "我的页面点击",
    pageName: "我的页面",
    buttonName: buttonName,
  });
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "我的页面",
    componentName: "精彩活动",
    componentContent: "精彩活动-" + item.title
  })
  const url = item?.link.url;
  const type = item?.link.type;
  const extra = item?.link.extra;

  jump({
    type: type,
    url: url,
    extra: extra
  })
}

// 定义页面配置
defineExpose({});
</script>
<style lang="less" scoped>
@import "@/common.less";

.my-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
  overflow: hidden;

  .wheel-selector-fixed {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 10;
  }

  .phone-button {
    position: absolute;
    z-index: 3;
    width: 686rpx;
    height: 180rpx;
    top: 676rpx;
    left: 50%;
    transform: translateX(-50%);
    border: none;
    background: transparent;
    opacity: 0;
  }

  .bg-container {
    width: 750rpx;
    height: 840rpx;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 0;
    overflow: hidden;

    .bg-img {
      width: 100%;
      height: 100%;
      display: block;
    }

    .banner_cover {
      width: 100%;
      height: 239rpx;
      position: absolute;
      bottom: -10rpx;
      left: 0;
      z-index: 1;
      display: block;
    }
  }

  .user-info {
    background-color: @color-white-soft;

    width: 686rpx;
    min-height: 343rpx;
    box-sizing: border-box;
    border-radius: 32rpx;
    position: relative;
    margin: 0 auto;
    margin-top: 676rpx;
    display: flex;

    .user-header {
      display: flex;
      align-items: center;
      position: absolute;
      width: 100%;

      .avatar-container {
        width: 100rpx;
        height: 100rpx;
        background-color: #f6f6f6;
        overflow: hidden;
        border-radius: 50%;

        position: absolute;
        left: 32rpx;
        top: 32rpx;
        z-index: 1;

        .avatar-wrapper {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0;
          border: none;
          background: transparent;
          width: 100%;
          height: 100%;
          cursor: pointer;
        }

        .avatar-wrapper::after {
          border: none !important;
          outline: none !important;
        }

        .avatar {
          width: 100%;
          height: 100%;
          display: block;
        }
      }

      .avatar-modify {
        width: 64rpx;
        height: 64rpx;
        position: absolute;
        left: 80rpx;
        top: 84rpx;
        z-index: 1;
        display: block;
        pointer-events: none;
      }

      .user-detail {
        display: flex;
        flex-direction: column;

        position: absolute;
        left: 148rpx;
        top: 48rpx;
        z-index: 1;

        .user-detail-nickname {
          display: flex;
          align-items: center;
        }

        .user-detail-nickname-icon-wrapper {
          display: flex;
          align-items: center;
          justify-content: center;
          // padding: 10rpx;
          margin-left: 10rpx;
          margin-top: -10rpx;
          min-width: 40rpx;
          min-height: 40rpx;
        }

        .user-detail-nickname-icon {
          width: 20rpx;
          height: 12rpx;
          display: block;
        }

        .nickname {
          font-size: 32rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 10rpx;
        }

        .integral-account {
          display: flex;
          font-size: 24rpx;
          color: #1d1e25;

          .integral-account-text {
            color: #1d1e25;
          }
        }

      }


      .integralContainer {
        position: absolute;
        top: 0rpx;
        right: 0rpx;
        width: 226rpx;
        height: 166rpx;

        .integralIcon {
          position: absolute;
          width: 226rpx;
          height: 166rpx;
          right: 0rpx;
        }

        .integralText0 {
          position: absolute;
          font-size: 24rpx;
          color: #1d1e25;
          top: 45rpx;
          right: 0rpx;
          width: 167rpx;
          text-align: center;
        }

        .integralText1 {
          position: absolute;
          font-size: 24rpx;
          color: #1d1e25;
          width: 167rpx;
          text-align: center;
          right: 0rpx;
          top: 81rpx;

        }
      }

      .edit-btn {
        image {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }

    .user-stats {
      display: flex;
      justify-content: space-around;

      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;

        .num {
          font-size: 36rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 8rpx;
        }

        .label {
          font-size: 24rpx;
          color: #666;
        }
      }
    }

    .user-desc {
      width: 100%;
      height: calc(100% - 161rpx);
      background-color: #fff;
      border-radius: 32rpx;
      padding: 32rpx 30rpx;
      box-sizing: border-box;
      margin-top: 180rpx;

      .desc-top {
        display: flex;
        align-items: center;
      }

      .desc-title {
        font-size: 32rpx;
        font-weight: 500;
        color: @color-black-deep;
      }

      .desc-age {
        font-size: 24rpx;
        color: @color-gold-cover;
        background-color: #fef7f2;
        padding: 7rpx 10rpx;
        border-radius: 10rpx;
        margin-left: 8rpx;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .desc-text {
        font-size: 24rpx;
        line-height: 34rpx;
        display: inline-block;
      }

      .desc-more {
        font-size: 24rpx;
        color: @color-gold-cover;
        line-height: 34rpx;
        display: block;

        text-align: right;
      }

      .desc-content {
        margin-top: 32rpx;
        position: relative;
      }
    }
  }

  .user-info-min {
    min-height: 180rpx;
  }

  .add-baby-info-module {
    width: 698rpx;
    height: 96rpx;
    position: relative;
    margin: 0 auto;
    margin-top: 30rpx;

    overflow: hidden;

    .add-baby-info-bg {
      width: 100%;
      height: 100%;
      display: block;
    }

    .add-baby-info-btn-container {
      position: absolute;
      bottom: 18rpx;
      right: 40rpx;

      .add-baby-info-btn {
        width: 160rpx;
        height: 60rpx;
        display: block;

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }

  .tool-container {
    margin: 0 auto;
    margin-top: 48rpx;
    width: 686rpx;

    .tool-title {
      font-size: 32rpx;
      font-weight: bolder;
      color: @color-black-deep;
      margin-left: 21rpx;
    }

    .tool-list {
      display: flex;
      flex-wrap: wrap;

      margin-top: 20rpx;

      .tool-item {
        width: 152rpx;
        height: 152rpx;
        margin-left: 26rpx;
        margin-bottom: 24rpx;
        position: relative;

        .tool-icon {
          width: 100%;
          height: 100%;
          border-radius: 24rpx;
          display: block;
        }

        &:nth-child(4n + 1) {
          margin-left: 0;
        }

        .tool-btn-register {
          position: absolute;
          width: 152rpx;
          height: 152rpx;
          top: 0;
          left: 0;
          opacity: 0;
        }
      }
    }
  }

  .vip-active-area {
    margin-left: 28rpx;
    margin-top: 60rpx;

    .vip-title {
      margin-left: 20rpx;
      font-weight: bolder;
    }

    .vip-active-swiper {
      width: 692rpx;
      height: 204rpx;
      flex-shrink: 0;
      margin-top: 30rpx;
      margin-bottom: 100rpx;

      .vip-active-img {
        width: 100%;
        height: 100%;
        border-radius: 32rpx;
      }
    }
  }

  .protocol-container {
    width: 360rpx;
    height: 25rpx;
    margin: 8rpx auto 130rpx;
    position: relative;

    image {
      width: 100%;
      height: 100%;
      display: block;
    }

    .hot-member {
      width: 142rpx;
      height: 50rpx;
      display: block;
      position: absolute;
      left: 53rpx;
      top: -15rpx;
    }

    .hot-privacy {
      width: 147rpx;
      height: 50rpx;
      display: block;
      position: absolute;
      left: 210rpx;
      top: -15rpx;
    }
  }
}
</style>