/*
 * @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 'dart:async';
import 'package:clipboard/clipboard.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:marking_app/provider/upgrade_provider.dart';
import 'package:marking_app/utils/app_upgrade/DownloadApk.dart';
import 'package:marking_app/utils/app_upgrade/UpgradePermission.dart';
import 'package:marking_app/utils/app_upgrade/model/UpdateAppEvent.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/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_string.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 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: 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),
                  )
                ],
              ),
            ),
            const 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 ConsumerWidget {
  const DownloadProgress({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(upgradeProvider);
    var str = (count * 100).toString().split('.')[0];
    if (count <= 0) return Container();
    return Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        LinearPercentIndicator(
          alignment: MainAxisAlignment.center,
          width: 245.w,
          animation: false,
          lineHeight: 20.0.h,
          percent: count,
          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 ConsumerWidget {
  final UpdateAppEvent updateAppEvent;
  final String deviceInfo;
  const DownloadButton(this.updateAppEvent, {required this.deviceInfo, Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(upgradeProvider);
    if (count > 0) return Container();

    return Container(
      height: 38.h,
      width: 245.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(42.h)),
        gradient: const LinearGradient(colors: [
          Color.fromRGBO(24, 70, 238, 1),
          Color.fromRGBO(72, 122, 255, 1),
        ]),
      ),
      child: MaterialButton(
        onPressed: () => easyThrottle('DownloadButton_App_Upgrade', () async {
          if (deviceInfo == "android" && updateAppEvent.equipment == Equipment.android) {
            bool flag = await UpgradePermission(updateAppEvent.deviceInfo).checkPermission();
            if (flag) {
              flag = await DownloadApk.installApk(context, updateAppEvent, ref);

              if (!flag) {
                print('执行到了重置更新按钮的地方....');
                ref.read(upgradeProvider.notifier).clean(); // 更新失败重置 更新按钮
              } 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 {
              await launchUrlString(updateAppEvent.link);
            } catch (e) {
              toPrint(val: '进来更新报错$e');
            }
          }
        }),
        child: quickText('立即体验', size: 16.sp, color: Colors.white, fontWeight: FontWeight.w500),
      ),
    );
  }
}
