// import 'dart:ffi';
import 'dart:io';
import 'dart:math' as math;
import 'package:get/get.dart';
import 'package:app_package/src/models/app_update.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:app_package/src/stores/app.dart';
import 'package:ota_update/ota_update.dart';
import 'package:flutter/material.dart';
import '../api/update.dart';
import '../stores/auth.dart';
import '../constants/config.dart';
import '../assets.gen.dart';

class UpdateAppStore {
  static late UpdateAppStore _instance;

  UpdateAppStore._(); // 私有构造函数
  static UpdateAppStore get instance {
    _instance = UpdateAppStore._();
    return _instance;
  }

  AppUpdateModel data = AppUpdateModel();
  final authGlobalStore = GetIt.I.get<AuthGlobalStore>();

  getUpdateInfo() async {
    final userId = authGlobalStore.info!.id;
    String version = await AppPackageInfo.instance.getPackageInfoVersion();
    var res = await UpdateApi.getUpdateInfo({
      'version': version,
      'platformType': Platform.isAndroid ? 'android' : 'ios',
      'applicationType': 'hgj',
      'userId': userId,
      'phoneMemory': '',
      'updateStatus': true,
    });
    if (res.data == null) return;
    data = res.data ?? AppUpdateModel();

    String? notipAppVersion = WisStorageUtil.get(key: 'notipAppVersion');

    /// 检查升级
    final update = await _checkUpdate(
      version: data.version ?? '0',
      buildVersion: data.buildVersion ?? '0',
    );

    if (update) {
      if (WisStorageUtil.get(key: 'isHideUpdate') == true ||
          (notipAppVersion == '${data.version}-${data.buildVersion}')) {
        return;
      } else {
        WisStorageUtil.set(
          key: 'isHideUpdate',
          data: false,
        );
        _showUpdate();
      }
    }
  }

  checkUpdate() async {
    final userId = authGlobalStore.info?.id;

    PackageInfo packageInfo = await AppPackageInfo.instance.getPackageInfo();

    var res = await UpdateApi.getUpdateInfo({
      'version': packageInfo.version,
      'platformType': Platform.isAndroid ? 'android' : 'ios',
      'applicationType': 'hgj',
      'userId': userId,
      'phoneMemory': '',
      'updateStatus': true,
    });
    if (res.data == null) {
      WToastUtil.show('当前版本已经是最新的了');
      return;
    }
    data = res.data!;
    final update = await _checkUpdate(
      version: data.version!,
      buildVersion: data.buildVersion!,
    );

    if (update) {
      _showUpdate();
    } else {
      WToastUtil.show('当前版本已经是最新的了');
    }
  }

  ///显示弹出层
  ///
  ///[url]  Android:优先[cdnDownloadLink]CDN连接， IOS ：[downloadLink]平台链接
  ///[canPop] 能否关闭 !（是否强制更新）
  _showUpdate() async {
    String url;
    url = data.downloadLink!;
    final canPop = !(data.forceUpdate ?? true);
    // final canPop = true;
    final recordText = '${data.updateRecord}';
    WModalUtil.custom(
      builder: (context, popTrigger) {
        return AppUpdateComponent(
          url: url,
          popTrigger: canPop ? popTrigger : null,
          // popTrigger: popTrigger,
          recordText: recordText,
          buildVersion: data.buildVersion,
          version: data.version,
        );
      },
    );
  }

  ///对比是否需要更新
  _checkUpdate({required String version, required String buildVersion}) async {
    var packageInfo = await AppPackageInfo.instance.getPackageInfo();
    final versionArr = version.split('.').toList();
    final curVersionArr = packageInfo.version.split('.').toList();
    var update = false;
    for (var i = 0; i < versionArr.length; i++) {
      final $0 = int.tryParse(versionArr[i]) ?? 0;
      final $1 = int.tryParse(curVersionArr[i]) ?? 0;

      if ($0 > $1) {
        update = true;
        break;
      }

      ///如果库中版本某一项已经小于当前版本  就没必要继续往下一项判断了
      else if ($0 < $1) {
        break;
      }
    }
    if (!update) {
      if ((int.tryParse(buildVersion) ?? 0) >
          (int.tryParse(packageInfo.buildNumber) ?? 0)) {
        update = true;
      }
    }

    return update;
  }

  closeTip(version, buildVesion) async {
    final boolean = await WModalUtil.showSync(
      '关闭后您将不会再接收到有关此版本的更新提示。',
      title: '关闭此版本提示',
      cancelText: '以后再说',
      confirmText: '确认关闭',
    );
    Get.back();
    if (boolean!) {
      WisStorageUtil.set(
        key: 'notipAppVersion',
        data: '$version-$buildVesion',
      );
      WisStorageUtil.set(
        key: 'isHideUpdate',
        data: true,
      );
    } else {
      WisStorageUtil.set(
        key: 'isHideUpdate',
        data: false,
      );
    }
  }
}

///app更新样式

class AppUpdateComponent extends StatefulWidget {
  AppUpdateComponent({
    Key? key,
    required this.url,
    required this.popTrigger,
    required this.version,
    required this.buildVersion,
    required this.recordText,
  }) : super(key: key);
  final String? url;
  final void Function(dynamic)? popTrigger;
  final String? version;
  final String? buildVersion;
  final String? recordText;

  @override
  State<AppUpdateComponent> createState() => _AppUpdateComponentState();
}

class _AppUpdateComponentState extends State<AppUpdateComponent>
    with SingleTickerProviderStateMixin {
  final appGlobalStore = GetIt.I.get<AppGlobalStore>();
  late int? downloadId;

  OtaEvent? currentEvent;
  double _progress = 0.0;
  String _status = '准备更新';
  bool _isUpdating = false;

  Future<void> _downloadAndInstallUpdate(String url, String name) async {
    try {
      setState(() {
        _isUpdating = true;
        _status = '准备下载更新';
        _progress = 0.0;
      });

      // 替换为你的 APK 下载地址
      String _downloedUrl = url;

      // 开始 OTA 更新
      OtaUpdate()
          .execute(
        _downloedUrl,
        destinationFilename: name,
      )
          .listen(
        (OtaEvent event) {
          setState(() {
            currentEvent = event;

            // 根据事件类型更新状态
            switch (event.status) {
              case OtaStatus.DOWNLOADING:
                _status = '正在下载更新...';
                // 解析进度百分比
                if (event.value != null) {
                  try {
                    _progress = double.parse(event.value!) / 100;
                  } catch (e) {
                    _progress = 0.0;
                  }
                }
                break;
              case OtaStatus.INSTALLING:
                _status = '正在安装更新...';
                _progress = 1.0;
                break;
              case OtaStatus.ALREADY_RUNNING_ERROR:
                _status = '错误：已有更新任务在运行';
                _isUpdating = false;
                break;
              case OtaStatus.PERMISSION_NOT_GRANTED_ERROR:
                _status = '错误：未授予安装权限';
                _isUpdating = false;
                break;
              case OtaStatus.INTERNAL_ERROR:
                _status = '错误：内部错误 ${event.value}';
                _isUpdating = false;
                break;
              case OtaStatus.DOWNLOAD_ERROR:
                _status = '错误：下载失败 ${event.value}';
                _isUpdating = false;
                break;
              case OtaStatus.CANCELED:
                setState(() {
                  _status = '已取消下载';
                  _isUpdating = false;
                });
                break;
              default:
                _status = '未知状态：${event.status}';
                break;
            }
          });
        },
      );
    } catch (e) {
      setState(() {
        _status = '更新失败：$e';
        _isUpdating = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = WTheme.of(context).colorScheme;
    return Wisdom(
      color: Colors.black38,
      child: SimpleDialog(
        backgroundColor: Colors.transparent,
        title: Stack(
          clipBehavior: Clip.none,
          children: [
            Image(
              image: AssetList.$main_updatebg_png_image,
            ),
            Positioned(
              top: 50.pt,
              left: 50.pt,
              child: DefaultTextStyle(
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.pt,
                  height: 1.5,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    WisText(
                      '发现新版本',
                      weight: FontWeight.bold,
                      size: 19.pt,
                    ),
                    WisText(
                      'V${widget.version}   build ${widget.buildVersion}',
                      size: 14.pt,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        titlePadding: EdgeInsets.zero,
        contentPadding: EdgeInsets.zero,
        children: [
          Wisdom(
            borderRadius: BorderRadius.vertical(
              bottom: Radius.circular(8.pt),
            ),
            padding: EdgeInsets.symmetric(horizontal: 30.pt, vertical: 15.pt),
            color: Colors.white,
            child: Column(
              children: [
                ConstrainedBox(
                  constraints: BoxConstraints(
                    maxHeight: 150.pt,
                    minHeight: 60.pt,
                  ),
                  child: SingleChildScrollView(
                    child: Wisdom.column(
                      margin: EdgeInsets.only(
                          bottom: Platform.isAndroid ? 10.pt : 20.pt),
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        WisText(
                          '更新内容',
                          weight: FontWeight.bold,
                          size: 16.pt,
                        ),
                        SizedBox(height: 10.pt),
                        WisText(
                          widget.recordText!,
                          size: 14.pt,
                        ),
                      ],
                    ),
                  ),
                ),
                if (Platform.isAndroid) ...[
                  Wisdom(
                    onTap: () => launch('https://app.huiguanjia.cn'),
                    child: WisText(
                      '(如遇到升级与安装困难，请关闭手机安全模式，或点击前往官网查看操作指南。)',
                      size: 11.pt,
                      color: colorScheme.grey,
                    ),
                  ),
                  SizedBox(height: 20.pt),
                ],

                // 进度
                currentEvent != null
                    ? Wisdom.column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          WaterLoadingProgress(
                            progress: _progress,
                            waterColor: Colors.blue.shade400,
                            backgroundColor: Colors.grey.shade300,
                            width: 250,
                            height: 50,
                          ),

                          const SizedBox(height: 5),
                          // Slider(
                          //   value: _progress,
                          //   min: 0.0,
                          //   max: 1.0,
                          //   onChanged: (value) {
                          //     setState(() {
                          //       _progress = value;
                          //     });
                          //   },
                          // ),
                          // const SizedBox(height: 8),
                          Text('$_status'),
                          _isUpdating
                              ? Wisdom.row(
                                  children: <Widget>[
                                    WButton(
                                      color: colorScheme.background4,
                                      margin: EdgeInsets.only(top: 15.pt),
                                      shape: RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(40.pt),
                                      ),
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 30.pt,
                                      ),
                                      height: 44.pt,
                                      // onPressed: () => launch(url),
                                      onPressed: () async => {
                                        // setState(() {
                                        //   currentEvent = null;
                                        //   _isUpdating = false;
                                        // }),
                                        // await RUpgrade.cancel(downloadId!),
                                        OtaUpdate().cancel(),
                                      },
                                      child: WisText(
                                        '取消',
                                        size: 16.pt,
                                        color: colorScheme.primary,
                                      ),
                                    ).asExpanded(),
                                  ],
                                )
                              : Container(),
                        ],
                      )
                    : Wisdom.row(
                        children: [
                          WButton(
                            margin: EdgeInsets.only(bottom: 15.pt),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(40.pt),
                            ),
                            padding: EdgeInsets.symmetric(
                              horizontal: 30.pt,
                            ),
                            height: 44.pt,
                            // onPressed: () => launch(url),
                            onPressed: () async => {
                              if (_isUpdating != true)
                                {
                                  /// 版本号
                                  if (Platform.isAndroid)
                                    {
                                      print(widget.url),
                                      _downloadAndInstallUpdate(widget.url!,
                                          'huiguanjia-${await AppPackageInfo.instance.getPackageInfoVersion()}-${await AppPackageInfo.instance.getPackageInfoBuildVersion()}.apk'),
                                    }
                                  else
                                    {
                                      launch(widget.url!),
                                    }
                                }
                            },
                            child: WisText(_isUpdating ? '更新中...' : '立即更新',
                                size: 16.pt, weight: FontWeight.bold),
                          ).asExpanded(),
                        ],
                      )
              ],
            ),
          ),
          if (widget.popTrigger != null)
            Wisdom.row(
                color: Colors.transparent,
                margin: EdgeInsets.only(top: 15.pt),
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Wisdom(
                    child: GestureDetector(
                      onTap: () {
                        OtaUpdate().cancel();
                        setState(() {
                          currentEvent = null;
                          _isUpdating = false;
                        });
                        UpdateAppStore.instance
                            .closeTip(widget.version, widget.buildVersion);
                      },
                      behavior: HitTestBehavior.deferToChild,
                      child: Wisdom(
                        border: Border.all(
                          color: Colors.white,
                        ),
                        color: Colors.white12,
                        padding: EdgeInsets.all(8.pt),
                        borderRadius: BorderRadius.circular(20.pt),
                        child: Icon(
                          Icons.close,
                          color: Colors.white,
                          size: 20.pt,
                        ),
                      ),
                    ),
                  ),
                ]),
        ],
      ),
    );
  }
}

class WaterLoadingProgress extends StatefulWidget {
  final double progress;
  final Color waterColor;
  final Color backgroundColor;
  final double width;
  final double height;
  final double borderRadius;

  const WaterLoadingProgress({
    Key? key,
    required this.progress,
    this.waterColor = Colors.blue,
    this.backgroundColor = Colors.grey,
    this.width = 200,
    this.height = 200,
    this.borderRadius = 20,
  }) : super(key: key);

  @override
  State<WaterLoadingProgress> createState() => _WaterLoadingProgressState();
}

class _WaterLoadingProgressState extends State<WaterLoadingProgress>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      decoration: BoxDecoration(
        color: widget.backgroundColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(widget.borderRadius),
        border: Border.all(
          color: widget.backgroundColor.withOpacity(0.3),
          width: 2,
        ),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(widget.borderRadius - 2),
        child: AnimatedBuilder(
          animation: _controller,
          builder: (context, child) {
            return CustomPaint(
              painter: WaterPainter(
                progress: widget.progress,
                waterColor: widget.waterColor,
                animationValue: _controller.value,
              ),
              size: Size(widget.width, widget.height),
            );
          },
        ),
      ),
    );
  }
}

class WaterPainter extends CustomPainter {
  final double progress;
  final Color waterColor;
  final double animationValue;

  WaterPainter({
    required this.progress,
    required this.waterColor,
    required this.animationValue,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = waterColor
      ..style = PaintingStyle.fill;

    final path = Path();
    final waterHeight = size.height * (1 - progress);

    // 波浪的振幅
    final amplitude = size.height * 0.05;
    // 波浪的频率
    final frequency = 2.0;

    path.moveTo(0, waterHeight);

    for (double x = 0; x <= size.width; x++) {
      // 创建两个交错的正弦波，形成更自然的水波效果
      final y = waterHeight +
          amplitude *
              math.sin((x / size.width * frequency * math.pi) +
                  animationValue * math.pi * 2) +
          amplitude *
              0.5 *
              math.sin((x / size.width * frequency * 2 * math.pi) +
                  animationValue * math.pi * 4);

      path.lineTo(x, y);
    }

    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.close();

    canvas.drawPath(path, paint);

    // 绘制百分比文字
    final textSpan = TextSpan(
      text: '${(progress * 100).toInt()}%',
      style: TextStyle(
        color: Colors.white,
        fontSize: size.width * 0.15,
        fontWeight: FontWeight.bold,
        shadows: [
          Shadow(
            color: Colors.black26,
            offset: Offset(1, 1),
            blurRadius: 3,
          ),
        ],
      ),
    );

    final textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
      textAlign: TextAlign.center,
    );

    textPainter.layout();
    textPainter.paint(
      canvas,
      Offset(
        (size.width - textPainter.width) / 2,
        (size.height - textPainter.height) / 2,
      ),
    );
  }

  @override
  bool shouldRepaint(WaterPainter oldDelegate) {
    return oldDelegate.progress != progress ||
        oldDelegate.waterColor != waterColor ||
        oldDelegate.animationValue != animationValue;
  }
}
