import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_util.dart';
import 'package:account_center/routes/route_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'new_position_state.dart';

class NewPositionLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final NewPositionState state = NewPositionState();

  late TabController controller;
  int? departmentPno;

  ///存储roleNo 遍历去重
  List<String> roleNos = [];

  ///去重复
  List<String> userNos = [];

  bool canManager = true;

  @override
  void onInit() {
    super.onInit();
    departmentPno = Get.arguments['departmentPno'];
    canManager = Get.arguments['canManager'] == true;
    controller = TabController(length: 2, vsync: this);
  }

  void textEmpty() {
    if (state.controller.text.isEmpty) {
      ToastUtil.showToast('请填写职位名称');
      return;
    }
    // if (state.roleList.isEmpty) {
    //   ToastUtil.showToast('请添加角色');
    //   return;
    // }
    // if (state.personList.isEmpty) {
    //   ToastUtil.showToast('请添加人员');
    //   return;
    // }
    confirm();
  }

  void confirm() {
    _newPositionRequest();
  }

  ///新建职位接口请求
  void _newPositionRequest() {
    state.focusNode.unfocus();
    fetch(Method.post, url: HttpApi.newPosition, onSuccess: (data) {
      Get.back(result: {});
    }, params: {
      'companyNo': getCompanyNo(),
      'adminPosition': state.radioIndex,
      'departmentName': state.controller.text,
      'departmentPno': departmentPno,
      'departmentType': 3, //部门类型:1-公司,2-部门,3-职位
      'users': userNos,
      'roleNos': roleNos,
    });
  }

  void changeRadio(int index) {
    if (canManager) {
      state.radioIndex = index;
      update();
    }
  }

  void deleteRole(item) {
    roleNos.remove(item['roleNo']);
    state.roleList.remove(item);
    update();
  }

  void goToRoleListPage() {
    state.focusNode.unfocus();
    Get.toNamed(RouteConfig.roleSelectPage, arguments: {'forbidNo': roleNos})
        ?.then((data) {
      if (data != null) {
        for (var e in data) {
          if (e['roleNo']?.toString().isNotEmpty == true) {
            roleNos.add(e['roleNo']?.toString() ?? '');
          }
        }
        state.roleList.addAll(data);
        update();
      }
    });
  }

  void goToPersonListPage() {
    state.focusNode.unfocus();
    Get.toNamed(
      RouteConfig.staffListSelectPage,
      arguments: {'forbidNo': userNos, 'isPosition': true},
    )?.then((data) {
      if (data != null) {
        for (var e in data) {
          if (e['userNo']?.toString().isNotEmpty == true) {
            userNos.add(e['userNo']?.toString() ?? '');
          }
        }
        state.personList.addAll(data);
        update();
      }
    });
  }

  void deletePerson(item) {
    userNos.remove(item['userNo']);
    state.personList.remove(item);
    update();
  }
}
