import { Logger } from '@ohos/common';
import { KVStore } from '@ohos/common/src/main/ets/utils/KVStore';
import {
  DEVICE_OAID,
  IS_AGREE_AGREEMENT,
  IS_KV_STORE_INIT_FINISHED,
  TOKEN,
  USER_INFO,
  USER_PROFILE } from '@ohos/common/src/main/ets/constants/AppConstants';
import { AgreementDialog } from '@ohos/common/src/main/ets/dialog/AgreementDialog';
import emitter from '@ohos.events.emitter';
import { EVT_KV_INIT_DONE } from '@ohos/common/src/main/ets/constants/EventConstants';
import { UserService } from '../viewmodel/UserService';
import { getOAID } from '@ohos/common/src/main/ets/utils/AppUtils';
import { routerIndex, routerLogin } from '@ohos/common/src/main/ets/router/RouterManager';
import { CommonService } from '@ohos/common/src/main/ets/viewmodel/CommonService';
import { UserProfile } from '@ohos/common/src/main/ets/viewmodel/DataBean';
import { registerUniProvider } from '@dcloudio/uni-app-runtime';
import { UniPaymentAlipayProviderImpl } from '@uni_modules/uni-payment-alipay';

/**
 * 启动页 - Splash Screen
 * 显示应用Logo和加载动画，1秒后自动跳转到主页面
 * 为了给用户更好的体验，采用“谁快听谁的，但有保底时间”的策略。
 */
@Entry
@Component
struct SplashScreenPage {
  @State countdown: number = 1;  // 修改为5秒倒计时
  private timerId: number = -1;
  @State canSkip: boolean = false;
  @State hasAgreed?: boolean = undefined;
  @State isShowCountDown: boolean = false;

  // 用于存储请求到的配置或错误状态
  private isNavigated: boolean = false;

  dialogController: CustomDialogController = new CustomDialogController({
    builder: AgreementDialog({
      confirm: () => {
        // --- 场景1：点击同意弹窗后触发 ---
        KVStore.getInstance().put(IS_AGREE_AGREEMENT, 'true').then(() => {
          this.agreeRun()
        });
      }
    }),
    autoCancel: false,
    onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
      if (dismissDialogAction.reason === DismissReason.PRESS_BACK ||
        dismissDialogAction.reason === DismissReason.TOUCH_OUTSIDE) {
        Logger.info('Rabbit_SplashScreenPage', '必须同意协议才能进入');
      }
    },
    alignment: DialogAlignment.Center,
    customStyle: true
  })

  async loadUserConfig() {
    try {
      // 1. 获取系统基本信息 (同步)，获取服务器时间，并与本地时间同步
      await UserService.getSystemTime()
      // 2. 等待时间同步完成后发，起用户配置请求(数据会持久化到本地)
      const profile = await CommonService.getUserProfile();
      // 3. 等待用户配置完成后，发起用户信息请求(数据会持久化到本地)
      await CommonService.getUserInfo()
      Logger.info('Rabbit_SplashScreenPage', `配置获取成功----> token:${profile.token} name:${profile.name}`);
    } catch (err) {
      Logger.error('Rabbit_SplashScreenPage', '请求失败，请检查参数或者接口返回数据:' + err);
    } finally {
      // 如果希望请求一回来就跳转（不等待5秒完），立即执行跳转：
      // this.navigateToMain();
    }
  }


  aboutToAppear() {
    Logger.info('Rabbit_SplashScreenPage', '启动页加载完成');
    if(AppStorage.get<boolean>(IS_KV_STORE_INIT_FINISHED)){
      this.showAgreement()
    }else{
      //等待KVStore初始化完成事件（KVStore初始化完成，执行获取协议，如同意执行跳转，否则弹协议窗）
      emitter.once({ eventId: EVT_KV_INIT_DONE }, () => {
        this.showAgreement()
      });
    }
  }

  showAgreement() {
    KVStore.getInstance().get(IS_AGREE_AGREEMENT, '').then((val: string) => {
      Logger.info('Rabbit_SplashScreenPage', val === 'true'?'已同意协议，计时开始...':'未同意协议，需要弹窗展示协议');

      if (val === 'true') {
        // ---已同意过，直接进入 ---
        this.agreeRun()
      } else {
        // 未同意，显示弹窗
        this.hasAgreed = false;
        this.dialogController.open();
      }
    });
  }

  // 同意协议后执行
  agreeRun() {
    getOAID().then((oaid: string) => {
      AppStorage.setOrCreate<string>(DEVICE_OAID, oaid);
    });

    this.hasAgreed = true;
    this.startFlow();
  }

  /**
   * 统一启动流程：延迟显示跳过按钮 + 开启倒计时
   */
  startFlow(): void {
    // 延迟500ms后显示跳过按钮
    setTimeout(() => {
      this.canSkip = true;
    }, 500);

    // 启动倒计时定时器
    this.startCountdown();
    this.loadUserConfig();
    registerUniProvider("payment", "alipay", new UniPaymentAlipayProviderImpl());
  }

  startCountdown(): void {
    this.clearTimer(); // 防御性清除，避免重复启动
    this.timerId = setInterval(() => {
      this.countdown -= 1;
      if (this.countdown <= 0) {
        this.navigateToMain();
      }
    }, 1000); // 注意：秒级倒计时应使用1000ms，500ms会导致2.5秒就结束
  }

  clearTimer(): void {
    if (this.timerId !== -1) {
      clearInterval(this.timerId);
      this.timerId = -1;
    }
  }

  navigateToMain(): void {
    if (this.isNavigated) return; // 防止重复跳转
    this.isNavigated = true;
    this.clearTimer();

    const profile = AppStorage.get<UserProfile>(USER_PROFILE);
    KVStore.getInstance().get(TOKEN, '').then((accountToken: string) => {
      //无论是游客还是登录用户都应该拥有自己的token，如果没有跳转到登录页处理
      if (profile && (profile.token !== '' || accountToken !== '')) {
        // if (profile) {
        KVStore.getInstance().get(USER_INFO, '{}').then(userJson => {
          if(userJson === '{}'){
            CommonService.getUserInfo()
          }
        })
        // 只有在 5 秒内请求成功并拿到了 token 才去首页
        routerIndex()
      } else {
        // 请求超时、失败、或还没回来的兜底方案：去登录页
        routerLogin('splash',true)
      }
    })
  }

  aboutToDisappear() {
    this.clearTimer();
  }

  // 跳过按钮点击事件
  onSkipClick() {
    if (this.canSkip) {
      this.navigateToMain();
    }
  }

  build() {
    Stack() {
      // 1. 背景图
      Image($r('app.media.ic_splash_mask'))
        .width('100%')
        .height('100%')
        .objectFit(ImageFit.Cover)

      // 2. 居中的 Logo
      Column() {
        Image($r('app.media.ic_splash_logo'))
          .width('151vp')
          .height('58vp')
      }
      .width('100%')
      .height('100%')
      .justifyContent(FlexAlign.Center)

      // 3. 右上角倒计时与跳过按钮
      if (this.hasAgreed === true && this.isShowCountDown) { // 只有同意协议后才显示
        Row() {
          Text(`${this.countdown}s | 跳过`)
            .fontSize('14fp')
            .fontColor(Color.White)
            .fontWeight(FontWeight.Medium)
        }
        .position({ x: '100%', y: 0 }) // 定位到右上角
        .markAnchor({ x: '100%', y: 0 }) // 锚点修正
        .margin({ top: px2vp(AppStorage.get<number>('statusBarHeight') ?? 0) + 20, right: 20 }) // 避让状态栏
        .padding({ left: 12, right: 12, top: 6, bottom: 6 })
        .backgroundColor('#40000000') // 40% 不透明度的黑色背景
        .borderRadius(15) // 圆角胶囊形状
        .visibility(this.canSkip ? Visibility.Visible : Visibility.Hidden) // 控制500ms后显示
        .onClick(() => {
          this.onSkipClick();
        })
      }
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#FFFFFF')
  }

}