/// 手机端上级机构的跳转页面

import 'dart:async';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/pages/organization/org_info/state.dart';
import 'package:get/get.dart';

class SelectOrganizationRow extends StatelessWidget
    implements FInteractiveContainer {
  SelectOrganizationRow({
    Key? key,
    required this.title,
    this.pageName = 'SelectOrganizationRow',
    this.icon,
    this.onClick,
  }) : super(key: key);

  @override
  final String pageName;

  /// 选择组织名
  final FWidget title;

  /// 选择组织icon
  final FWidget? icon;

  /// 点击事件
  final Function? onClick;

  @override
  FWidget build(BuildContext context) {
    return FMaterial(
      color: Colors.white,
      child: FInk(
        child: FInkWell(
          onTap: () => onClick!(),
          child: FColumn(
            children: [
              FContainer(
                padding: EdgeInsets.symmetric(horizontal: 20),
                height: 50,
                child: FRow(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    FContainer(
                      child: FRow(
                        children: [
                          FRow(
                            children: [
                              icon ?? FText(''),
                            ],
                          ),
                          title,
                        ],
                      ),
                    ),
                    FContainer(
                      child: FRow(
                        children: [
                          FIcon(
                            Icons.chevron_right,
                            color: Color.fromRGBO(164, 164, 164, 1),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              FContainer(
                margin: EdgeInsets.symmetric(horizontal: 20),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Color.fromRGBO(245, 245, 245, 1),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class SelectOrganization extends FStatefulWidget
    implements FInteractiveContainer {
  SelectOrganization({
    Key? key,
    required this.list,
    this.code = '',
    this.title = '',
    this.pageName = 'SelectOrganization',
  }) : super(key: key);
  @override
  final String pageName;
  static Completer<List<String>?>? _completer;

  static Future<List<String>?>? open(orgOptions, {title = ''}) async {
    _completer = Completer<List<String>?>();
    Get.to(
      () => SelectOrganization(
        list: orgOptions,
        title: title,
      ),
      preventDuplicates: false,
      transition: Transition.rightToLeftWithFade,
    );
    final result = await _completer!.future;
    _completer = null;
    return result;
  }

  /// 选择的组织code
  final String? code;

  /// 选择的组织名

  final String? title;

  /// 组织list下拉选择器数据
  final List<OrgModel> list;

  @override
  FState<SelectOrganization> createState() => _SelectOrganizationState();
}

class _SelectOrganizationState extends FState<SelectOrganization> {
  final ScrollController _scrollController = ScrollController();
  final userInfoManager = Get.find<IUserInfoManager>();

  /// 选择下钻的位置
  late int areaIndex;

  /// 获取的areaCode
  late String areaCode;

  ///机构列表数据
  late List<OrgModel> _list;

  ///关键字
  String _keyword = '';
  int _pageIndex = 1;
  @override
  void initState() {
    _list = widget.list;
    _scrollController.addListener(_scrollListener);
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _scrollListener() async {
    if (_scrollController.position.maxScrollExtent ==
        _scrollController.position.pixels) {
      _pageIndex++;
      var orgs = await userInfoManager.searchOrganizationsAsync(
          keyword: _keyword, pageIndex: _pageIndex);
      if (orgs.isNotEmpty) {
        var infos = orgs
            .map((e) => OrgModel(
                code: e.organizationCode ?? '', name: e.organizationName ?? ''))
            .toList();
        setState(() {
          _list = infos;
        });
      }
    }
  }

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      appBar: FAppBar.simple(
        title: widget.title ?? i18nBook.organization.orgSelectionTip.t,
        onBackClicked: () => Get.back(),
      ),
      body: _buildOrgListView(),
    );
  }

  ///机构列表视图
  FWidget _buildOrgListView() {
    return FScaffold(
      appBar: FAppBar(
        leading: null,
        leadingWidth: 0,
        backgroundColor: Colors.white,
        elevation: 0,
        title: _buildSearchInput(),
      ),
      body: FListView.builder(
        itemCount: _list.length,
        controller: _scrollController,
        itemBuilder: (context, index) {
          return SelectOrganizationRow(
            title: FText(
              _list.toList()[index].name,
            ),
            onClick: () {
              SelectOrganization._completer!.complete(
                [_list.toList()[index].code, _list.toList()[index].name],
              );
              Get.until(
                (route) {
                  final backRoute =
                      route.settings.name != "/SelectOrganization";
                  return backRoute;
                },
              );
            },
          );
        },
      ),
    );
  }

  FWidget _buildSearchInput() {
    return FRow(
      children: [
        FBorderInput(
          fillColor: Colors.white,
          hintSize: 14,
          contentSize: 14,
          maxLength: 50,
          borderColor: Color.fromARGB(255, 185, 184, 184),
          suffixIcon: FIconButton(
            name: "search",
            businessParent: widget,
            onPressed: () async {
              _pageIndex = 1;
              if (_keyword.isEmpty) {
                setState(() {
                  _list = [];
                });
                return;
              }
              var list = await userInfoManager.searchOrganizationsAsync(
                  keyword: _keyword, pageIndex: _pageIndex);
              var result = list
                  .map((e) => OrgModel(
                      name: e.organizationName ?? '',
                      code: e.organizationCode ?? ''))
                  .toList();
              setState(() {
                _list = result;
              });
            },
            icon: FIcon(
              Icons.search,
              size: 20,
            ),
          ),
          height: 36,
          hintText: i18nBook.common.search.t,
          onChanged: (value) {
            _keyword = value;
          },
        ),
      ],
    );
  }
}
