import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:account_center/page/enterprise/organization_structure/organization_event.dart';
import 'package:account_center/routes/route_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'organization_structure_state.dart';

class OrganizationStructureLogic extends GetxController {
  final OrganizationStructureState state = OrganizationStructureState();

  int? departmentPno;

  late int companyNo;

  dynamic department;

  bool fromMyDepartment = false;

  @override
  void onInit() {
    if (Get.arguments is Map) {
      var argument = Get.arguments as Map;
      companyNo = argument['companyNo'].toString().toInt();
      state.title = '人员管理';
      _organizationTitle(argument);
    }
    OrganizationEvent.controllers.add(this);
    super.onInit();
  }

  @override
  void onClose() {
    OrganizationEvent.controllers.remove(this);
    super.onClose();
  }

  void _organizationTitle(Map<dynamic, dynamic> argument) {
    List<dynamic> parentDepartment = argument['parents'] ?? [];
    if (parentDepartment.isNotEmpty) {
      department = parentDepartment.last;
      departmentPno = department['departmentNo'].toString().toInt();
      state.isRoot = false;
    } else {
      /// 不是管理部门进来的
      if (!fromMyDepartment) {
        parentDepartment = [
          {'companyName': SpUtil.getString(SPKey.companyName)}
        ];
        state.isRoot = true;
        departmentPno = null;
      }
    }
    state.parents = parentDepartment;
  }

  void _requestPositionDetail() {
    fetch(
      Method.get,
      url: HttpApi.getDepartmentInfo,
      onSuccess: (depart) {
        department = depart;
        update();
      },
      queryParameters: {'departmentNo': departmentPno},
    );
  }

  @override
  void onReady() {
    requestData();
    super.onReady();
  }

  Future<void> createDepartment() async {
    var result = await Get.toNamed(RouteConfig.createDepartment, arguments: {
      'companyNo': companyNo,
      'departmentPno': departmentPno,
    });
    if (result != null) {
      requestData();
    }
  }

  void newPosition() {
    Get.toNamed(RouteConfig.newPositionPage,
        arguments: {'departmentPno': departmentPno, 'canManager': true})?.then(
      (value) {
        if (value != null) {
          requestData();
        }
      },
    );
  }

  void more() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            mackButton(
              "批量变更部门",
              () {},
              decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius:
                      BorderRadius.vertical(top: Radius.circular(16))),
            ),
            Container(
              height: 1,
              width: double.infinity,
              color: Color(0xffF3F5F8),
            ),
            mackButton("编辑部门", () {}),
            Container(
              height: 1,
              width: double.infinity,
              color: Color(0xffF3F5F8),
            ),
            mackButton("查看部门", () {}),
            Container(
              height: 8,
              width: double.infinity,
              color: Color(0xffF3F5F8),
            ),
            mackButton('取消', () {
              Get.back();
            }),
          ],
        ),
      ),
      enableDrag: false,
      isScrollControlled: true,
    );
  }

  Widget mackButton(String title, VoidCallback callback,
      {BoxDecoration? decoration}) {
    return Container(
      height: 50,
      width: double.infinity,
      color: decoration == null ? Colors.white : null,
      decoration: decoration,
      child: TextButton(
        onPressed: callback,
        child: Text(
          title,
          style: TextStyle(
            color: Color(0xff344254),
            fontWeight: FontWeight.w500,
            fontSize: 16,
          ),
        ),
      ),
    );
  }

  void departmentSetting() {
    dynamic depart = department;
    Get.toNamed(RouteConfig.departmentSettingPage, arguments: {
      'departmentNo': depart['departmentNo'],
      'departmentName': depart['departmentName'],
      'manageStatus': depart['manageStatus'],
      'isMyDepartment': fromMyDepartment,
    })?.then((value) {
      OrganizationEvent.refreshData();
      if (value == 'delete') {
        OrganizationEvent.refreshData();
        Get.back();
      } else {
        _requestPositionDetail();
      }
    });
  }

  bool get departmentManagerRoot => fromMyDepartment && departmentPno == null;

  /// 请求数据
  Future<void> requestData() async {
    if (departmentManagerRoot) {
      fetchList(
        Method.get,
        url: HttpApi.listDepartmentManage,
        queryParameters: {
          'companyNo': companyNo,
        },
        onSuccess: (response) {
          state.parents = [];
          onSuccess(response);
          return true;
        },
        onError: (code, msg) {
          ToastUtil.showToast(msg);
          return true;
        },
      );
    } else {
      fetchList(
        Method.post,
        url: HttpApi.listLevelOneDepartmentWidthNumByPno,
        params: {
          'companyNo': companyNo,
        }..addIf(departmentPno != null, 'departmentPno', departmentPno ?? 0),
        onSuccess: (response) {
          onSuccess.call(response);
          return true;
        },
        onError: (code, msg) {
          ToastUtil.showToast(msg);
          return true;
        },
      );
    }
  }

  void onSuccess(List<dynamic> response) {
    state.departments.clear();
    state.positions.clear();
    for (var element in response) {
      if (element['departmentType'] == 2) {
        state.departments.add(element);
      } else if (element['departmentType'] == 3) {
        state.positions.add(element);
      }
    }
    update();
  }

  void clickDepartment(element) {
    if (element['departmentType'] == 2) {
      Get.toNamed(RouteConfig.organizationStructurePage,
          arguments: {
            'companyNo': companyNo,
            'isMyDepartment': fromMyDepartment,
            'parents': [...state.parents, element]
          },
          preventDuplicates: false);
    } else if (element['departmentType'] == 3) {
      Get.toNamed(RouteConfig.positionDetailsPage,
          arguments: {
            'companyNo': companyNo,
            'isMyDepartment': fromMyDepartment,
            'departmentNo': element['departmentNo']?.toString().toInt() ?? 0,
            'parents': [...state.parents, element]
          },
          preventDuplicates: false);
    }
  }
}
