import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/utils/index.dart';

import '../../../../../../common/api/index.dart';
import '../../../../../../common/models/process/index.dart';
import '../../../../../../common/values/index.dart';
import '../../../../../common/handwriting/index.dart';
import 'index.dart';

class QuickprocessingController extends GetxController {
  QuickprocessingController();

  final state = QuickprocessingState();
  final TextEditingController opinionInputController = TextEditingController();
  List<TaskData> taskList = [];

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null && map['taskList'] != null && map['taskList'] is List) {
      taskList
        ..clear()
        ..addAll(map['taskList']);
    }
    loadTaskData();
    loadMyIdeas();
    super.onReady();
  }

  /// 常用意见
  Future<void> loadMyIdeas() async {
    var myApp =
        await OrganizationPersonalService.to.getMyCustomData(O2.myCustomIdea);
    if (myApp != null && myApp.isNotEmpty) {
      Map<String, dynamic> m = O2Utils.parseStringToJson(myApp);
      List<dynamic> myIdes = m['ideas'] ?? [];
      if (myIdes.isEmpty) {
        return;
      }
      for (var element in myIdes) {
        if (element == null) {
          continue;
        }
        final idea = element.toString();
        if (idea.isEmpty) {
          continue;
        }
        state.ideaList.add(idea);
      }
    }
  }

  /// 待办任务对象
  Future<void> loadTaskData() async {
    if (taskList.isEmpty) {
      OLogger.e('没有待办数据，taskList is empty!!!!!');
      return;
    }
    Loading.show();
    final data = await ProcessSurfaceService.to.getTaskData(taskList[0].id!);
    if (data != null) {
      Loading.dismiss();
      state.task.value = data;
      final firstRoute =
          (data.routeNameList ?? []).firstWhereOrNull((element) => true) ?? '';
      state.routeName = firstRoute;
    }
  }

  /// 处理完成 返回 true  上级页面需要刷新
  void processFinish() {
    Get.back(result: true);
  }

  void cancel() {
    Get.back();
  }

  /// 选择路由
  void chooseRoute(String routeName) {
    state.routeName = routeName;
  }

  /// 添加常用意见
  void addOpinion(String idea) {
    final opinion = opinionInputController.text;
    if (opinion.isNotEmpty) {
      opinionInputController.text = '$opinion, $idea';
    } else {
      opinionInputController.text = idea;
    }
  }

  Future<void> openHandwriting() async {
    final result = await HandwritingPage.startWriting();
    if (result != null && result is String) {
      OLogger.d('获取到手写图片：$result');
      state.handwritingImagePath.value = result;
    }
  }

  void deleteHandwritingFile() {
    state.handwritingImagePath.value = null;
  }

  /// 继续流转
  Future<void> submitProcess() async {
    if (taskList.isEmpty) {
      Loading.toast('process_task_quick_process_empty_list'.tr);
      return;
    }
    final opinion = opinionInputController.text;
    final routeName = state.routeName;
    if (routeName.isEmpty) {
      Loading.toast('process_task_quick_process_empty_route'.tr);
      return;
    }
    Loading.show();
    final filePath = state.handwritingImagePath.value;
    File? file;
    if (filePath != null && filePath.isNotEmpty) {
      file = File(filePath);
    }
    int errorNumber = 0;
    for (var task in taskList) {
      // 添加决策和意见
      task.routeName = routeName;
      task.opinion = opinion;
      // 如果有手写意见的图片，先上传图片
      if (file != null) {
        int len = await file.length();
        OLogger.d('文件大小： $len');
        final fileId = await ProcessSurfaceService.to
            .uploadAttachment(task.work!, "\$mediaOpinion", file);
        if (fileId != null && fileId.id != null) {
          task.mediaOpinion = fileId.id;
        }
      }
      // 提交流程
      final id = await ProcessSurfaceService.to.processing(task);
      if (id != null && id.id != null) {
        OLogger.i('快速提交成功，id ${id.id} $routeName ');
      } else {
        errorNumber++;
      }
    }
    if (errorNumber > 0) {
      Loading.showError(
          'process_task_quick_process_submit_error'.trArgs(['$errorNumber']));
    } else {
      Loading.dismiss();
    }
    processFinish();
  }
}
