import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:uuid/uuid.dart';

import '../../../../../common/api/index.dart';
import '../../../../../common/models/index.dart';
import '../../../../../common/services/index.dart';
import '../../../../../common/utils/index.dart';
import '../../../../../common/values/index.dart';
import '../../bbs_mixin.dart';
import 'index.dart';

class SubjectReplyController extends GetxController with BBSCommons {
  SubjectReplyController();

  final state = SubjectReplyState();
  String subjectId = '';
 

  final TextEditingController replyInputController = TextEditingController();
  final FocusNode replyInputNode = FocusNode();

  final Uuid _uuid = const Uuid();
  String replyId = '';
  String replyParentId = '';

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    replyId = _uuid.v1();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    var map = Get.arguments;
    if (map != null) {
      subjectId = map["subjectId"] ?? "";
      replyParentId = map["replyParentId"] ?? "";
      String replyHint = map["replyHint"] ?? "";
      if (replyHint.isEmpty) {
        replyHint = 'bbs_subject_reply_hint'.tr;
      }
      state.replyHintObs = replyHint;
      OLogger.d("主题id: $subjectId ");
    }
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  void replay() {
    var content = replyInputController.text;
    if (content.isEmpty) {
      Loading.toast('bbs_subject_reply_hint'.tr);
      return;
    }
    if (state.replyImageMap.isNotEmpty) {
      // 判断是否有正在上传的图片
      bool hasLoading = false;
      for (var element in state.replyImageMap.values) {
        if (element.fileId == null || element.fileId?.isEmpty == true) {
          hasLoading = true;
        }
      }
      if (hasLoading) {
        Loading.toast('bbs_subject_reply_image_loading'.tr);
        return;
      }
    }
    _replayPost(content);
  }

  /// 选择图片
  void addImage() {
    _pickImageAndUpload(ImageSource.gallery);
  }
  /// 拍照
  void takePhoto() {
    _pickImageAndUpload(ImageSource.camera);
  }

  /// 点击图片 删除
  void clickImageItem(ReplyImageItem item) {
    if (item.fileId == null || item.fileId?.isEmpty == true) {
      OLogger.e("还在上传，不处理！");
    } else {
      String path = item.fileLocalPath ?? '';
      if (path.isNotEmpty) {
        state.replyImageMap.remove(path);
      }
    }
  }

  Future<void> _pickImageAndUpload(ImageSource source) async {
    if (ImageSource.camera == source && !await O2Utils.cameraPermission()){
      return;
    }
     XFile? file = await pickImageByType(source);
     if (file != null) {
      OLogger.d("文件：${file.path}");
      Size size = await getLocalImageSize(file.path);
      _uploadImage(file.path, size.width.toInt(), size.height.toInt());
    }
  }
  

  Future<void> _uploadImage(String path, int width, int height) async {
    if (!state.replyImageMap.containsKey(path)) {
      ReplyImageItem item =
          ReplyImageItem(fileLocalPath: path, width: width, height: height);
      if (width > O2.BBS_IMAGE_MAX_WIDTH) {
        double ratio = (width / O2.BBS_IMAGE_MAX_WIDTH);
        int showHeight = height ~/ ratio;
        int showWidth = O2.BBS_IMAGE_MAX_WIDTH;
        item.showHeight = showHeight;
        item.showWidth = showWidth;
      } else {
        item.showHeight = height;
        item.showWidth = width;
      }
      state.replyImageMap[path] = item;
      OLogger.d('已经刷新！');
      IdData? iddata = await BBSAssembleControlService.to
          .uploadAttachment(replyId, File(path));
      if (iddata != null) {
        var replyItem = state.replyImageMap[path];
        if (replyItem != null) {
          replyItem.fileId = iddata.id;
          state.replyImageMap[path] = replyItem;
        }
      } else {
        state.replyImageMap.remove(path);
      }
    }
  }

  Future<void> _replayPost(String content) async {
    replyInputNode.unfocus(); // 关闭输入法
    content = formatToHtml(content);
    OLogger.d("content _formatToHtml :$content");
    content += addImagesToContent(state.replyImageMap.values.toList());
    OLogger.d("content html and image:$content");
    var deviceType = SharedPreferenceService.to
        .getString(SharedPreferenceService.currentDeviceTypeKey);
    String machineName = await machineInfo();
    var post = ReplyFormJson(
        id: replyId,
        content: content,
        subjectId: subjectId,
        replyMachineName: machineName,
        replySystemName: deviceType);
    if (replyParentId.isNotEmpty) {
      post.parentId = replyParentId;
    }
    IdData? iddata = await BBSAssembleControlService.to.replaySubject(post);
    if (iddata != null) {
      Get.back(result: iddata.id);
    }
  }
 
   
}
