import 'dart:typed_data';
import 'dart:ui';

import 'package:cpt_form/modules/apply/vm/apply_view_model.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';
import '../../router/page/form_page_router.dart';

@RoutePage()
class SignaturePage extends HookConsumerWidget {
  const SignaturePage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context}) {
    if (context != null) {
      context.router.push(const SignaturePageRoute());
    } else {
      appRouter.push(const SignaturePageRoute());
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final viewModel = ref.watch(applyViewModelProvider.notifier);
    final state = ref.watch(applyViewModelProvider);

    //签名版配置
    final HandSignatureControl handSignatureControl = useMemoized(() {
      return HandSignatureControl(
        threshold: 3.0,
        smoothRatio: 190 / 345,
        velocityRange: 2.0,
      );
    });

    useEffect(() {
      //赋值State的值
      Future.microtask(() {});

      return () {
        // 组件卸载时执行
        handSignatureControl.dispose();
      };
    }, []);

    return WillPopScope(
        child: Scaffold(
            appBar: MyAppBar.appBar(context, state.detailPage?['title']),
            backgroundColor: context.appColors.backgroundWhite,
            body: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  physics: const BouncingScrollPhysics(),
                  child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 15),
                    width: double.infinity,
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        MyTextView(
                          S.current.signature,
                          fontSize: 17,
                          marginTop: 30,
                          isFontMedium: true,
                          textColor: context.appColors.textBlack,
                        ),

                        //签名的说明文本
                        MyTextView(
                          state.detailPage?['detail_data']['signature_txt'],
                          fontSize: 15,
                          marginTop: 26,
                          marginBottom: 21,
                          isFontRegular: true,
                          textColor: context.appColors.textBlack,
                        ),

                        //签名框
                        Stack(
                          children: [
                            //签名
                            Center(
                              child: Container(
                                width: 345,
                                height: 190,
                                color: context.appColors.imgGrayBg,
                                child: state.enableEdit
                                    ? HandSignature(
                                        control: handSignatureControl,
                                        color: context.appColors.textBlack,
                                        width: 1.0,
                                        maxWidth: 3.5,
                                        type: SignatureDrawType.shape,
                                      )
                                    : MyLoadImage(
                                        state.formContentDetail.signature,
                                        width: 345,
                                        height: 190,
                                      ),
                              ),
                            ),

                            //清除签名
                            Align(
                              alignment: Alignment.bottomRight,
                              child: Visibility(
                                visible: state.enableEdit,
                                child: MyTextView(
                                  S.current.clean,
                                  fontSize: 12,
                                  textColor: Colors.white,
                                  cornerRadius: 10.37,
                                  backgroundColor: context.appColors.btnBgDefault,
                                  paddingTop: 4,
                                  paddingBottom: 4,
                                  paddingLeft: 11,
                                  paddingRight: 11,
                                  margin: 10,
                                  onClick: () {
                                    handSignatureControl.clear();
                                  },
                                ),
                              ),
                            ),
                          ],
                        ).constrained(
                          width: 345,
                          height: 190,
                        ),

                        //同意协议富文本
                        RichText(
                          text: TextSpan(
                            style: TextStyle(fontSize: 15, fontWeight: FontWeight.w400, color: context.appColors.textBlack),
                            children: <TextSpan>[
                              TextSpan(
                                text: S.current.signed_and_agreed_by,
                              ),
                              TextSpan(
                                text: " ${UserConfigService.getState().userName ?? "-"} \n",
                                style: TextStyle(color: context.appColors.textPrimary),
                              ),
                              TextSpan(
                                text: DateTimeUtils.formatNowDateStr(format: 'dd MMM yyyy HH:mm'),
                              ),
                            ],
                          ),
                        ).marginOnly(top: 21, bottom: 21),
                      ],
                    ),
                  ),
                ).expanded(),

                //底部按钮
                MyButton(
                  onPressed: () async {
                    final isFilled = handSignatureControl.isFilled;
                    if (!isFilled) {
                      ToastEngine.show("Please sign first");
                      return;
                    }

                    var byteData = await handSignatureControl.toImage(
                      format: ImageByteFormat.png,
                      border: 0,
                      width: 345,
                      height: 190,
                      background: Colors.white,
                    ) as ByteData;

                    //存入本表单数据
                    viewModel.updateFormContentDetail((content) {
                      content.signatureByteData = byteData;
                    });

                    viewModel.submitForm();
                  },
                  text: S.current.submit,
                  textColor: Colors.white,
                  backgroundColor: context.appColors.btnBgDefault,
                  fontWeight: FontWeight.w500,
                  enable: state.enableEdit,
                  disabledBackgroundColor: context.appColors.disEnableGray,
                  type: ClickType.throttle,
                  fontSize: 16,
                  minHeight: 50,
                  radius: 0,
                ),
              ],
            )),
        onWillPop: () async {
          viewModel.handlePopAction();
          return true;
        });
  }
}
