import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:cs_resources/theme/theme_config.dart';
import 'package:cs_resources/theme/theme_notifier.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:plugin_basic/basic_export.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/cache/local_cache_manager.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/directory/directory_util.dart';
import 'package:plugin_platform/engine/image/image_preview.dart';
import 'package:plugin_platform/engine/media/image_picker_utils.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/sp/sp_util.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/picker/date_picker_util.dart';
import 'package:widgets/picker/option_pick_util.dart';
import 'package:plugin_platform/platform_export.dart';


class DemoPage extends HookConsumerWidget {
  const DemoPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final _userService = UserConfigService.getInstance(ref: ref);
    final _userConfig = UserConfigService.getState(ref: ref);
    Log.d("VisitorPage - build 了");

    return Scaffold(
      appBar: AppBar(title: Text("Visitor"),systemOverlayStyle: ThemeConfig.getSystemUiOverlayStyleByTheme(context)),
      backgroundColor: context.appColors.backgroundDefault,
      body: Center(
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Text("当前的用户:${_userConfig.userName}"),
                ElevatedButton(
                  onPressed: () {
                    _userService.setUserInfo("张三");
                  },
                  child: Text(
                    '修改用户信息',
                  ),
                ),
              ],
            ).marginOnly(top: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {
                   // fetchServerTime();
                  },
                  child: Text('网络请求'),
                ),
                ElevatedButton(
                  onPressed: () {
                    ToastEngine.show("这是一个吐司气泡");
                  },
                  child: Text('吐司/气泡'),
                ),
                ElevatedButton(
                  onPressed: () async {
                    NotifyEngine.showSuccess("操作成功");
                    await Future.delayed(Duration(seconds: 3));
                    NotifyEngine.showFailure("操作失败");
                    await Future.delayed(Duration(seconds: 3));
                    NotifyEngine.showError("操作错误");
                  },
                  child: Text('成功/失败通知'),
                ),
              ],
            ).marginOnly(top: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {
                    DialogEngine.show(
                        widget: AppDefaultDialog(
                          //这种布局自己自定义去
                          title: "提示",
                          message: "默认的弹窗，自定义的弹窗自己画去",
                          confirmAction: () {
                            ToastEngine.show("点击了确定");
                          },
                        ));
                  },
                  child: Text('弹窗'),
                ),
                ElevatedButton(
                  onPressed: () {
                    DateTime dateTime = DateTime.now();
                    DatePickerUtil.showCupertinoDatePicker(
                      mode: CupertinoDatePickerMode.date,
                      selectedDateTime: dateTime,
                      onDateTimeChanged: (date) {
                        dateTime = date;
                      },
                      title: "选择日期",
                    );
                  },
                  child: Text('时间选择'),
                ),
                ElevatedButton(
                  onPressed: () {
                    OptionPickerUtil.showCupertinoOptionPicker(
                      items: ["前天", "昨天", "今天", "明天", "后天"],
                      initialSelectIndex: 0,
                      onPickerChanged: (_, index) {
                        ToastEngine.show("选中的索引为：$index");
                      },
                    );
                  },
                  child: Text('条件选择'),
                ),
              ],
            ).marginOnly(top: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {
                    ImagePickerUtils().show(context, (filePath) {
                      ToastEngine.show("图片的路径为：$filePath");
                    });
                  },
                  child: Text('相册/相册'),
                ),
                ElevatedButton(
                  onPressed: () async {
                    final PermissionStatus permissionStatus = await Permission.phone.request();
                    if (permissionStatus.isGranted) {
                      final Uri launchUri = Uri(
                        scheme: 'tel',
                        path: "+8618571458165",
                      );
                      await launchUrl(launchUri);
                    } else {
                      // 权限被拒绝
                      ToastEngine.show('Phone call permission denied');
                    }
                  },
                  child: Text('App动态权限'),
                ),
              ],
            ).marginOnly(top: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () async {
                    final tempPath = DirectoryUtil.getTempPath();
                    final docPath = DirectoryUtil.getAppDocPath();
                    final appSupportPath = DirectoryUtil.getAppSupportPath();
                    final storagePath = DirectoryUtil.getStoragePath(); //只能拿沙盒路径，外置SD卡是拿不到的
                    final cacheSize = await DirectoryUtil.getAppCacheSize();

                    Log.d("沙盒路径 - tempPath：$tempPath docPath：$docPath appSupportPath：$appSupportPath storagePath：$storagePath "
                        "cacheSize：$cacheSize");
                  },
                  child: Text('沙盒路径'),
                ),
                ElevatedButton(
                  onPressed: () async {
                    //Key-Value的重要信息持久化缓存（只存小东西如配置，token）
                    await SPUtil.putBool("isVip", true);
                    final isVip = SPUtil.getBool("isVip", defValue: false);
                    Log.d("存入并取出SP的值 - isVip：$isVip");

                    //沙盒缓存文件缓存(可存入对象，大文本，Json，网络请求数据)
                    await localCache.put("name", "李四", expiry: const Duration(seconds: 10));
                    await localCache.put("age", 28, expiry: const Duration(seconds: 10));
                    await localCache.put("gender", 1);
                    await localCache.put("skills", ["游泳", "跑步", "编程"]);
                    await localCache.put("json", {"code": "200", "msg": "Success", "data": 2});

                    String? name = await localCache.get("name");
                    int? age = await localCache.get("age");
                    int? gender = await localCache.get("gender");
                    List<String>? skills = await localCache.get("skills");
                    Map<String, dynamic>? json = await localCache.get("json");
                    Log.d("获取缓存name：$name");
                    Log.d("获取缓存age：$age");
                    Log.d("获取缓存gender：$gender");
                    Log.d("获取缓存skills：$skills");
                    Log.d("获取缓存json：$json");
                  },
                  child: Text('缓存用法'),
                ),
                ElevatedButton(
                  onPressed: () {},
                  child: Text('图片预览'),
                ),
              ],
            ).marginOnly(top: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {},
                  child: Text('图片加载'),
                ),
                Hero(
                    tag: '112cc8a34e13',
                    child: MyLoadImage("https://pic.quanjing.com/cz/8s/QJ8856274343.jpg@%21794ws", width: 80, height: 80),
                ),
                ElevatedButton(
                  onPressed: () {
                    //单图预览，支持hero
                    ImagePreviewEngine.singleImagePreview(context, "https://pic.quanjing.com/cz/8s/QJ8856274343.jpg@%21794ws", heroTag: '112cc8a34e13');
                    //多图预览,支持hero
                    // ImagePreviewEngine.multipleImagePreview(context, "https://pic.quanjing.com/cz/8s/QJ8856274343.jpg@%21794ws");
                  },
                  child: Text('图片预览'),
                ),
              ],
            ).marginOnly(top: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {
                    ref.read(themeProvider.notifier).toggleTheme();
                  },
                  child: Text('手动切换主题'),
                  style: ButtonStyle(
                    backgroundColor: WidgetStateProperty.all<Color>(context.appColors.btnBgDefault),
                    // 设置按钮的背景颜色
                    foregroundColor: WidgetStateProperty.all<Color>(Colors.white),
                    // 设置按钮文字的颜色
                    shadowColor: WidgetStateProperty.all<Color>(context.appColors.btnBgDefault),
                    // 按钮阴影颜色
                    elevation: WidgetStateProperty.all<double>(5),
                    // 按钮阴影的高度
                    shape: WidgetStateProperty.all<RoundedRectangleBorder>(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30), // 圆角边框
                      ),
                    ),
                  ),
                ),
                ElevatedButton(
                  onPressed: () {
                    ref.read(themeProvider.notifier).followSystemTheme();
                  },
                  child: Text('跟随系统主题'),
                  style: ButtonStyle(
                    backgroundColor: WidgetStateProperty.all<Color>(context.appColors.btnBgDefault),
                    // 设置按钮的背景颜色
                    foregroundColor: WidgetStateProperty.all<Color>(Colors.white),
                    // 设置按钮文字的颜色
                    shadowColor: WidgetStateProperty.all<Color>(context.appColors.btnBgDefault),
                    // 按钮阴影颜色
                    elevation: WidgetStateProperty.all<double>(5),
                    // 按钮阴影的高度
                    shape: WidgetStateProperty.all<RoundedRectangleBorder>(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30), // 圆角边框
                      ),
                    ),
                  ),
                ),
              ],
            ).marginOnly(top: 10),
          ],
        ),
      ),
    );
  }
}
