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

import 'package:cpt_form/modules/form/apply/form_apply_screen.dart';
import 'package:cs_resources/generated/assets.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/componentRouter/component_service_manager.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/date_time_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/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import '../../router/page/form_page_router.dart';
import 'vm/apply_view_model.dart';

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

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

  @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 () {
        // 释放控制器资源
      };
    }, []);

    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(
                    width: double.infinity,
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        //支付
                        Visibility(
                          visible: state.formItem != null && state.formItem!.price > 0,
                          child: Row(
                            children: [
                              MyAssetImage(
                                Assets.paymentInfoDetails,
                                width: 27,
                                height: 27,
                                color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                              ),
                              MyTextView(
                                S.current.payment,
                                textColor: context.appColors.textBlack,
                                fontSize: 17,
                                marginLeft: 14,
                                isFontMedium: true,
                              ).expanded(),
                            ],
                          ).marginOnly(top: 15, left: 15, right: 15),
                        ),

                        //支付金额
                        Visibility(
                          visible: state.formItem != null && state.formItem!.price > 0,
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              MyTextView(
                                S.current.fee,
                                textColor: context.appColors.textBlack,
                                fontSize: 18,
                                isFontRegular: true,
                              ),
                              const Spacer(),
                              MyTextView(
                                "SGD",
                                textColor: context.appColors.textBlack,
                                fontSize: 18,
                                isFontRegular: true,
                              ),
                              MyTextView(
                                "\$${state.formItem?.price ?? 0}",
                                textColor: context.appColors.textPrimary,
                                fontSize: 22,
                                marginLeft: 8,
                                isFontMedium: true,
                              ),
                            ],
                          ).marginOnly(top: 20, left: 15, right: 15, bottom: 20),
                        ),

                        //分割线
                        Visibility(
                          visible: state.formItem != null && state.formItem!.price > 0,
                          child: Divider(
                            color: context.appColors.dividerDefault,
                            height: 0.5,
                          ),
                        ),

                        //押金
                        Visibility(
                          visible: state.formItem != null && state.formItem!.deposit > 0,
                          child: Row(
                            children: [
                              MyAssetImage(
                                Assets.paymentInfoDetails,
                                width: 27,
                                height: 27,
                                color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                              ),
                              MyTextView(
                                S.current.deposit,
                                textColor: context.appColors.textBlack,
                                fontSize: 17,
                                marginLeft: 14,
                                isFontMedium: true,
                              ).expanded(),
                            ],
                          ).marginOnly(top: 15, left: 15, right: 15),
                        ),

                        //押金金额
                        Visibility(
                          visible: state.formItem != null && state.formItem!.deposit > 0,
                          child: Row(
                            children: [
                              MyTextView(
                                S.current.deposit_hold,
                                textColor: context.appColors.textBlack,
                                fontSize: 18,
                                isFontRegular: true,
                              ),
                              const Spacer(),
                              MyTextView(
                                "SGD",
                                textColor: context.appColors.textBlack,
                                fontSize: 18,
                                isFontRegular: true,
                              ),
                              MyTextView(
                                "\$${state.formItem?.deposit ?? 0}",
                                textColor: context.appColors.textPrimary,
                                fontSize: 22,
                                marginLeft: 8,
                                isFontMedium: true,
                              ),
                            ],
                          ).marginOnly(top: 20, left: 15, right: 15, bottom: 20),
                        ),

                        //分割线
                        Visibility(
                          visible: state.formItem != null && state.formItem!.deposit > 0,
                          child: Divider(
                            color: context.appColors.dividerDefault,
                            height: 0.5,
                          ),
                        ),

                        //银行卡
                        // Row(
                        //   children: [
                        //     const MyAssetImage(Assets.paymentCardIcon, width: 27, height: 27),
                        //     MyTextView(
                        //       S.current.card,
                        //       textColor: context.appColors.textBlack,
                        //       fontSize: 17,
                        //       marginLeft: 14,
                        //       isFontMedium: true,
                        //     ).expanded(),
                        //   ],
                        // ).marginOnly(top: 14, left: 15, right: 15, bottom: 14),
                        //
                        // //选择支付卡
                        // _paymentInfo(context, ref),

                        //签名
                        MyTextView(
                          S.current.signature,
                          fontSize: 17,
                          marginTop: 24,
                          marginLeft: 15,
                          marginRight: 15,
                          isFontMedium: true,
                          textColor: context.appColors.textBlack,
                        ),

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

                        //签名框
                        Center(
                          child: GestureDetector(
                              //处理手势冲突，手指在签名版上的时候不滑动父布局
                              behavior: HitTestBehavior.opaque,
                              onVerticalDragUpdate: (_) {},
                              child: Stack(
                                children: [
                                  //签名
                                  Center(
                                    child: Container(
                                      width: 345,
                                      height: 190,
                                      color: context.appColors.imgGrayBg,
                                      child: HandSignature(
                                        control: handSignatureControl,
                                        color: context.appColors.textBlack,
                                        width: 1.0,
                                        maxWidth: 3.5,
                                        type: SignatureDrawType.shape,
                                      ),
                                    ),
                                  ),

                                  //清除签名
                                  Align(
                                    alignment: Alignment.bottomRight,
                                    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, left: 15, right: 15),
                      ],
                    ),
                  ),
                ).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.payment,
                  textColor: Colors.white,
                  backgroundColor: context.appColors.btnBgDefault,
                  fontWeight: FontWeight.w500,
                  type: ClickType.throttle,
                  fontSize: 16,
                  minHeight: 50,
                  radius: 0,
                ),
              ],
            )),
        onWillPop: () async {
          viewModel.handlePopAction();
          return true;
        });
  }

  Widget _paymentInfo(BuildContext context, WidgetRef ref) {
    return Container(
        height: 75,
        padding: const EdgeInsets.symmetric(horizontal: 20),
        color: context.appColors.backgroundDark,
        child: Row(
          children: [
            const MyAssetImage(
              Assets.paymentMasterCardIcon,
              height: 34,
              width: 56,
            ),
            MyTextView(
              "Ending 9423",
              marginLeft: 15,
              marginRight: 15,
              textColor: context.appColors.textBlack,
              fontSize: 15,
              isFontMedium: true,
            ).expanded(),
            MyTextView(
              S.current.change,
              textColor: Colors.white,
              backgroundColor: context.appColors.btnBgDefault,
              paddingRight: 16,
              paddingLeft: 16,
              paddingTop: 8,
              onClick: () {
                ComponentServiceManager().paymentService.startChooseCardPage();
              },
              paddingBottom: 8,
              cornerRadius: 7,
              fontSize: 15,
              isFontMedium: true,
            )
          ],
        ));
  }
}
