import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/components/appbar.dart';
import 'package:vitalapp/components/button.dart';

import 'controller.dart';

// ignore: must_be_immutable
class ContractTemplatePage extends GetView<ContractTemplateController> {
  ContractTemplatePage({super.key});
  late InAppWebViewController? _webViewController;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: const Color.fromRGBO(238, 238, 238, 1),
      appBar: VAppBar(
        titleWidget: const Text(
          "合同",
          style: TextStyle(fontSize: 24),
        ),
      ),
      body: Stack(
        children: [
          FutureBuilder(
            future: controller.loadData(),
            builder: (context, snapshot) {
              if (snapshot.connectionState != ConnectionState.done) {
                return const Center(
                  child: SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(),
                  ),
                );
              } else {
                return InAppWebView(
                  initialData: InAppWebViewInitialData(
                    data:
                        '<body style="padding: 100px;">${controller.state.templateContent}</body>',
                  ),
                  initialOptions: InAppWebViewGroupOptions(
                    crossPlatform: InAppWebViewOptions(
                      useShouldOverrideUrlLoading: false,
                      mediaPlaybackRequiresUserGesture: false,
                      cacheEnabled: true,
                    ),
                    android: AndroidInAppWebViewOptions(
                      //设置为 true 以启用混合组合
                      useHybridComposition: true,
                    ),
                  ),
                  onLoadStart: (controller, url) {
                    PromptBox.loading('加载合同中');
                    // 显示加载指示器
                  },
                  onLoadStop: (controller, url) {
                    PromptBox.dismiss();
                  },
                  onWebViewCreated: (InAppWebViewController controller) {
                    _webViewController = controller;
                  },
                );
              }
            },
          ),
          Obx(
            () => Positioned(
              bottom: 8,
              left: 200,
              right: 200,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  VButton(
                    label: "签字",
                    onTap: () {
                      gotoSignature();
                    },
                  ),
                  if (controller.state.userSignature != '')
                    VButton(
                      label: "提交",
                      onTap: () => controller.submitContract(),
                    ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Future<void> _scrollToBottom() async {
    if (_webViewController != null) {
      await _webViewController!.scrollTo(
        x: 0,
        y: 3000,
        animated: true,
      );
    }
  }

  Future<void> gotoSignature() async {
    final result = await Get.toNamed("/contract/signature");
    if (kDebugMode) {
      // TODO: 调试记录签名
      // await TextStorage(
      //   fileName: "signature_${DateTime.now().millisecondsSinceEpoch}.txt",
      //   directory: "debug",
      // ).save(result);
    }
    controller.state.userSignature = result;
    final dto = await controller.contractTemplateManager
        .getContractTemplateDetail(controller.state.templateCode);
    if (dto != null) {
      controller.state.templateContent = dto.templateContent ?? '';
      controller.getkey();
    }
    _scrollToBottom();
    _webViewController?.loadData(
      data:
          '<body style="padding: 100px;">${controller.state.templateContent}</body>',
      mimeType: 'text/html',
      encoding: 'utf-8',
    );
  }
}
