import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:wallpaperx/common/components/dialog/remind_dialog.dart';
import 'package:wallpaperx/common/components/easy_loading.dart';
import 'package:wallpaperx/common/utils/local_path_util.dart';
import 'package:wallpaperx/common/utils/shared_util.dart';
import 'package:wallpaperx/entity/userinfo_model.dart';
import 'package:wallpaperx/generated/assets.dart';
import 'package:wallpaperx/page/home/home_controller.dart';
import 'package:wallpaperx/res/values/strings.dart';
import 'package:wallpaperx/routes/app_pages.dart';
import 'package:share_plus/share_plus.dart';

class SettingsController extends GetxController {
  final privacyUrlAndroid = 'https://visualwallpaper.mystrikingly.com/privacy';
  final termsUrlAndroid = 'https://visualwallpaper.mystrikingly.com/terms';

  final privacyUrlIOS = 'https://visualwallpaper.mystrikingly.com/privacy';
  final termsUrlIOS = 'https://visualwallpaper.mystrikingly.com/terms';

  final options = [
    'AI preferences',
    'Privacy Policy',
    'Terms of Service',
    'Feedback',
    'About',
    'Share',
    "log Out",
    "Delete Account"
  ];

  late bool shareIsOpen = false;

  ///email输入文本
  final TextEditingController feedbackTextController = TextEditingController();

  /// 输入框焦点
  FocusNode focusNode = FocusNode();

  HomeController homeController = Get.find<HomeController>();

  UserinfoModel userinfo = UserinfoModel();

  Timer? _timer;

  void settingOptionOnTap(int index, {String? type}) async {
    if (index == 0) {
      Get.toNamed(AppPages.aiManager);
    }
    if (index == 1) {
      Get.toNamed(AppPages.privacyPolicy, arguments: {
        'title': options[index],
        'url': Platform.isIOS ? privacyUrlIOS : privacyUrlAndroid,
      });
    }
    if (index == 2) {
      Get.toNamed(AppPages.termsOfService, arguments: {
        'title': options[index],
        'url': Platform.isIOS ? termsUrlIOS : termsUrlAndroid,
      });
    }
    if (index == 3) {
      Get.toNamed(AppPages.feedBack);
    }
    if (index == 4) {
      Get.toNamed(AppPages.about);
    }
    if (index == 5) {
      if (!shareIsOpen) {
        shareIsOpen = !shareIsOpen;
        Share.shareXFiles(
          [await getImageFileFromAssets(Assets.iconIconApp)],
          text: appName,
        ).then((value) {
          shareIsOpen = !shareIsOpen;
        });
      }
    }
    var loginAccount = UPCache.getInstance().get("loginAccount");
    if (index == 6) {
      if (loginAccount != null) {
        Get.dialog(
          barrierDismissible: false,
          RemindDialog(
            content: 'Are you sure you want to logout?',
            confirmOnTap: () {
              loading(show: true);
              _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
                UPCache.getInstance().remove("loginAccount");
                homeController.userinfo = UserinfoModel();
                update(["userinfo"]);
                dismiss(dismiss: true);
                _stopTimer();
              });
            },
          ),
        );
      } else {
        toast("not login");
      }
    }
    if (index == 7) {
      if (loginAccount != null) {
        Get.dialog(
          barrierDismissible: false,
          RemindDialog(
            content: 'Are you sure you want to write off the account?',
            confirmOnTap: () {
              loading(show: true);
              _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
                UPCache.getInstance().remove(loginAccount);
                UPCache.getInstance().remove("loginAccount");
                homeController.userinfo = UserinfoModel();
                update(["userinfo"]);
                dismiss(dismiss: true);
                _stopTimer();
              });
            },
          ),
        );
      } else {
        toast("not login");
      }
    }
  }

  void toEdit({UserinfoModel? userinfo}) {
    if (homeController.userinfo.username == null) {
      Get.toNamed(AppPages.login);
    } else {
      Get.toNamed(AppPages.editUserinfo, arguments: {
        'title': 'Edit',
      });
    }
  }

  /// 获取用户信息
  void loadUserInfo({String? userID}) {
    var loginAccount = UPCache.getInstance().get("loginAccount");
    var map = UPCache.getInstance().getJson(loginAccount ?? "");
    if (map != null) {
      userinfo = UserinfoModel.fromJson(map);
    }
  }

  Future<XFile> getImageFileFromAssets(String path) async {
    final byteData = await rootBundle.load(path);
    final file = File('${(await LocalPathUtil.getTemporaryPath()).path}/$path');
    await file.create(recursive: true);
    await file.writeAsBytes(byteData.buffer
        .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
    return XFile(file.path);
  }

  /// 停止定时器
  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
  }
}
