import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/college/controller.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/horizontal_user_card.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/simple_Info.dart';
import 'package:get/get.dart';

class AddClassUser extends FStatefulWidget implements FPage {
  @override
  String get pageName => "AddStudent";
  final bool isAddStudent;
  final String userGroupCode;

  AddClassUser({
    this.isAddStudent = true,
    required this.userGroupCode,
  });
  @override
  FState<FStatefulWidget> createState() {
    return AddStudentState();
  }
}

class AddStudentState extends FState<AddClassUser> {
  final controller = Get.find<FlyinsonoCollegeController>();
  final TextEditingController searchController = TextEditingController();
  ScrollController _scrollController = ScrollController();
  List<UserExtendDTO> _searchUsers = [];
  List<String> _selectedUsers = [];
  bool _isLoadingMore = false;
  bool _isLoading = false;
  //改
  int _totalItemCount = 0;
  int _currentIndex = 1;

  @override
  void initState() {
    super.initState();
    _getUserList();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
              _scrollController.position.maxScrollExtent &&
          !_isLoadingMore &&
          _searchUsers.length < _totalItemCount) {
        _currentIndex++;
        _dropDownGetUserList(); // 加载下一页数据
      }
    });
  }

  @override
  FWidget build(BuildContext context) {
    var title = widget.isAddStudent
        ? i18nBook.college.addStudent.t
        : i18nBook.college.addTeacher.t;
    if (kIsMobile) {
      return FScaffold(
        appBar: FAppBar.simple(title: title, onBackClicked: router.back),
        body: FColumn(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _buildTopOperateButton(),
            FExpanded(
              child: _buildUserList(),
            ),
            _buildSubmitButton(),
          ],
        ),
      );
    } else {
      return FSimpleDialog(
        okString: i18nBook.common.confirm.t,
        cancelString: i18nBook.common.cancel.t,
        isDefault: true,
        title: FText(
          title,
          style: TextStyle(color: Colors.white),
        ),
        onCancel: router.back,
        onClose: router.back,
        onOk: () async {
          bool result;
          if (widget.isAddStudent) {
            result = await controller.addStudents(
              _selectedUsers,
              widget.userGroupCode,
            );
            if (result) {
              PromptBox.toast(i18nBook.remedical.addSuccess.t);
            } else {
              PromptBox.toast(i18nBook.remedical.addFailed.t);
            }
          } else {
            result = await controller.addTeachers(_selectedUsers);
          }
          if (result) {
            router.back();
          }
        },
        children: [
          FContainer(
            alignment: Alignment.center,
            child: _buildTopOperateButton(),
          ),
          FContainer(
            height: 450,
            width: 500,
            child: _buildUserList(),
          ),
        ],
      );
    }
  }

  FWidget _buildTopOperateButton() {
    return FContainer(
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FContainer(
            margin: EdgeInsets.symmetric(vertical: 10),
            height: 35,
            width: kIsMobile ? 240 : 300,
            child: FTextField(
              decoration: InputDecoration(
                contentPadding:
                    EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.0), // 设置圆角的半径
                ),
                hintText: i18nBook.college.searchUser.t,
              ),
              controller: searchController,
            ),
          ),
          _rowSpaceing(),
          FElevatedButton(
            child: FText(i18nBook.common.search.t),
            onPressed: () => _getUserList(),
            style: ButtonStyle(
              fixedSize: MaterialStateProperty.all<Size>(
                Size(65, 33), // 设置宽度为200，高度为50
              ),
            ),
            businessParent: widget,
            name: 'search',
          ),
        ],
      ),
    );
  }

  FWidget _rowSpaceing() {
    return const FSizedBox(
      width: 15,
    );
  }

  // 下拉获取用户列表
  void _dropDownGetUserList() async {
    if (widget.isAddStudent) {
      PageResult<UserExtendDTO> userExtendPageResult =
          await controller.getStudents(
        keyword: searchController.text,
        pageIndex: _currentIndex,
      );
      _totalItemCount = userExtendPageResult.totalCount;
      _searchUsers.addAll(
        userExtendPageResult.pageData ?? [],
      );
    } else {
      _searchUsers = await controller.getTeachers(
        keyword: searchController.text,
      );
    }
    setState(() {});
  }

  void _scrollToTop() {
    _scrollController.animateTo(
      0.0, // 滚动到的位置，0 表示最顶部
      curve: Curves.easeInOut, // 使用平滑的曲线过渡
      duration: Duration(milliseconds: 300), // 动画持续时间
    );
  }

  void _getUserList() async {
    setState(() {
      _isLoading = true;
    });
    _currentIndex = 1;
    _scrollToTop();
    List<UserExtendDTO> users = [];
    if (widget.isAddStudent) {
      PageResult<UserExtendDTO> userExtendPageResult =
          await controller.getStudents(
        keyword: searchController.text,
      );
      _totalItemCount = userExtendPageResult.totalCount;
      users = userExtendPageResult.pageData ?? [];
    } else {
      users = await controller.getTeachers(
        keyword: searchController.text,
      );
    }
    setState(() {
      _isLoading = false;
      _searchUsers = users;
    });
  }

  FWidget _buildUserList() {
    if (_isLoading) {
      return FCenter(
        child: FContainer(
          width: 40,
          height: 40,
          child: FCircularProgressIndicator(),
        ),
      );
    }
    return FListView.builder(
        shrinkWrap: true,
        itemCount: _searchUsers.length,
        controller: _scrollController,
        itemBuilder: (_, i) {
          var user = _searchUsers[i];
          return FHorizontalUserSimpleCard(
            margin: EdgeInsets.only(left: 60, right: 60, top: 5),
            itemInfo: SimpleInfoItem(
              itemCode: user.userCode!,
              name: user.displayName,
              role: widget.isAddStudent ? user.phone : user.roleName,
              des: [user.rootOrganizationName],
              image: user.headImageUrl,
            ),
            isSelected: _selectedUsers.contains(user.userCode),
            onTap: (isSelected) {
              if (isSelected) {
                _selectedUsers.add(user.userCode!);
              } else {
                _selectedUsers.remove(user.userCode!);
              }
            },
          );
        });
  }

  FWidget _buildSubmitButton() {
    return FGestureDetector(
      businessParent: this.widget,
      child: FContainer(
        margin: EdgeInsets.symmetric(
          vertical: FSpacings.M,
          horizontal: FSpacings.XL,
        ),
        height: 50,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(8),
          ),
          color: FTheme.ins.colorScheme.primary,
        ),
        child: FText(
          i18nBook.common.confirm.t,
          style: TextStyle(color: Colors.white),
        ),
      ),
      onTap: () async {
        bool result;
        if (widget.isAddStudent) {
          result = await controller.addStudents(
            _selectedUsers,
            widget.userGroupCode,
          );
        } else {
          result = await controller.addTeachers(_selectedUsers);
        }
        if (result) {
          router.back();
        }
      },
      name: 'Start Consultation',
    );
  }
}
