<template>
  <s-layout
    title="我的"
    tabbar="/pages/index/user"
    navbar="custom"
    :bgStyle="template.style?.background"
    :navbarStyle="template.style?.navbar"
    onShareAppMessage
    :showFloatButton="true"
  >
    <s-block v-for="(item, index) in template.data" :key="index" :styles="item.style">
      <s-block-item :type="item.type" :data="item.data" :styles="item.style" />
    </s-block>
  </s-layout>
</template>

<script setup>
  import { computed, onMounted } from 'vue';
  import { onShow, onPageScroll, onPullDownRefresh } from '@dcloudio/uni-app';
  import sheep from '@/sheep';

  // 隐藏原生tabBar
  uni.hideTabBar({
    fail: () => {},
  });

  const template = computed(() => sheep.$store('app').template.user);
  const isLogin = computed(() => sheep.$store('user').isLogin);

  // 建行生活自动登录(测试用)
  const testCcbLogin = async () => {
    // 检查是否已登录
    if (isLogin.value) {
      console.log('[User] 用户已登录,跳过建行测试登录');
      return;
    }

    // 测试用的固定加密参数
    const testCcbParam = {
      ccbParamSJ: "ZWVlRURYQndmYlpJOGpMRWRPRWEwRjVCZk82NjQxam1sL0l0d0NWMm9lUDdURld3MDRXamlNSGcva29COXBoZkVHKytHbHpSeUM3VkNESkUvTXYrOHFGYkhZWXo4d1NmanZuN0kvODF6TEo1OU9UbTZhS29MSUw3NjQzTGRKQWtrUHhyQi92TEVscWZzVWhlbVBpMVhHbHV2Z2RheXczK0VDL0J5N0g5aWNNR1ZPbFpWN0w4RHlNMGcrY09ZdWF2RUwzN2xheUNqUXdNV1dkR0F6RmlKL1V4b0NyMUhQM2R0Ui9ld0Vicll4eFdFeTFvUEthQ3Z5Vy9MajZxNFhQZTlrSjdTQVh1UjFyOWZGYjdMa003LzZpNnVSd2hWSnBCZ1h0WnRwU1VQb3UxSmh1UG00ejdleW9SUVMrOUJ2bW5VcVJBZnM0dy9RWEIwRlhwOGtLZW5rQ3RPK2xjdHlmTzE2cnU5UXJleHhmT2Y1ZXZwNjh3Qy9aTWVCTnoxZng4OXI2YWd5NUFWbmE2bzUwOVJES2tCZElhaG5JZll2eURPa2lyeTBqS0pBdGptSkRIRWFhcjUvaTlTVXkrbVdIbklmdDNsZE4rbWRnMWE0R0tzZmpqNUpDcll2VkFvQ0tBWklIc3FRL21admtrSDBqWEhYZ0ZrMjk2MWJ3eExSNGI=",
      cityid: "360100",
      CITYID: "360100"
    };

    console.log('[User] 开始建行测试登录...');

    // 显示加载提示
    uni.showLoading({
      title: '建行登录中...',
      mask: true
    });

    try {
      // 调用建行登录API
      const result = await sheep.$api.third.ccbLogin(testCcbParam);

      uni.hideLoading();

      if (result.code === 1) {
        console.log('[User] 登录接口返回成功,开始更新状态...');

        // 🔑 关键:使用setToken方法更新登录状态
        // 这会同时:
        // 1. 设置isLogin = true
        // 2. 保存token到storage
        // 3. 自动调用loginAfter()更新用户信息
        sheep.$store('user').setToken(result.data.token);

        // 也保存userInfo到storage(可选,setToken会自动获取)
        uni.setStorageSync('userInfo', result.data.user_info);

        console.log('[User] ✅ 建行测试登录成功');
        console.log('[User] 登录状态已更新:', sheep.$store('user').isLogin);

        // 显示欢迎提示
        uni.showToast({
          title: `欢迎 ${result.data.user_info?.nickname || ''}`,
          icon: 'success',
          duration: 2000
        });

        // 等待状态更新完成后刷新页面
        setTimeout(() => {
          console.log('[User] 刷新页面数据...');
          sheep.$store('user').updateUserData();
        }, 100);
      } else {
        throw new Error(result.msg || '登录失败');
      }
    } catch (error) {
      console.error('[User] ❌ 建行测试登录失败:', error);

      uni.hideLoading();

      uni.showModal({
        title: '登录失败',
        content: error.message || error.msg || '请检查网络连接',
        showCancel: false
      });
    }
  };

  // 页面挂载时自动登录(仅用于测试)
  onMounted(() => {
    // 延迟500ms执行,确保页面渲染完成
    setTimeout(() => {
      testCcbLogin();
    }, 500);
  });

  onShow(() => {
    sheep.$store('user').updateUserData();
  });

  onPullDownRefresh(() => {
    sheep.$store('user').updateUserData();
    setTimeout(function () {
      uni.stopPullDownRefresh();
    }, 800);
  });

  onPageScroll(() => {});
</script>

<style></style>
