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

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/utils/index.dart';
import 'index.dart';

enum CreateFormStartType { none, cms, process }

class CreateFormController extends GetxController {
  CreateFormController();

  final state = CreateFormState();

  final TextEditingController inputController = TextEditingController();

  CmsCategoryData? _category;
  dynamic _cmsData; // 文档数据

  ProcessData? _process;

  // 工作数据 工作创建的时候带入的 data 数据
  dynamic _processWorkData;

  // 启动流程工作后返回job
  StartProcessCallbackJob? _callback;

  CreateFormStartType startType = CreateFormStartType.none; // 启动类型

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    var map = Get.arguments;
    if (map != null) {
      var ignoreTitle = map['ignoreTitle'];
      if (ignoreTitle != null && ignoreTitle is bool) {
        state.ignoreTitle = ignoreTitle;
      }
      final category = map['category'];
      final process = map['process'];
      if (category != null && category is CmsCategoryData) {
        _category = category;
        state.title =
            '${'cms_create_document_title'.tr} - ${category.categoryName}';
        _cmsData = map['cmsData'];
        startType = CreateFormStartType.cms;
      } else if (process != null && process is ProcessData) {
        _process = process;
        state.title = '${'process_create_title'.tr} - ${process.name}';
        startType = CreateFormStartType.process;
        _processWorkData = map['workData'];
      }
      final callback = map['callback'];
      if (callback is StartProcessCallbackJob) {
        _callback = callback;
      }
    }
    loadIdentity();
    super.onReady();
  }

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

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

  void loadIdentity() async {
    Loading.show();
    state.identityList.clear();
    var person = await OrganizationPersonalService.to.person();
    if (person == null) {
      Get.back();
      Loading.showError('process_no_identity'.tr);
      return;
    }
    Loading.dismiss();
    if (person.woIdentityList == null ||
        person.woIdentityList?.isEmpty == true) {
      Get.back();
      Loading.showError('process_no_identity'.tr);
      return;
    }
    state.identityList.addAll(person.woIdentityList!);
    state.identity = person.woIdentityList?[0].distinguishedName ?? '';
    if (state.ignoreTitle && state.identityList.length == 1) {
      start();
    }
  }

  void chooseIdentity(String distinguishedName) {
    OLogger.d('选择了身份 $distinguishedName');
    state.identity = distinguishedName;
  }

  void clickSave() {
    if (!state.ignoreTitle) {
      var title = inputController.text;
      if (title.isEmpty) {
        Loading.toast('cms_create_document_title_not_empty'.tr);
        return;
      }
    }
    if (state.identity.isEmpty) {
      Loading.toast('cms_create_document_identity_not_empty'.tr);
      return;
    }
    start();
  }

  void start() {
    // 直接创建
    if (startType == CreateFormStartType.cms) {
      createDocument();
    } else if (startType == CreateFormStartType.process) {
      createProcess();
    } else {
      OLogger.e('参数不正确！startType： $startType');
    }
  }

  ///
  /// 创建cms文档
  ///
  void createDocument() async {
    if (_category == null) {
      Loading.toast('cms_create_document_no_args'.tr);
      return;
    }
    Loading.show();
    var title = inputController.text;
    var document = <String, dynamic>{};
    document['title'] = title;
    document['appId'] = _category?.appId;
    document['categoryId'] = _category?.id;
    document['categoryAlias'] = _category?.categoryAlias;
    document['categoryName'] = _category?.categoryName;
    document['creatorIdentity'] = state.identity;
    document['docStatus'] = "draft";
    document['isNewDocument'] = true;
    if (_cmsData != null) {
      document['docData'] = _cmsData;
    }
    if (_category?.workflowFlag != null &&
        _category?.workflowFlag?.isNotEmpty == true) {
      // 启动流程
      var body = <String, dynamic>{};
      body['title'] = title;
      body['identity'] = state.identity;
      body['data'] = {'cmsDocument': document};
      var list = await ProcessSurfaceService.to
          .startProcess(_category!.workflowFlag!, body);
      if (list != null) {
        Loading.dismiss();
        CreateFormBackResult? result;
        if (list.isNotEmpty &&
            list[0].taskList != null &&
            list[0].taskList!.isNotEmpty) {
          var task = list[0].taskList![0];
          result = CreateFormBackResult(CreateFormBackResultType.processWork,
              processWork: CreateFormBackProcessWork(
                  work: task.work,
                  job: task.job,
                  title: task.title ??
                      'process_work_no_title'.trArgs(['${task.processName}'])));
        } else {
          // 当前没有可打开的工作
          result = null;
        }
        Get.back(result: result);
      }
    } else {
      OLogger.d('doc data: $document');
      var id = await CmsAssembleControlService.to.documentPost(document);
      if (id != null && id.id != null) {
        Loading.dismiss();
        CreateFormBackResult result = CreateFormBackResult(
            CreateFormBackResultType.cmsDoc,
            cmsDoc: CreateFormBackCmsDoc(id: id.id!, title: title));
        Get.back(result: result);
      }
    }
  }

  ///
  /// 创建流程工作
  ///
  void createProcess() async {
    if (_process == null || _process?.id == null) {
      Loading.toast('process_create_work_no_args'.tr);
      return;
    }
    Loading.show();
    var title = inputController.text;
    // 启动流程
    var body = <String, dynamic>{};
    body['title'] = title;
    body['identity'] = state.identity;
    if (_processWorkData != null) {
      body['data'] = _processWorkData;
    }
    if (_process?.defaultStartMode == 'draft') {
      // 草稿模式
      var draft =
          await ProcessSurfaceService.to.startDraft(_process!.id!, body);
      if (draft != null) {
        Loading.dismiss();
        var work = draft.work;
        CreateFormBackResult? result;
        if (work != null) {
          // 打开草稿
          result = CreateFormBackResult(CreateFormBackResultType.processDraft, processDraft: work);
        } else {
          result = null;
        }
        Get.back(result: result);
      }
    } else {
      var list =
          await ProcessSurfaceService.to.startProcess(_process!.id!, body);
      if (list != null) {
        Loading.dismiss();
        // 有 callback  返回数据
        if (list.isNotEmpty && list[0].job != null && _callback != null) {
          _callback!(list[0].job!);
        }
        // 打开工作
        CreateFormBackResult? result;
        if (list.isNotEmpty &&
            list[0].taskList != null &&
            list[0].taskList!.isNotEmpty) {
          var task = list[0].taskList![0];
          result = CreateFormBackResult(CreateFormBackResultType.processWork,
                processWork: CreateFormBackProcessWork(
                    work: task.work,
                    job: task.job,
                    title: task.title ??
                        'process_work_no_title'.trArgs(['${task.processName}'])));
          } else {
            // 当前没有可打开的工作
            result = null;
          }
          Get.back(result: result);
      }
    }
  }
}
