import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/define.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/managers/interfaces/entities/classInfo.dart';
import 'package:flyinsono/pages/college/controller.dart';
import 'package:flyinsono/pages/college/widgets/my_class/join_class.dart';
import 'package:get/get.dart';

import '../hover_text_tab.dart';
import 'add_user.dart';
import 'apply_review.dart';
import 'create_class.dart';
import 'tablele_header.dart';

class MyClass extends FStatefulWidget implements FPage {
  @override
  String get pageName => 'MyClass';

  @override
  FState<FStatefulWidget> createState() {
    return MyClassState();
  }
}

class MyClassState extends FState<MyClass> with TableleHeader {
  final controller = Get.find<FlyinsonoCollegeController>();
  final TextEditingController searchController = TextEditingController();
  final buttonStyle = ButtonStyle(
    minimumSize: MaterialStateProperty.all<Size>(Size(90, 30)),
  );
  final _buttonStyle = ButtonStyle(
    fixedSize: MaterialStateProperty.all(Size(100, 25)),
  );
  int _selectedIndex = 0;
  bool _tableLoading = false;
  int _currentPageIndex = 1;
  int _totalPageSize = 0;

  @override
  void initState() {
    _initCourseInfos();
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FExpanded(
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSpacingg(),
          FisBuilder<FlyinsonoCollegeController>(
            id: 'class_tabs',
            builder: (_) {
              return _buildTabs();
            },
          ),
          _buildSpacingg(),
          FisBuilder<FlyinsonoCollegeController>(
            id: 'class_top_operate_button',
            builder: (_) {
              return _buildTopOperateButton();
            },
          ),
          _buildSpacingg(),
          FExpanded(
            child: FisBuilder<FlyinsonoCollegeController>(
              id: 'class_table',
              builder: (_) {
                return _buildClassTable();
              },
            ),
          ),
          FisBuilder<FlyinsonoCollegeController>(
            id: 'class_table_pagination',
            builder: (_) {
              return FContainer(
                margin: EdgeInsets.only(bottom: 15, right: 15),
                child: FTablePagination(
                  currListLength: _totalPageSize,
                  currPageIndex: 1,
                  pageSize: 20,
                  onChangePage: (pageIndex, listLength) => _changePage(
                    pageIndex,
                    listLength,
                  ),
                  totalItemNumText: i18nBook.common.ofTerm.translate(
                    ['$_totalPageSize'],
                  ),
                  previousFivePageText: i18nBook.common.previousFivePageText.t,
                  nextFivePageText: i18nBook.common.nextFivePageText.t,
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  FWidget _buildSpacingg() {
    return const FSizedBox(height: 15);
  }

  FWidget _buildTabs() {
    return FRow(
      children: [
        _rowSpaceing(),
        FHoverTextTab(
          onPressed: () => _changeTab(0),
          text: i18nBook.college.teacherRole.t,
          isSelected: _selectedIndex == 0,
        ),
        FHoverTextTab(
          onPressed: () => _changeTab(1),
          text: i18nBook.college.studentRole.t,
          isSelected: _selectedIndex == 1,
        ),
      ],
    );
  }

  FWidget _buildTopOperateButton() {
    return FContainer(
      margin: EdgeInsets.only(left: 15),
      child: FRow(
        children: [
          _rowSpaceing(),
          FContainer(
            margin: EdgeInsets.symmetric(vertical: 10),
            height: 30,
            width: 230,
            child: FTextField(
              decoration: InputDecoration(
                contentPadding:
                    EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.0), // 设置圆角的半径
                ),
                hintText: i18nBook.common.search.t,
              ),
              controller: searchController,
            ),
          ),
          _rowSpaceing(),
          FElevatedButton(
            style: _buttonStyle,
            child: FText(i18nBook.common.search.t),
            onPressed: () async {
              await _getClassInfoList();
              setState(() {});
            },
            businessParent: widget,
            name: 'search',
          ),
          _rowSpaceing(),
          FElevatedButton(
            style: _buttonStyle,
            child: FText(i18nBook.common.refresh.t),
            onPressed: () {
              searchController.text = '';
              _getClassInfoList();
            },
            businessParent: widget,
            name: 'search',
          ),
          _rowSpaceing(),
          if (_selectedIndex == 0) ...[
            FElevatedButton(
              style: _buttonStyle.copyWith(
                  padding: MaterialStatePropertyAll(
                      EdgeInsets.symmetric(horizontal: 2))),
              child: FText(i18nBook.college.createClass.t),
              onPressed: () {
                router.dialog(
                  () => CreateClass((name) async {
                    var result = await controller.createClass(name);
                    if (result) {
                      router.back();
                    }
                    setState(() {});
                  }),
                );
              },
              businessParent: widget,
              name: 'search',
            ),
          ] else ...[
            FElevatedButton(
              style: _buttonStyle,
              child: FText(i18nBook.college.joinClass.t),
              onPressed: () {
                router.dialog(
                  () => JoinClass((code) async {
                    var result = await controller.joinClass(code);
                    if (result) {
                      router.back();
                      setState(() {});
                    }
                  }),
                );
              },
              businessParent: widget,
              name: 'search',
            ),
          ],
        ],
      ),
    );
  }

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

  ///班级列表
  FWidget _buildClassTable() {
    if (_selectedIndex == 0) {
      return FTable<UserGroupDTO>(
        autoHeight: false,
        noDataHintText: i18nBook.common.noData.t,
        columns: getTeachTableleHeader(_buildTeachOperates),
        source: controller.state.classInfos,
        loading: _tableLoading,
      );
    } else {
      return FTable<UserGroupDTO>(
        autoHeight: false,
        noDataHintText: i18nBook.common.noData.t,
        columns: getStudentTableleHeader(_buildStudentOperates),
        source: controller.state.classInfos,
        loading: _tableLoading,
      );
    }
  }

  FWidget _buildTeachOperates(UserGroupDTO info) {
    return FContainer(
      height: 50,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          FElevatedButton(
            child: FContainer(
              alignment: Alignment.center,
              height: 25,
              child: FText(i18nBook.college.applyForReview.t),
            ),
            style: buttonStyle,
            onPressed: () async {
              await controller.getApplyStudents(info.code!);
              router.dialog(
                () => StudentsReview(userGroupCode: info.code!),
              );
            },
            businessParent: widget,
            name: 'apply for review',
          ),
          FElevatedButton(
            child: FContainer(
              alignment: Alignment.center,
              height: 25,
              child: FText(i18nBook.college.viewStudent.t),
            ),
            style: buttonStyle,
            onPressed: () async {
              await controller.getClassStudents(info.code!);
              router.dialog(
                () => StudentsReview(
                  isApplyReview: false,
                  userGroupCode: info.code!,
                ),
              );
            },
            businessParent: widget,
            name: 'view students',
          ),
          FElevatedButton(
            child: FContainer(
              alignment: Alignment.center,
              height: 25,
              child: FText(i18nBook.college.addStudent.t),
            ),
            style: buttonStyle,
            onPressed: () {
              router.dialog(
                () => AddClassUser(
                  userGroupCode: info.code!,
                ),
              );
            },
            businessParent: widget,
            name: 'add students',
          ),

          /// 暂时屏蔽
          // FElevatedButton(
          //   child: FContainer(
          //     alignment: Alignment.center,
          //     height: 25,
          //     child: FText(i18nBook.college.addTeacher.t),
          //   ),
          //   style: buttonStyle,
          //   onPressed: () {
          //     router.dialog(
          //       () => AddClassUser(
          //         isAddStudent: false,
          //         userGroupCode: info.code!,
          //       ),
          //     );
          //   },
          //   businessParent: widget,
          //   name: 'add instructor',
          // ),
          // FElevatedButton(
          //   child: FContainer(
          //     alignment: Alignment.center,
          //     height: 25,
          //     child: FText(i18nBook.college.assignCourse.t),
          //   ),
          //   style: buttonStyle,
          //   onPressed: () {},
          //   businessParent: widget,
          //   name: 'assign courses',
          // ),
          // FElevatedButton(
          //   child: FContainer(
          //     alignment: Alignment.center,
          //     height: 25,
          //     child: FText(i18nBook.college.distributeExam.t),
          //   ),
          //   style: buttonStyle,
          //   onPressed: () {},
          //   businessParent: widget,
          //   name: 'distribute exam papers',
          // ),
          // FElevatedButton(
          //   child: FContainer(
          //     alignment: Alignment.center,
          //     height: 25,
          //     child: FText(i18nBook.college.distributeExercise.t),
          //   ),
          //   style: buttonStyle,
          //   onPressed: () {},
          //   businessParent: widget,
          //   name: 'distribute exercises',
          // ),
        ],
      ),
    );
  }

  FWidget _buildStudentOperates(UserGroupDTO info) {
    return FSizedBox(
      height: 50,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FElevatedButton(
            style: buttonStyle,
            child: FContainer(
              alignment: Alignment.center,
              height: 25,
              child: FText(i18nBook.college.exercise.t),
            ),
            onPressed: () {},
            businessParent: widget,
            name: 'practice',
          ),
          _rowSpaceing(),
          FElevatedButton(
            style: buttonStyle,
            child: FContainer(
              alignment: Alignment.center,
              height: 25,
              child: FText(i18nBook.college.exam.t),
            ),
            onPressed: () {},
            businessParent: widget,
            name: 'exam',
          ),
          _rowSpaceing(),
          FElevatedButton(
            child: FContainer(
              alignment: Alignment.center,
              height: 25,
              child: FText(i18nBook.college.quitClass.t),
            ),
            style: buttonStyle,
            onPressed: () {
              controller.quitClass(info.code!);
            },
            businessParent: widget,
            name: 'exit class',
          ),
        ],
      ),
    );
  }

  Future<void> _initCourseInfos() async {
    _tableLoading = true;
    _totalPageSize =
        await controller.getClassInfos(roleType: ClassRoleType.Teacher);
    _tableLoading = false;
    if (mounted) {
      setState(() {});
    }
  }

  Future<void> _getClassInfos(ClassRoleType roleType) async {
    _tableLoading = true;
    var totalPageSize = await controller.getClassInfos(
      roleType: roleType,
      pageIndex: _currentPageIndex,
      keyword: searchController.text,
    );
    _tableLoading = false;
    _totalPageSize = totalPageSize;
  }

  void _changePage(pageIndex, listLength) {
    _currentPageIndex = pageIndex;
    _getClassInfoList();
  }

  Future<void> _getClassInfoList() async {
    if (_selectedIndex == 0) {
      await _getClassInfos(
        ClassRoleType.Teacher,
      );
    } else {
      await _getClassInfos(
        ClassRoleType.Student,
      );
    }
  }

  void _changeTab(int currentIndex) async {
    if (_selectedIndex != currentIndex) {
      _selectedIndex = currentIndex;
      searchController.text = '';
      await _getClassInfoList();
      controller.updateClassTablePagination();
    } else {
      return;
    }
  }
}
