import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/common_util.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/components/classify_data_selector/classify_data_selector.dart';
import 'package:flyinsono/lab/components/lab_dialog.dart';
import 'package:flyinsono/lab/components/view_mode_switcher/view_mode_switcher.dart';
import 'package:flyinsono/lab/manager/interfaces/project.dart';
import 'package:flyinsono/lab/manager/page_manager.dart';
import 'package:flyinsono/lab/mixin/tab_hook_mixin.dart';
import 'package:flyinsono/lab/mock_data/mock_rpc.dart';
import 'package:flyinsono/lab/pages/lab_create_project/view.dart';
import 'package:flyinsono/lab/pages/lab_data/controller.dart';
import 'package:flyinsono/lab/pages/lab_project/widgets/look_project_member_dialog.dart';
import 'package:flyinsono/lab/pages/lab_project/widgets/project_member_dialog.dart';
import 'package:flyinsono/lab/pages/lab_record_info/widgets/alert_dialog.dart';
import 'package:flyinsono/lab/router/lab_route_names.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/index.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:get/get.dart';
import 'index.dart';

class LabProjectController extends GetxController with TabHookMixin {
  LabProjectController({
    required this.tabHashCode,
  });
  @override
  final int tabHashCode;
  static const labProjectListId = "lab_project_list";
  static const viewModeSwitcherId = "view_mode_switcher";
  static const projectDataPanelId = "project_data_panel";
  static const projectDataViewId = "project_data_view";
  static const projectMember = "project_member";
  static const projectSelectMember = "project_select_member";
  static const projectTitle = "project_title";
  static const labMainContent = "lab_main_content";
  static const projectTimeLine = "project_time_line";

  final state = LabProjectState();

  /// 项目成员搜索栏输入控制器
  final projectMemberSearchInputController = TextEditingController();

  /// 项目搜索栏输入控制器
  final projectSearchInputController = TextEditingController();

  /// 项目接口
  final projectService = Get.find<IProjectManager>();

  /// 项目列表
  List<ClassifyData<ProjectModel>> projectClassifyData = [];
  int selectedClassifyIndex = 0;
  int selectedProjectIndex = 0;
  bool isProjectListLoading = false;
  bool isCollapseTimeLine = false; // 是否收起时间轴
  /// 我创建的|我参与的列表
  List<ProjectModel> get currentProjectList =>
      projectClassifyData[selectedClassifyIndex].data;

  /// 当前选中项目
  ProjectModel? get currentSelectedProjectModel => projectClassifyData.length ==
              0 ||
          projectClassifyData[selectedClassifyIndex].data.length == 0
      ? null
      : projectClassifyData[selectedClassifyIndex].data[selectedProjectIndex];

  /// 项目名称
  String get projectName => currentSelectedProjectModel?.name ?? '';

  /// 项目code
  String get projectCode => currentSelectedProjectModel?.id ?? '';

  /// 项目简介
  String? get projectIntroduction =>
      currentSelectedProjectModel?.projectIntroduction;

  /// 项目Type
  OrganizationPatientTypeEnum projectType = OrganizationPatientTypeEnum.Person;

  String get projectTypeName =>
      projectType == OrganizationPatientTypeEnum.Person ? "人用科研" : "小动物科研";
  bool get isCanCreateProject =>
      Store.user.hasFeature(FeatureKeys.CreateProjectAuthority);
  // 轮询定时器（用于获取当前选中的任务详情进度）
  Timer? timer;

  /// 项目数据（病人列表）
  List<PatientModel> patientData = [];
  bool isProjectDataLoading = false;

  /// 所有项目成员 - 未排序
  List<MemberModel> allMemberModelList = [];

  /// 所有能邀请的项目成员
  List<MemberModel> get allCanInviteMemberModelList {
    return allMemberModelList
        .where((allMember) => !selectMemberModelListByProjectDetail
            .any((selectMember) => allMember.code == selectMember.code))
        .where((element) =>
            element.name?.toLowerCase().contains(
                projectMemberSearchInputController.text.toLowerCase()) ??
            false)
        .toList();
  }

  /// 所有能移除的项目成员
  List<MemberModel> get allCanRemoveMemberModelList {
    return allMemberModelList
        .where((allMember) => selectMemberModelListByProjectDetail
            .any((selectMember) => allMember.code == selectMember.code))
        .toList();
  }

  /// 所有项目成员 - 已排序&筛选搜索
  List<MemberModel> get allMemberModelListSort =>
      projectMemberSearchInputController.text != ""
          ? filterMemberList(allMemberModelList)
          : allCanRemoveMemberModelList + allCanInviteMemberModelList;

  bool get isShowPullDownButton => selectedClassifyIndex == 0;

  /// 选中的项目成员
  List<MemberModel> selectMemberModelList = [];

  /// 选中的项目成员根据项目详情
  List<MemberModel> selectMemberModelListByProjectDetail = [];

  /// 项目时间轴列表
  List<TimeAxisDetail> taskList = [];

  // 数据展示模式
  ViewMode viewMode = ViewMode.list;

  // 是否倒序
  bool isReverse = true;

  void changeViewMode(ViewMode mode) async {
    //验证是否有权限或者项目是否有效
    bool validateResult = await projectService.validateResearchProjectAuthAsync(
            projectCode: projectCode) ??
        false;
    if (validateResult) {
      viewMode = mode;
      update([viewModeSwitcherId, projectDataViewId]);
    } else {
      selectedClassifyIndex = 0;
      selectedProjectIndex = 0;
      initProjectList();
    }
  }

  void onProjectClick(int classifyIndex, int itemIndex) {
    selectedClassifyIndex = classifyIndex;
    selectedProjectIndex = itemIndex;
    update([labProjectListId, projectTitle]);
    updateProjectData(projectCode);
  }

  void onChangeMember(MemberModel member) {
    MemberModel? select = selectMemberModelList
        .firstWhereOrNull((element) => element.code == member.code);
    if (select != null) {
      selectMemberModelList.remove(select);
    } else {
      selectMemberModelList.add(member);
    }
    update([projectMember]);
  }

  /// 创建或者编辑项目
  void createOrUpdateResearchProject(bool isCreate) async {
    await Get.dialog(
      LabAlertDialog(
        title: isCreate ? "创建项目" : "编辑项目",
        contentVerticalPadding: 10,
        contentHorizontalPadding: 20,
        content: LabCreateProjectPage(
          projectModel: isCreate ? null : currentSelectedProjectModel,
        ),
      ),
      barrierColor: LabColors.base100.withOpacity(0.1),
    );
    // if (result is bool && result) {
    //   await projectService.updateResearchProjectAsync(
    //     projectCode: projectCode,
    //     projectName: currentProjectName,
    //   );
    // }

    initProjectList();
  }

  void onSearchProject() {
    initProjectList();
  }

  /// 删除项目
  void deleteResearchProject() async {
    dynamic result = await Get.dialog(
      LabDialog(
        title: "删除项目",
        content: "确定要删除当前所选项目？",
      ),
      barrierColor: LabColors.base100.withOpacity(0.1),
    );
    if (result is bool && result) {
      bool? deleteProject = await projectService.deleteResearchProjectRequest(
        projectCode: projectCode,
      );
      if (deleteProject ?? false) {
        selectedClassifyIndex = 0;
        selectedProjectIndex = 0;
        initProjectList();
        PromptBox.toast('删除完成');
      }
    }
  }

  void searchMember() {
    update([projectMember]);
  }

  void clickImportData() async {
    //验证是否有权限或者项目是否有效
    bool validateResult = await projectService.validateResearchProjectAuthAsync(
            projectCode: projectCode) ??
        false;
    if (validateResult) {
      PageManager.ins.openNewTab(LabRouteNames.Import, "导入数据",
          multiple: false, args: projectCode);
    } else {
      selectedClassifyIndex = 0;
      selectedProjectIndex = 0;
      initProjectList();
    }
  }

  void clickProjectDataItem(int index) async {
    //验证是否有权限或者项目是否有效
    bool validateResult = await projectService.validateResearchProjectAuthAsync(
            projectCode: projectCode) ??
        false;
    if (validateResult) {
      PageManager.ins.openTab(
        LabRouteNames.Data,
        args: LabDataActiveArguments(
          patientCode: patientData[index].code,
          projectCode: projectCode,
        ),
      );
    } else {
      selectedClassifyIndex = 0;
      selectedProjectIndex = 0;
      initProjectList();
    }
  }

  List<MemberModel> filterMemberList(memberList) {
    List<MemberModel> sortMembers = [];
    memberList.forEach((element) {
      if (element.name
          .toLowerCase()
          .contains(projectMemberSearchInputController.text.toLowerCase())) {
        sortMembers.add(element);
      }
    });
    return sortMembers;
  }

  List<List<MemberModel>> findDifference(
      List<MemberModel> array1, List<MemberModel> array2) {
    List<MemberModel> lessMembers = [];
    List<MemberModel> moreMembers = [];

    // 将数组2中不在数组1中的成员加入数组3
    for (var member in array2) {
      if (!array1.contains(member)) {
        moreMembers.add(member);
      }
    }

    // 将数组1中不在数组2中的成员加入数组4
    for (var member in array1) {
      if (!array2.contains(member)) {
        lessMembers.add(member);
      }
    }

    return [lessMembers, moreMembers];
  }

  // 邀请项目成员
  void projectMemberManagement() async {
    await initProjectMember();
    bool removeMember = false;
    bool inviteMember = false;
    bool? result = await Get.dialog(
      LabAlertDialog(
        title: "管理项目成员",
        content: Container(
          alignment: Alignment.center,
          margin: allMemberModelList.length == 0
              ? EdgeInsets.only(bottom: 50)
              : EdgeInsets.only(bottom: 0),
          child: allMemberModelList.length == 0
              ? NoDataWidget()
              : ProjectMemberDialog(),
        ),
        onConfirm: () {
          Get.back(result: true);
        },
      ),
      barrierColor: LabColors.base100.withOpacity(0.1),
    );

    if (result is bool && result) {
      List<String> memberCodes = [];
      List<String> removeCodes = [];
      // 查找差异
      var difference = findDifference(
          selectMemberModelListByProjectDetail, selectMemberModelList);
      List<MemberModel> lessMembers = difference[0];
      List<MemberModel> moreMembers = difference[1];
      moreMembers.forEach((element) {
        memberCodes.add(element.code!);
      });
      lessMembers.forEach((element) {
        removeCodes.add(element.code!);
      });

      if (removeCodes.length != 0)
        // 移除成员
        removeMember = await projectService.removeResearchProjectMembersAsync(
              projectCode: projectCode,
              memberCodes: removeCodes,
            ) ??
            false;
      if (memberCodes.length != 0)
        // 邀请成员
        inviteMember = await projectService.inviteResearchProjectMembersAsync(
              projectCode: projectCode,
              memberCodes: memberCodes,
            ) ??
            false;
      update([projectSelectMember]);
      initProjectList();

      if (inviteMember) {
        PromptBox.toast('成员邀请成功');
        return;
      }
      if (removeMember) {
        PromptBox.toast('成员移除成功');
      }
    }
  }

  // 查看项目成员
  void lookProjectMember() async {
    await Get.dialog(
      LabAlertDialog(
        title: "查看全部",
        content: Container(
          alignment: Alignment.center,
          margin: selectMemberModelList.length == 0
              ? EdgeInsets.only(bottom: 50)
              : EdgeInsets.only(bottom: 0),
          child: selectMemberModelList.length == 0
              ? NoDataWidget()
              : LookProjectMemberDialog(),
        ),
        // onConfirm: () {
        //   Get.back(result: true);
        // },
      ),
      barrierColor: LabColors.base100.withOpacity(0.1),
    );
  }

  /// 初始化项目列表
  void initProjectList() async {
    isProjectListLoading = true;
    isProjectDataLoading = true;

    update([labProjectListId, projectDataPanelId]);
    List<ResearchProjectBaseDTO>? createdResearchProjectList =
        await projectService.getResearchProjectListAsync(
      keyWord: projectSearchInputController.text,
      searchType: ResearchProjectSearchTypeEnum.ICreated,
    );
    List<ResearchProjectBaseDTO>? joinedResearchProjectList =
        await projectService.getResearchProjectListAsync(
      keyWord: projectSearchInputController.text,
      searchType: ResearchProjectSearchTypeEnum.IJoined,
    );
    List<ProjectModel> createdProjects = [];
    createdResearchProjectList?.forEach((element) {
      createdProjects.add(ProjectModel(
        id: element.code ?? '',
        name: element.name ?? '',
        type: ProjectType.created,
        organizationPatientType: element.patientType,
        projectIntroduction: element.introduction ?? '',
      ));
    });
    List<ProjectModel> joinedProjects = [];
    joinedResearchProjectList?.forEach((element) {
      joinedProjects.add(ProjectModel(
        id: element.code ?? '',
        name: element.name ?? '',
        type: ProjectType.joined,
        organizationPatientType: element.patientType,
        projectIntroduction: element.introduction ?? '',
      ));
    });
    projectClassifyData = [
      ClassifyData(
        classifyName: "我创建的",
        data: createdProjects,
        showActionButton: true,
        showItemActionButton: true,
      ),
      if (joinedProjects.length != 0)
        ClassifyData(classifyName: "我加入的", data: joinedProjects),
    ];
    isProjectListLoading = false;
    updateProjectData(projectCode);
    update([labProjectListId, projectTitle, labMainContent]);
  }

  /// 初始化项目成员
  Future<void> initProjectMember() async {
    allMemberModelList = [];
    PageCollection<UserBaseDTO>? userPage =
        await projectService.getUserBaseInfoPagesAsync(
      keyWord: '',
      pageIndex: 1,
      pageSize: 1000,
    );
    List<UserBaseDTO>? userList = userPage?.pageData!;
    userList?.forEach((element) {
      if (element.userCode != null && element.userCode != Store.user.code) {
        allMemberModelList.add(MemberModel(
          name: element.userName ?? '',
          avatar: element.headImageUrl ?? '',
          role: '',
          code: element.userCode ?? '',
        ));
      }
    });
  }

  /// 更新项目数据（病人列表）
  void updateProjectData(String projectCode, [int sort = 0]) async {
    if (projectCode.isEmpty) {
      isProjectDataLoading = false;
      return;
    }
    //验证是否有权限或者项目是否有效
    bool validateResult = await projectService.validateResearchProjectAuthAsync(
            projectCode: projectCode) ??
        false;
    if (validateResult) {
      isProjectDataLoading = true;
      update([projectDataPanelId, labMainContent]);
      PageCollection<ResearchProjectDataDTO>? result =
          await projectService.getResearchProjectDataPagesAsync(
        projectCode: projectCode,
        keyWord: '',
        pageIndex: 1,
        pageSize: 1000,
        sort: sort,
      );
      List<PatientModel> patients = [];
      result?.pageData?.forEach((element) {
        String patientName =
            FEncryptHelper.decryptBase64(element.patientName ?? '');
        if (patientName.isEmpty) {
          patientName = "未命名";
        }
        patients.add(PatientModel(
          id: element.devicePatientId ?? '',
          code: element.patientCode ?? '',
          name: patientName,
          isExistUrmData: element.isUrm,
          fileSize: CommonUtil.convertBytesToMegabytesOrGigabytes(
            int.parse(
              element.fileSize ?? '0',
            ),
          ),
        ));
      });
      // 项目数据
      patientData = patients;
      isProjectDataLoading = false;
      await getProjectDetail();
      update([projectDataPanelId, labMainContent]);
    } else {
      selectedClassifyIndex = 0;
      selectedProjectIndex = 0;
      initProjectList();
    }
  }

  /// 获取项目详情
  Future<void> getProjectDetail() async {
    if (projectCode.isEmpty) {
      return;
    }
    ResearchProjectDTO? projectDetail =
        await projectService.getResearchProjectDetail(
      projectCode: projectCode,
    );
    getTaskListByProjectCode();
    List<MemberModel> memberModelList = [];

    if (projectDetail != null) {
      projectType = projectDetail.patientType;

      projectDetail.users?.forEach((element) {
        memberModelList.add(MemberModel(
          name: element.userName ?? '',
          avatar: element.headImageUrl ?? '',
          role: '',
          code: element.userCode ?? '',
        ));
      });
      selectMemberModelList = memberModelList;
      selectMemberModelListByProjectDetail = memberModelList.toSet().toList();
    }
    update([projectSelectMember, projectTitle]);
  }

  /// 获取项目时间轴
  void getTaskListByProjectCode() async {
    if (projectCode.isEmpty) {
      return;
    }
    taskList = await projectService.getTimeAxisByProjectAsync(
          projectCode: projectCode,
        ) ??
        [];
    update([projectTimeLine]);
  }

  ///  收起时间轴
  void setTimeLineCollapse(bool isCollapse) {
    isCollapseTimeLine = isCollapse;
    update([labMainContent]);
  }

  // 开启定时器
  void startUpdateTimer() {
    if (timer != null) {
      return;
    }
    timer = Timer.periodic(
      Duration(milliseconds: 5000),
      (timer) {
        print("定时器执行 $tabHashCode");
        getTaskListByProjectCode();
      },
    );
  }

  // 销毁定时器
  void cancelTimer() {
    timer?.cancel();
    timer = null;
  }

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

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

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

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

  @override
  void onActive(arguments) {
    // startUpdateTimer();
    initProjectList();
    if (arguments is int) {
      if (arguments == 0) {}
    }
  }

  @override
  void onSleep() {
    cancelTimer();
  }
}

class MemberModel {
  String? name;
  String? avatar;
  String? role;
  String? code;

  MemberModel({
    this.name,
    this.avatar,
    this.role,
    this.code,
  });
}
