import 'dart:io';

import 'package:clean/base/base_controller.dart';
import 'package:clean/data/consts/constants.dart';
import 'package:clean/dialog/privacy_dialog.dart';
import 'package:clean/main.dart';
import 'package:clean/module/main/main_view.dart';
import 'package:clean/module/splash/intro/intro_view.dart';
import 'package:flutter/Material.dart';
import 'package:get/get.dart';
import 'package:apple_pay/apple_pay.dart';

import '../../data/bean/payment_way.dart';
import '../../data/bean/store_item.dart';
import '../../data/consts/event_report_id.dart';
import '../../data/repositories/store_repository.dart';
import '../../dialog/loading_dialog.dart';
import '../../handler/event_handler.dart';
import '../../handler/photo_scan_handler.dart';

class SplashController extends BaseController {
  Animation<double>? animation;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    print('SplashController onReady');
    super.onReady();

    final isAgreePrivacy = isAgreePrivacyPolicy();
    if (isAgreePrivacy) {
      onAgreePrivacy();
      EventHandler.report(EventId.event_01000);
    } else {
      Future.delayed(const Duration(seconds: 2), () {
        privacyDialog(
          onAgree: () {
            setPrivacyPolicy(true);

            onAgreePrivacy();
            EventHandler.report(EventId.event_01002);
          },
          onDisagree: () {
            setPrivacyPolicy(false);
            exit(0);
          },
        );
      });
    }
  }

  // 已经同意隐私
  void onAgreePrivacy() async {
    await initAfterGrant();
    initStoreIndexData();




    PhotoScanHandler.handleAllPhotos();

    Future.delayed(const Duration(seconds: 2), () {
      if (isFirstIntro()) {
        IntroPage.start();
      } else {
        MainTabPage.start();
      }
    });
  }

  void initStoreIndexData() {
    // LoadingDialog.showLoading();
    final List<StoreItem> storeItems = <StoreItem>[];
    storeRepository.storeIndex().then((indexData) async {
      storeItems.addAll(indexData.items);
      var freeAppleId = "";
      for (var item in storeItems) {
        if (item.freeTrialName != null) {
          freeAppleId = item.appleGoodsId;
        }
      }
      var isFree = await ApplePay().check(freeAppleId);
      setGoodsFree(isFree);
      // LoadingDialog.hide();
    });
  }

  @override
  void onClose() {
    print('SplashController onClose');
    super.onClose();
  }
}
