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

import '../../../../../../common/api/index.dart';
import '../../../../../../common/models/index.dart';
import '../../../../../../common/utils/index.dart';
import '../../../../../apps/process/process_picker/index.dart';
import '../../../../contact/contact_picker/index.dart';
import 'index.dart';

class EmpowerCreateController extends GetxController {
  EmpowerCreateController();

  final state = EmpowerCreateState();


  ProcessData? _process;
  ProcessApplicationData? _app;
  O2Identity? _person;

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    state.typeList.add(EmpowerTypeData(key: 'all', name: 'account_safe_empower_type_all'.tr));
    state.typeList.add(EmpowerTypeData(key: 'application', name: 'account_safe_empower_type_app'.tr));
    state.typeList.add(EmpowerTypeData(key: 'process', name: 'account_safe_empower_type_process'.tr));
    state.type = 'all';
    loadIdentity();
    super.onReady();
  }

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

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

  loadIdentity() async {
    Loading.show();
    final person = await OrganizationPersonalService.to.person();
    Loading.dismiss();
    if (person != null && person.woIdentityList != null) {
      state.identityList.clear();
      state.identityList.addAll(person.woIdentityList!);
      state.identity = person.woIdentityList?[0].distinguishedName ?? '';
    }
     
  }

  void clickSave() async {
    final identity = state.identity;
    if ( identity.isEmpty) {
      Loading.showError('account_safe_empower_form_empty_identity'.tr);
      return;
    }
    final toPerson = _person?.distinguishedName;
    if (toPerson == null || toPerson.isEmpty) {
      Loading.showError('account_safe_empower_form_empty_to_person'.tr);
      return;
    }
    final startTime = state.startTime;
    if (  startTime.isEmpty) {
      Loading.showError('account_safe_empower_form_empty_start_time'.tr);
      return;
    }
    final endTime = state.endTime;
    if (  endTime.isEmpty) {
      Loading.showError('account_safe_empower_form_empty_end_time'.tr);
      return;
    }
    if (startTime.compareTo(endTime) > 0) {
      Loading.showError('account_safe_empower_form_start_end_time_over'.tr);
      return;
    }
    final type = state.type;
    final app = _app?.id;
    final appName = _app?.name;
    final process = _process?.id;
    final processName = _process?.name;
    OLogger.d("post empower $toPerson $identity $startTime $endTime $type $app $appName $process $processName");
    if (type == 'application' && _app == null) {
      Loading.showError('account_safe_empower_form_empty_app'.tr);
      return;
    }
    if (type == 'process' && _process == null) {
      Loading.showError('account_safe_empower_form_empty_process'.tr);
      return;
    }
    final body = EmpowerData(fromIdentity: identity, toIdentity: toPerson, startTime: '$startTime:00', completedTime: '$endTime:00', type: type, enable: true);
    if (type == 'application') {
      body.application = _app?.id;
      body.applicationAlias = _app?.alias;
      body.applicationName = _app?.name;
    } else if (type == 'process') {
      body.process = _process?.id;
      body.processAlias = _process?.alias;
      body.processName = _process?.name;
      body.edition = _process?.edition;
    }
    final result = await OrganizationPersonalService.to.empowerCreate(body);
    if (result != null) {
        Get.back();
        Loading.toast('success'.tr);
      }
  }
  void clickIdentity(String distinguishedName) {
    state.identity = distinguishedName;
  }
  /// 选择委托人
  clickChooseToPerson() async {
    final person = await ContactPickerPage.startPicker([ContactPickMode.identityPicker], maxNumber: 1);
    if (person != null && person is ContactPickerResult) {
      final identities = person.identities ?? [];
      if (identities.isNotEmpty) {
         _person = identities.first;
         state.toPerson = _person?.name ?? '';
      }
    }
  }

  /// 选择开始时间
  void clickChooseStartTime() {
    chooseDateTime(true);
  }
  void clickChooseEndTime(){
    chooseDateTime(false);
  }

  /// 日期时间选择器 
  /// 
  /// 开始时间 和 结束时间 选择使用
  chooseDateTime(bool isStartTime) async {
    final context = Get.context;
    if (context == null) {
      OLogger.e('错误，没有 context！');
      return;
    }
    DateTime initDate = DateTime.now();
    TimeOfDay initTime = TimeOfDay(hour: initDate.hour, minute: initDate.minute);
    // 日期选择
    final result = await showDatePicker(
        context: context,
        initialDate: initDate,
        firstDate: initDate.addYears(-10),
        lastDate: initDate.addYears(10));
    if (result != null) {
      var date = result.ymd();
      final context2 = Get.context;
      if (context2 == null) {
        OLogger.e('错误，没有 context！');
        return;
      }
      // ignore: use_build_context_synchronously
      final startTime = await showTimePicker(context: context2, initialTime: initTime);
      if (startTime != null) {
         final startHour =
            startTime.hour > 9 ? '${startTime.hour}' : '0${startTime.hour}';
        final startMinute = startTime.minute > 9
            ? '${startTime.minute}'
            : '0${startTime.minute}';
        date = '$date $startHour:$startMinute';
        if (isStartTime) {
          state.startTime = date;
        } else {
          state.endTime = date;
        }
      }
    }
  }

  void clickType(EmpowerTypeData type) {
    state.type = type.key;
  }
  
  // 选择流程应用
  clickChooseApplication() async {
    final result = await ProcessPickerPage.startPicker(ProcessPickerMode.application);
    if (result != null && result is ProcessApplicationData) {
       _app = result;
       state.appName = result.name ?? '';
    }
  }
  // 选择流程
  clickChooseProcess() async {
    final result = await ProcessPickerPage.startPicker(ProcessPickerMode.process);
    if (result != null && result is ProcessData) {
       _process = result;
       state.processName = result.name ?? '';
    }
  }
}
