import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../../../../common/widgets/index.dart';
import '../../../common/create_form/index.dart';
import '../../../common/process_webview/index.dart';
import 'index.dart';



class ExceptionDataController extends GetxController {
  ExceptionDataController();

  final state = ExceptionDataState();
  // 当前页码
  var page = 1;
  // 防止重复刷新
  bool isLoading = false;
  // 刷新控件的 controller
  final refreshController = RefreshController();
  // 配置文件
  AttendanceV2Config? config;

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    loadConfig();
    refreshMyAppealList();
    super.onReady();
  }

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

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

  loadConfig() async {
    final result = await AttendanceAssembleControlService.to.config();
    config = result;
    if (config?.appealEnable == true) {
      state.enableProcess = true;
    }
  }

  /// 刷新列表数据
  refreshMyAppealList() async {
    if (isLoading) return;
    page = 1;
    isLoading = true;
    final result =
        await AttendanceAssembleControlService.to.myAppealListByPage(page);
    state.myAppealList.clear();
    if (result != null) {
      state.myAppealList.addAll(result);
    }
    refreshController.refreshCompleted();
    state.hasMoreData = (result?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }

  /// 加载更多数据
  loadMoreMyAppealList() async {
    if (isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    isLoading = true;
    page++;
    final result =
        await AttendanceAssembleControlService.to.myAppealListByPage(page);
    if (result != null) {
      state.myAppealList.addAll(result);
    }
    refreshController.loadComplete();
    state.hasMoreData = (result?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }

  /// 启动流程 发起工作
  _clickStartProcess(AttendanceV2Appeal info) async {
    OLogger.d('点击了启动流程');
    final result = await AttendanceAssembleControlService.to.checkAppealEnable(info.id!);
    if (result?.value == true && config?.processId != null) {
      // 考勤配置的流程
      final process = await ProcessSurfaceService.to.getProcess(config!.processId!);
      if (process == null) {
        Loading.toast('args_error'.tr);
        return;
      }
      final workData = {
        "appealId": info.id, 
        "record": info.record
      };
      CreateFormPage.startProcess(true, process: process, callback:(jobId) => _updateAppealStartStatus(jobId, info.id!), workData: workData);
    }
  }
  /// 启动成功后更新数据状态
  _updateAppealStartStatus(String jobId, String id) async {
    OLogger.d('开始更新数据，id $id, job: $jobId');
    final result = await AttendanceAssembleControlService.to.appealStartProcess(id, jobId);
    OLogger.d('更新数据成功！ ${result?.value}');
    refreshMyAppealList();
  }
  /// 查看工作
  _clickOpenJob(AttendanceV2Appeal info) async {
    OLogger.d('点击了打开流程');
    final result = await ProcessWebviewPage.openJob(info.jobId ?? '');
    if (result == null) {
      _showRestStatusDialog(info);
    }
    // if (info.jobId?.isNotEmpty == true) {
    //   try {
    //     final result = await ProcessSurfaceService.to.getWorkByJob(info.jobId!);
    //     _resolveResult(result, info);
    //   } catch (e) {
    //     OLogger.e('错误', e);
    //     _resolveResult(null, info);
    //   }
    // }
  }
  _resolveResult(WorkReference? result, AttendanceV2Appeal info) {
      final count = (result?.workCompletedList?.length ?? 0) + (result?.workList?.length ?? 0);
      if (result == null || count < 1) {
        _showRestStatusDialog(info);
        return;
      }
      Work? work;
      if (result.workList?.isNotEmpty == true) {
        work = result.workList![0];
      }
      if (work == null && result.workCompletedList?.isNotEmpty == true) {
        work =  result.workCompletedList![0];
      }
      if (work != null) {
        ProcessWebviewPage.open(work.id!, title: work.title??'');
      }
  }
  /// confirm 确认是否还原
  _showRestStatusDialog(AttendanceV2Appeal info) {
    final context = Get.context;
    if (context == null) {
      return;
    }
    O2UI.showConfirm(context, 'attendance_appeal_reset_status_msg'.tr, okPressed: ()=>_resetStatus(info));
  }
  /// 还原数据状态
  _resetStatus(AttendanceV2Appeal info) async {
    final result = await AttendanceAssembleControlService.to.appealRestStatus(info.id!);
    OLogger.d('还原数据状态成功！ ${result?.value}');
    refreshMyAppealList();
  }

  /// 点击 item 显示操作
  void showOperationMenu(AttendanceV2Appeal info) {
    final context = Get.context;
    if (context == null) {
      return;
    }
    if (!state.enableProcess) {
      return;
    }
    if (info.status == AttendanceV2AppealStatusEnum.StatusAdminDeal.key) {
      return ;
    }
    // 初始化状态 启动流程
    if (info.status == AttendanceV2AppealStatusEnum.StatusInit.key) {
      var result = info.record?.resultText();
      if (info.record?.fieldWork == true) {
        result = 'attendance_result_fieldWork'.tr;
      }
      final content = '${info.recordDate} $result';
      O2UI.showConfirm(context, 'attendance_appeal_start_process_content'.trArgs([content]), okText: 'attendance_appeal_start_process'.tr, okPressed: () => _clickStartProcess(info));
    } else if (info.jobId?.isNotEmpty == true) {
      // 有关联流程，查看流程
     _clickOpenJob(info);
    }
    
  }
}
