/*
 * @Author: wangyang 1147192855@qq.com
 * @Date: 
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-09-29 10:11:54
 * @FilePath: \marking_app\lib\utils\app_upgrade\UpdateDialog.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Descripttion: 版本更新提示弹窗
 * @version: 
 * @Author: wy
 * @Date: 2020-07-30 14:03:28
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-01-12 15:08:43
 */
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/utils/app_upgrade/DownloadApk.dart';
import 'package:making_school_asignment_app/common/utils/app_upgrade/UpgradePermission.dart';
import 'package:making_school_asignment_app/common/utils/app_upgrade/upgradeLogic.dart';
import 'package:making_school_asignment_app/common/utils/utils.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../anti_shake_throttling.dart';
import 'model/UpdateAppEvent.dart';

class UpdateDialog extends Dialog {
  final UpdateAppEvent updateAppEvent;
  final String deviceInfo;

  const UpdateDialog({super.key, required this.updateAppEvent, required this.deviceInfo});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: isPad() ? ScreenUtil().screenWidth * 0.62 : 319.w,
        height: 440.h,
        padding: EdgeInsets.symmetric(vertical: 8.h),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(18.sp),
          image: const DecorationImage(
            alignment: Alignment.topCenter,
            image: AssetImage("assets/images/upgrade_dialog_bgc.png"),
            fit: BoxFit.fitWidth,
          ),
        ),
        child: Column(
          children: <Widget>[
            Expanded(
              child: ListView(
                physics: const BouncingScrollPhysics(),
                padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 0),
                children: [
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top:isPad()? 136.h : 128.h, bottom: 10.h),
                    child: quickText(
                      updateAppEvent.title,
                      size: 18.sp,
                      fontWeight: FontWeight.w600,
                      color: const Color.fromRGBO(58, 90, 159, 1),
                    ),
                  ),
                  HtmlWidget(
                    updateAppEvent.description,
                    customStylesBuilder: (element) {
                      return {'color': '#666666', 'font-weight': 'normal', 'text-decoration': 'none'};
                    },
                    onLoadingBuilder: (context, element, loadingProgress) => const CircularProgressIndicator(),
                    renderMode: RenderMode.column,
                    textStyle: TextStyle(fontSize: 14.sp, color: Colors.black87),
                  )
                ],
              ),
            ),
            DownloadProgress(),
            DownloadButton(updateAppEvent, deviceInfo: deviceInfo),
          ],
        ),
      ),
    );
  }

  // 调起
  static showUpdateDialog(BuildContext context, UpdateAppEvent updateAppEvent) {
    return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () async => false,
          child: UpdateDialog(updateAppEvent: updateAppEvent, deviceInfo: updateAppEvent.deviceInfo),
        );
      },
    );
  }
}

// 进度条
class DownloadProgress extends StatelessWidget {
  DownloadProgress({super.key});
  final logic = Get.find<UpgradeLogic>();

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      var str = (logic.downloadRatio.value * 100).toString().split('.')[0];
      if (logic.downloadRatio.value <= 0) return Container();
      return Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          LinearPercentIndicator(
            alignment: MainAxisAlignment.center,
            width: isPad() ? ScreenUtil().screenWidth * 0.55 : 245.w,
            animation: false,
            lineHeight: 20.0.h,
            percent: logic.downloadRatio.value,
            center: quickText(
              "$str%",
              size: 14.sp,
              align: TextAlign.center,
              color: Colors.white,
            ),
            linearStrokeCap: LinearStrokeCap.roundAll,
            progressColor: Theme.of(context).primaryColor,
          ),
          Container(
            height: 6.h,
          ),
          quickText('更新中...', size: 12.sp, fontWeight: FontWeight.w500, color: const Color.fromRGBO(90, 90, 90, 1))
        ],
      );
    });
  }
}

// 点击下载按钮
class DownloadButton extends StatelessWidget {
  final UpdateAppEvent updateAppEvent;
  final String deviceInfo;
  DownloadButton(this.updateAppEvent, {required this.deviceInfo, super.key});
  final logic = Get.find<UpgradeLogic>();

  // 打开浏览器或者对应的对应市场进行下载
  Future<bool> toLaunch(UpdateAppEvent data) async {
    var uri = Uri.parse('market://details?id=${updateAppEvent.packageName}');
    if (await canLaunchUrl(uri)) {
      // 跳进对应的应用市场进行更新操作
      return await launchUrl(uri);
    }
    // 无法进入应用市场就打开浏览器进行下载
    uri = Uri.parse(data.link);
    if (await canLaunchUrl(uri)) return await launchUrl(uri);
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final count = logic.downloadRatio.value;
      if (count > 0) return Container();
      var primaryColor = Theme.of(context).primaryColor;

      if (updateAppEvent.equipment == Equipment.windows) {
        return SizedBox(
          child: quickText('若没有弹出更新弹框，可关闭APP重新打开执行更新...', size: 16.sp),
        );
      }

      return Container(
        height: 38.h,
        width: isPad() ? ScreenUtil().screenWidth * 0.45 : 245.w,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(42.h)),
          gradient: LinearGradient(colors: [primaryColor, primaryColor.withOpacity(0.7)]),
        ),
        child: MaterialButton(
          onPressed: () => easyThrottle('DownloadButton_App_Upgrade', duration: const Duration(milliseconds: 1000), () async {
            if (deviceInfo == "android" && updateAppEvent.equipment == Equipment.android) {
              // 权限检查 判断是否有读写内存的权限
              bool flag = await UpgradePermission(updateAppEvent.deviceInfo).checkPermission(context, updateAppEvent);
              if (flag) {
                flag = await DownloadApk.installApk(context, updateAppEvent, logic);
                if (!flag) {
                  print('执行到了重置更新按钮的地方....');
                  logic.downloadRatio.value = 0.0; // 更新失败重置 更新按钮
                } else {
                  print('更新成功重新打开APP..............');
                  RestartWidget.restartApp(context); // 安装成功 重启APP
                }
                return;
              }
              // await FlutterClipboard.copy(updateAppEvent.link);
              // setTimeOut(1000, () => ToastUtils.showInfo('下载链接已经复制到设备，可前往浏览器下载安装'));
            } else if (deviceInfo == "ios" && updateAppEvent.equipment == Equipment.ios) {
              try {
                print(updateAppEvent.link);
                await launchUrlString(updateAppEvent.link);
              } catch (e) {
                print('进来更新报错$e');
              }
            }
            //  else if (deviceInfo == 'windows' && updateAppEvent.equipment == Equipment.windows) {
            //   await autoUpdater.setFeedURL(updateAppEvent.link);
            //   await autoUpdater.checkForUpdates();
            //   await autoUpdater.setScheduledCheckInterval(0);
            // }
          }),
          child: quickText(!logic.loadingApk.value ? '立即体验' : '正在下载...', size: 16.sp, color: Colors.white, fontWeight: FontWeight.w500),
        ),
      );
    });
  }
}
