import 'dart:async';

import 'package:fis_i18n/i18n.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/font_sizes.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remote_controller/index.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/index.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/simple_Info.dart';
import 'package:universal_html/js_util.dart';

import 'horizontal_user_card.dart';

class AddParticipantsPage extends FisView implements FPage {
  /// 确认后的回调函数
  final Function? confirmCallback;

  /// 控制器
  final RealTimeConsultationController controller;

  AddParticipantsPage(
      {Key? key, this.confirmCallback, required this.controller})
      : super(key: key);

  @override
  String get pageName => 'AddParticipantsPage';

  FWidget build(BuildContext context) {
    return _DesktopLayout(confirmCallback ?? () {}, controller);
  }
}

class _DesktopLayout extends FStatefulWidget {
  /// 确认后的回调函数
  final Function confirmCallback;

  /// 控制器
  final RealTimeConsultationController controller;

  final FPage businessParent = newObject();
  _DesktopLayout(this.confirmCallback, this.controller);

  @override
  FState<FStatefulWidget> createState() {
    return _DesktopLayoutState(businessParent, confirmCallback, controller);
  }
}

class _DesktopLayoutState extends FState<_DesktopLayout> {
  final RealTimeConsultationController controller;

  final FPage businessParent;
  final Function confirmCallback;
  final ScrollController _scrollController = ScrollController();
  final ScrollController _totalScrollController = ScrollController();

  ///所有医院
  List<FSelectModel> hospitals = [];

  ///对应医院的所有人员信息
  List<SimpleInfoItem> totalData = [];

  ///点击右侧列表(预点击)，在点击确认按钮后保存到isCheckedRight  string是usercode,bool表示是否选中。该值表示某个医院的人员选中状态
  Map<String, bool> isCheckedRightPrepare = new Map<String, bool>();

  ///点击右侧列表（所有人员的选中状态，不按医院分类）,string 表示userCode
  Map<String, bool> isCheckedRight = new Map<String, bool>();

  ///点击左侧列表
  late Map<FSelectModel, bool> isClickedLeft = new Map<FSelectModel, bool>();

  ///右侧列表的选中标识
  late Map<String, FWidget> checkedIconWidget = new Map<String, FWidget>();

  ///所有已选中的参与人code(预选中，在点击确认按钮后生效)
  List<String> participantsTotalPrepare = [];

  Timer? _debounce;

  String _selectedHospital = '';

  _DesktopLayoutState(
      this.businessParent, this.confirmCallback, this.controller);

  @override
  FWidget build(BuildContext context) {
    return mainContent(businessParent, controller, hospitals);
  }

  @override
  void initState() {
    super.initState();
    hospitals = _getHospitals();

    for (int i = 1; i < hospitals.length; i++) {
      isClickedLeft[hospitals[i]] = false;
    }
    isClickedLeft[hospitals[0]] = true;
    _selectedHospital = hospitals[0].code;
    _getUserInfo(hospitals[0].code);
    participantsTotalPrepare.clear();
    for (var item in controller.state.applicationInfo.participantsTotal) {
      participantsTotalPrepare.add(item);
    }
  }

  @override
  void dispose() {
    controller.searchController.text = '';
    super.dispose();
  }

  FWidget mainContent(FPage businessParent,
      RealTimeConsultationController controller, List<FSelectModel> hospitals) {
    return FSimpleDialog(
      title: FText(
        i18nBook.realTimeConsultation.addParticipants.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: FFontSizes.H5,
        ),
      ),
      backgroundColor: Color.fromRGBO(230, 230, 230, 1),
      children: [
        FContainer(
          padding: EdgeInsets.only(right: 30),
          color: Colors.white,
          width: 600,
          child: FFlex(
            crossAxisAlignment: CrossAxisAlignment.start,
            direction: Axis.horizontal,
            children: [
              FExpanded(
                child: FContainer(
                  height: 600,
                  child: FAlwaysScrollListView(
                    scrollController: _scrollController,
                    child: QuickFWidget(ScrollConfiguration(
                      behavior: ScrollConfiguration.of(context)
                          .copyWith(scrollbars: false),
                      child: FListView(
                        controller: _scrollController,
                        children: _createLeftListView(hospitals),
                      ),
                    )),
                  ),
                ),
                flex: 1,
              ),
              FExpanded(
                child: FContainer(
                  height: 600,
                  decoration: BoxDecoration(
                    border: Border(
                      left: BorderSide(width: 1.0, color: Colors.black26),
                    ),
                  ),
                  child: FColumn(
                    children: [
                      FContainer(
                        width: 390,
                        child: FSearchInput(
                          businessParent: businessParent,
                          hintText: i18nBook.common.search.t,
                          onChanged: (value) {
                            if (_debounce?.isActive ?? false) {
                              _debounce?.cancel();
                            }
                            _debounce = Timer(
                              Duration(milliseconds: 300),
                              () async {
                                _getUserInfo(_selectedHospital);
                              },
                            );
                          },
                          serchOnPressed: () async {
                            _getUserInfo(_selectedHospital);
                          },
                          controller: controller.searchController,
                        ),
                      ),
                      FSizedBox(
                        height: 540,
                        child: FAlwaysScrollListView(
                          scrollController: _totalScrollController,
                          child: QuickFWidget(ScrollConfiguration(
                            behavior: ScrollConfiguration.of(context)
                                .copyWith(scrollbars: false),
                            child: FListView(
                              shrinkWrap: true,
                              controller: _totalScrollController,
                              children: _createRightListView(totalData),
                            ),
                          )),
                        ),
                      ),
                    ],
                  ),
                ),
                flex: 2,
              ),
            ],
          ),
        ),
      ],
      isDefault: true,
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      onOk: () {
        if (participantsTotalPrepare.length <= 0) {
          PromptBox.toast(i18nBook.realTimeConsultation.chooseParticipants.t);
        } else {
          isCheckedRight = isCheckedRightPrepare;
          controller.state.applicationInfo.participantsTotal =
              participantsTotalPrepare;
          controller.getParticipantsDetails();
          confirmCallback();
          router.back();
        }
      },
      onCancel: () {
        router.back();
      },
    );
  }

  ///创建左侧列表
  List<FWidget> _createLeftListView(List<FSelectModel> hospitals) {
    List<FWidget> listTitles = [];
    for (var item in hospitals) {
      listTitles.add(
        _leftListView(item),
      );
    }

    return listTitles;
  }

  List<FWidget> _createRightListView(List<SimpleInfoItem> totalData) {
    List<FWidget> list = [];
    for (var i = 0; i < totalData.length; i++) {
      list.add(_rightListView(totalData[i]));
    }
    return list;
  }

  ///获取医院信息
  List<FSelectModel> _getHospitals() {
    List<FSelectModel> hospitals = [];
    hospitals = controller.state.organizations;
    return hospitals;
  }

  /// 获取对应医院的人员信息
  Future<void> _getUserInfo(String organizationCode) async {
    var result = await controller.getUserInfosByOrganizationCode(
      organizationCode,
      keyword: controller.searchController.text,
    );
    for (int i = 0; i < totalData.length; i++) {
      if (participantsTotalPrepare.indexOf(totalData[i].itemCode) == -1) {
        //如果没有被选中过，就不显示选中状态
        isCheckedRight[totalData[i].itemCode] = false;
        isCheckedRightPrepare[totalData[i].itemCode] = false;
      } else {
        isCheckedRight[totalData[i].itemCode] = true;
        isCheckedRightPrepare[totalData[i].itemCode] = true;
      }
    }
    setState(() {
      totalData = result;
    });
  }

  ///左侧列表的通用样式
  FWidget _leftListView(FSelectModel selectedHospital) {
    return FContainer(
      color: isClickedLeft[selectedHospital]!
          ? FTheme.ins.colorScheme.primary
          : Colors.white,
      child: new FListTile(
        title: FText(
          selectedHospital.name,
          style: TextStyle(
            color:
                isClickedLeft[selectedHospital]! ? Colors.white : Colors.black,
          ),
        ),
        onTap: () async {
          _selectedHospital = selectedHospital.code;
          controller.searchController.text = '';
          //当点击的时候获取对应人员信息并刷新右侧列表
          await _getUserInfo(selectedHospital.code);

          //将其他医院的选中状态置为false
          for (int i = 0; i < hospitals.length; i++) {
            isClickedLeft[hospitals[i]] = false;
          }

          isClickedLeft[selectedHospital] = !isClickedLeft[selectedHospital]!;

          setState(() {});
        },
      ),
    );
  }

  ///右侧列表Item样式
  FWidget _rightListView(SimpleInfoItem userInfo) {
    if (userInfo.des == null) {
      userInfo.des = [];
    }
    userInfo.des!.insert(0, i18nBook.user.skilledAreaWithDevider.t);
    return FHorizontalUserSimpleCard(
      itemInfo: userInfo,
      isSelected: participantsTotalPrepare.contains(userInfo.itemCode),
      onTap: (isSelected) {
        if (isSelected) {
          //将选中的人员信息保存到list
          if (participantsTotalPrepare.indexOf(userInfo.itemCode) < 0) {
            participantsTotalPrepare.add(userInfo.itemCode);
          }
        } else {
          //如果取消选中
          if (participantsTotalPrepare.indexOf(userInfo.itemCode) >= 0) {
            participantsTotalPrepare
                .removeAt(participantsTotalPrepare.indexOf(userInfo.itemCode));
          }
        }
      },
    );
  }
}
