import 'package:clean/base/base_controller.dart';
import 'package:clean/model/asset_info.dart';
import 'package:clean/utils/expand.dart';
import 'package:clean/utils/file_utils.dart';
import 'package:clean/utils/image_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../utils/toast_util.dart';
import '../image_picker/image_picker_assets.dart';

import 'package:intl/intl.dart';

import 'dart:typed_data';
import 'dart:io';

class PrivacyController extends BaseController {
  late var passwordStr = "".obs;

  late var isUnlock = false.obs;

  late List<AssetEntity>? imageList;

  // 存储所有图片，按月份分组
  final assetsByMonth = <String, List<AssetInfo>>{}.obs;

  // 获取月份数量
  int get monthCount => assetsByMonth.length;

  // 获取总图片数量
  int get totalAssetCount =>
      assetsByMonth.values.fold(0, (sum, list) => sum + list.length);

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    loadAssets();
  }

  // 加载并分组图片
  Future<void> loadAssets() async {
    final imageList = await FileUtils.getAllAssets();
    if (imageList.isEmpty) return;

    // 清空现有数据
    assetsByMonth.clear();

    // 按月份分组
    for (var asset in imageList) {
      final monthKey = ImageUtil.getMonthKey(asset.createDateTime);
      if (!assetsByMonth.containsKey(monthKey)) {
        assetsByMonth[monthKey] = [];
      }
      assetsByMonth[monthKey]!.add(asset);
    }

    // 对每个月份内的图片按时间排序（新的在前）
    assetsByMonth.forEach((key, list) {
      list.sort((a, b) => b.createDateTime.compareTo(a.createDateTime));
    });

    // 打印分组结果
    assetsByMonth.forEach((key, assets) {
      print('${ImageUtil.formatMonthKey(key)}: ${assets.length} photos');
    });
  }

  // 处理输入密码逻辑
  void inputPassword(String num) {
    passwordStr.value = passwordStr.value + num;

    if (passwordStr.value.length == 4) {
      if (passwordStr.value != "1234") {
        ToastUtil.show("Input Error");
        Future.delayed(const Duration(milliseconds: 100), () {
          passwordStr.value = "";
        });
      } else {
        isUnlock.value = true;
      }
    }
  }

  // 上传按钮点击
  void uploadBtnClick() {
    showCupertinoModalPopup(
      context: Get.context!,
      builder: (context) {
        return CupertinoActionSheet(
          actions: <Widget>[
            //操作按钮集合
            CupertinoActionSheetAction(
              onPressed: () {
                Navigator.pop(context);
                openGallery();
              },
              child: Text(
                'Upload from Gallery',
                style: TextStyle(
                  color: "#007AFF".color,
                  fontWeight: FontWeight.w500,
                  fontSize: 16.sp,
                ),
              ),
            ),
            CupertinoActionSheetAction(
              onPressed: () {
                Navigator.pop(context);
                openCamera();
              },
              child: Text(
                'Take and Upload',
                style: TextStyle(
                  color: "#007AFF".color,
                  fontWeight: FontWeight.w500,
                  fontSize: 16.sp,
                ),
              ),
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            //取消按钮
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text(
              'Cancel',
              style: TextStyle(
                color: "#007AFF".color,
                fontWeight: FontWeight.w500,
                fontSize: 16.sp,
              ),
            ),
          ),
        );
      },
    );
  }

  // 保存并刷新图片列表
  Future<void> saveAndRefreshAssets(List<AssetEntity> assets) async {
    for (var asset in assets) {
      await FileUtils.saveAsset(asset);
    }
    // 重新加载图片列表
    loadAssets();
  }

  // 开启图库
  Future<void> openGallery() async {
    var status = await Permission.photos.status;
    if (status == PermissionStatus.granted) {
      List<AssetEntity>? pickList = await ImagePickAssets.pick();
      if (pickList != null && pickList.isNotEmpty) {
        await saveAndRefreshAssets(pickList);
      }
    } else {
      ToastUtil.show("请先开启权限");
    }
  }

  // 开启相机
  Future<void> openCamera() async {
    final entity = await CameraPicker.pickFromCamera(
      Get.context!,
      pickerConfig: const CameraPickerConfig(),
    );
    if (entity != null) {
      await saveAndRefreshAssets([entity]);
    }
  }
}
