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 '../../../../common/widgets/index.dart';
import '../bbs_mixin.dart';
import 'index.dart';

class PublishSubjectController extends GetxController with BBSCommons {
  PublishSubjectController();

  final state = PublishSubjectState();
  /// 帖子标题
  final TextEditingController subjectTitleInputController = TextEditingController();
  final FocusNode subjectTitleInputNode = FocusNode();
  /// 帖子内容
  final TextEditingController subjectContentInputController = TextEditingController();
  final FocusNode subjectContentInputNode = FocusNode();

  /// 帖子摘要
  final TextEditingController subjectSummaryInputController = TextEditingController();
  final FocusNode subjectSummaryInputNode = FocusNode();

  /// 板块对象
  SectionInfoList? sectionInfo;
  List<String> categoryList = []; // 帖子分类  sectionInfo.typeCategory 
  List<String> subjectTypeList = []; // 帖子类型 sectionInfo.subjectType

  final Uuid _uuid = const Uuid();
  String subjectId = '';

 /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    subjectId = _uuid.v1();
    super.onInit();
  }
  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map == null || map["sectionInfo"] == null ||  map["sectionInfo"] is! SectionInfoList ) {
      Loading.toast('args_error'.tr);
      Get.back();
      return;
    }
    sectionInfo = map["sectionInfo"];
    if (sectionInfo?.typeCategory?.isNotEmpty == true) {
      categoryList = sectionInfo?.typeCategory?.split("|") ?? [];
    }
    if (sectionInfo?.subjectType?.isNotEmpty == true) {
      subjectTypeList = sectionInfo?.subjectType?.split("|") ?? [];
    }
    if (categoryList.isNotEmpty) {
      state.category = categoryList[0];
    }
    if (subjectTypeList.isNotEmpty) {
      state.subjectType = subjectTypeList[0];
    }
    super.onReady();
  }

  /// 发表帖子
  void postSubject() {
    final title = subjectTitleInputController.text;
    if (title.isEmpty) {
      Loading.toast('bbs_subject_publish_title_not_empty'.tr);
      subjectTitleInputNode.requestFocus();
      return;
    }
    final content = subjectContentInputController.text;
    if (content.isEmpty) {
      Loading.toast('bbs_subject_publish_content_not_empty'.tr);
      subjectContentInputNode.requestFocus();
      return;
    }
    if (state.imageMap.isNotEmpty) {
      // 判断是否有正在上传的图片
      bool hasLoading = false;
      for (var element in state.imageMap.values) {
        if (element.fileId == null || element.fileId?.isEmpty == true) {
          hasLoading = true;
        }
      }
      if (hasLoading) {
        Loading.toast('bbs_subject_reply_image_loading'.tr);
        return;
      }
    }

    _post(title, content);
    
  }

  Future<void> _post(String title, String content) async {
    subjectTitleInputNode.unfocus(); // 关闭输入法
    subjectContentInputNode.unfocus(); // 关闭输入法
    subjectSummaryInputNode.unfocus(); // 关闭输入法
    content = formatToHtml(content);
    OLogger.d("content _formatToHtml :$content");
    content += addImagesToContent(state.imageMap.values.toList());
    OLogger.d("content html and image:$content");
    var deviceType = SharedPreferenceService.to.getString(SharedPreferenceService.currentDeviceTypeKey);
    String machineName = await machineInfo();
    var post = SubjectInfo(
        sectionId: sectionInfo?.id,
        id: subjectId,
        title: title,
        content: content,
        type: state.subjectType,
        typeCategory: state.category,
        summary: subjectSummaryInputController.text,
        anonymousSubject: state.anonymousSubject,
        machineName: machineName,
        systemType: deviceType,
    );
    IdData? iddata = await BBSAssembleControlService.to.subjectPublish(post);
    if (iddata != null) {
      Get.back(result: iddata.id);
      Loading.toast('bbs_subject_publish_success'.tr);
    }
  }
 

  /// 选择图片
  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.imageMap.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.imageMap.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.imageMap[path] = item;
      OLogger.d('已经刷新！');
      IdData? iddata = await BBSAssembleControlService.to
          .uploadAttachment(subjectId, File(path));
      if (iddata != null) {
        var replyItem = state.imageMap[path];
        if (replyItem != null) {
          replyItem.fileId = iddata.id;
          state.imageMap[path] = replyItem;
        }
      } else {
        state.imageMap.remove(path);
      }
    }
  }


  void showMoreSubjectInfoView() {
    state.openMore = !state.openMore;
  }

  /// 切换匿名发帖
  void changeAnonymousSubject(bool value) {
     state.anonymousSubject = value;
  }

  /// 切换分类
  void changeCategory() {
    final context = Get.context;
    if (context == null) {
      return ;
    }
    O2UI.showBottomSheetLongList(context, categoryList.map((e) => ListTile(
      title: Text(e),
      onTap: () {
         Navigator.pop(context);
         state.category = e;
      },
     )).toList());
  }
  /// 切换类型
  void changeSubjectType() {
    final context = Get.context;
    if (context == null) {
      return ;
    }
    O2UI.showBottomSheetLongList(context, subjectTypeList.map((e) => ListTile(
      title: Text(e),
      onTap: () {
         Navigator.pop(context);
         state.subjectType = e;
      },
     )).toList());
  }

  
}
