import 'dart:typed_data';

import 'package:cpt_ms/modules/job/sign_in_sign_out/sign_in_sign_out_page.dart';
import 'package:cs_resources/constants/color_constants.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/base/base_stateful_page.dart';
import 'package:plugin_basic/base/mixin_state_lifecycle.dart';
import 'package:plugin_basic/utils/ext_get_nav.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:router/path/router_path.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/screen_util.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_appbar.dart';
import 'package:plugin_basic/base/base_state.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'sign_camera_controller.dart';
import 'sign_camera_state.dart';
import 'package:camera/camera.dart';
import 'package:image/image.dart' as img;
import 'dart:io';
import 'package:path/path.dart';

/*
   签到的自定义相机页面
 */
class SignCameraPage extends BaseStatefulPage<SignCameraController> {
  SignCameraPage({super.key});

  //启动当前页面
  static void startInstance(void Function(String? path)? cb) {
    return Get.start(RouterPath.MSSignCamera, arguments: {'cb': cb});
  }

  @override
  State<SignCameraPage> createState() => _SignCameraPageState();

  @override
  SignCameraController createRawController() {
    return SignCameraController();
  }
}

class _SignCameraPageState extends BaseState<SignCameraPage, SignCameraController> with StateLifecycle {
  late SignCameraState state;

  //Camera的控制器
  late CameraController _controller;
  List<CameraDescription>? _cameras;
  bool _isCameraInitialized = false;

  @override
  void initState() {
    super.initState();
    state = controller.state;
    state.cb = Get.arguments['cb'] as void Function(String?)?;
    _initCamera(); // 初始化摄像头
  }

  @override
  void dispose() {
    Get.delete<SignCameraController>();
    super.dispose();
    _controller.dispose(); // 页面销毁时释放摄像头资源
  }

  @override
  void onResume() {
    super.onResume();
    Log.d("SignInSignOutPage Lifecycle - onResume");
  }

  @override
  void onPause() {
    super.onPause();
    Log.d("SignInSignOutPage Lifecycle - onPause");
  }

  @override
  void onStop() {
    super.onStop();
    Log.d("SignInSignOutPage Lifecycle - onStop");
  }

  @override
  void onStart() {
    super.onStart();
    Log.d("SignInSignOutPage Lifecycle - onStart");
  }

  // 初始化摄像头（选择后置摄像头，配置分辨率）
  Future<void> _initCamera() async {
    // 1. 获取设备上所有可用摄像头
    _cameras = await availableCameras();
    if (_cameras == null || _cameras!.isEmpty) {
      debugPrint("无可用摄像头");
      return;
    }
    // 2. 选择摄像头（优先选前置镜头）
    CameraDescription frontCamera = _cameras!.firstWhere((cam) => cam.lensDirection == CameraLensDirection.front);


    // 3. 初始化控制器（分辨率选 medium，平衡性能和画质）
    _controller = CameraController(
      frontCamera,
      ResolutionPreset.medium,
    );

    // 4. 等待控制器初始化完成
    await _controller.initialize();

    if (mounted) {

      setState(() {
        _isCameraInitialized = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    Log.d("SignInSignOutPage Lifecycle - build走了一遍");
    // 摄像头未初始化时，显示加载

    return autoCtlGetBuilder(
      builder: (controller) {
        return SafeArea(
        bottom: MediaQuery.of(context).padding.bottom > 38,
          top: false,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            padding: EdgeInsets.only(top: ScreenUtil.getStatusBarH(context)),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Color(0xFF091D44),
                  Color(0xFF245A8A),
                  Color(0xFF7F7CEC),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
            child: Column(
              children: [
                //顶部的搜索标题布局
                MyAppBar.titleBar(context, "Sign in / Sign out"),

                SingleChildScrollView(
                  child: Column(
                    children: [
                      // -------- 1:1 摄像头预览区域 --------
                      AspectRatio(
                        aspectRatio: 3 / 4, // 宽高比 1:1
                        child: (!_isCameraInitialized || !_controller.value.isInitialized)
                            ? const Center(child: CircularProgressIndicator(color: Colors.white))
                            : Utils.isEmpty(state.watermarkedFile)
                                ? CameraPreview(_controller)
                                : MyLoadImage(state.watermarkedFile),
                      ),

                      Padding(
                        padding: const EdgeInsets.only(top: 40, bottom: 40),
                        child: Stack(
                          children: [
                            Visibility(
                              visible: Utils.isEmpty(state.watermarkedFile),
                              child: const MyAssetImage(Assets.cptJobSignTakePic, width: 93, height: 93).onTap(() {
                                _takePicture();
                              }),
                            ),
                            Visibility(
                              visible: Utils.isNotEmpty(state.watermarkedFile),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  MyButton(
                                    onPressed: () {
                                      controller.handleImage(null);
                                    },
                                    text: 'Retake'.tr,
                                    textColor: Colors.white,
                                    backgroundColor: ColorConstants.textYellowF8AE00,
                                    radius: 25,
                                    minHeight: 50,
                                  ).marginOnly(left: 30, right: 7.5).expanded(),
                                  MyButton(
                                    onPressed: () {
                                      controller.confirmImage();
                                    },
                                    text: 'Confirm'.tr,
                                    textColor: Colors.white,
                                    backgroundColor: ColorConstants.textGreen0AC074,
                                    radius: 25,
                                    minHeight: 50,
                                  ).marginOnly(right: 30, left: 7.5).expanded(),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ).expanded(),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 拍照逻辑：调用控制器拍摄照片
  Future<void> _takePicture() async {
    try {
      if (_isCameraInitialized || _controller.value.isInitialized) {
        XFile picture = await _controller.takePicture();
        debugPrint("照片路径：${picture.path}");

        String? watermarkedPath = await _addWatermark(picture.path);
        // 后续可处理：上传服务器、保存到相册等
        debugPrint("处理后带水印的图片路径：$watermarkedPath");

        if (Utils.isNotEmpty(watermarkedPath)) {
          controller.handleImage(watermarkedPath);
        } else {
          ToastEngine.show("Image processing failed !");
        }
      }
    } catch (e) {
      debugPrint("拍照失败：$e");
      ToastEngine.show("Take Picture Failed");
    }
  }

  Future<String?> _addWatermark(String imagePath) async {
    try {
      // -------- 步骤1：解码图片并修正旋转 --------
      File originalFile = File(imagePath);
      if (!await originalFile.exists()) {
        debugPrint("错误：原始图片不存在 → $imagePath");
        return null;
      }

      // 读取图片字节
      Uint8List imageBytes = await originalFile.readAsBytes();
      img.Image? originalImage = img.decodeImage(imageBytes);
      if (originalImage == null) {
        debugPrint("错误：图片解码失败");
        return null;
      }

      //如果宽>高，则逆时针旋转90度
      if (originalImage.width > originalImage.height) {
        debugPrint("图片的宽>高，则逆时针旋转90度");
        originalImage = img.copyRotate(originalImage, 270);
      }

      //由于是前置摄像头 → 水平镜像翻转
      originalImage = img.flipHorizontal(originalImage);

      // -------- 步骤2：生成水印文本（时间） --------
      String watermarkText = DateTimeUtils.formatNowDateStr(format: 'yyyy-MM-dd HH:mm');

      // -------- 步骤3：准备绘制字体 --------
      img.drawString(originalImage, img.arial_24, 20, 20, watermarkText);

      // -------- 步骤5：保存带水印的新图片（避免覆盖原始文件） --------
      String watermarkedPath = join(dirname(imagePath), 'watermarked_${basename(imagePath)}');
      File watermarkedFile = File(watermarkedPath);

      // 编码为 JPG 保存到File
      final processedBytes = img.encodeJpg(originalImage, quality: 95);
      await watermarkedFile.writeAsBytes(processedBytes);

      debugPrint("成功：带水印图片已保存 → $watermarkedPath");

      return watermarkedPath;
    } catch (e) {
      debugPrint("添加水印失败：$e");
      ToastEngine.show("Image processing failed");
    }
    return null;
  }
}
