import 'dart:async';
import 'package:flyinsono/architecture/define.dart';
import 'package:get/get.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/services/modules/area_region.dart';

/// 单个选择行
class SelectAreaItemRow extends StatelessWidget {
  SelectAreaItemRow({
    Key? key,
    required this.title,
    this.icon,
    this.isImage = false,
    this.onClick,
    this.hintText = '',
    this.imageUrl = '',
  }) : super(key: key);

  /// 选择名
  final FWidget title;

  /// 单行选择icon
  final FWidget? icon;

  /// 是否是图片上传组件
  final bool? isImage;

  /// 副标题
  final String? hintText;

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

  ///  图片地址
  final String? imageUrl;

  @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 ?? FContainer(),
                            ],
                          ),
                          title,
                        ],
                      ),
                    ),
                    FContainer(
                      child: FRow(
                        children: [
                          FIcon(
                            Icons.chevron_right,
                            color: Color.fromRGBO(164, 164, 164, 1),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              FContainer(
                margin: const EdgeInsets.symmetric(horizontal: 20),
                decoration: const BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Color.fromRGBO(245, 245, 245, 1),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// 手机端地区选择的组件
class SelectArea extends StatefulWidget {
  SelectArea({
    Key? key,
    this.code = '',
  }) : super(key: key);

  static Completer<List<String>?>? _completer;

  static Future<List<String>?>? open() async {
    _completer = Completer<List<String>?>();

    Get.to(
      () => SelectArea(),
      preventDuplicates: false,
      transition: Transition.rightToLeftWithFade,
    );
    final result = await _completer!.future;
    _completer = null;
    return result;
  }

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

  @override
  State<SelectArea> createState() => _SelectAreaState();
}

class _SelectAreaState extends State<SelectArea> {
  /// 选择下钻的层级
  int areaIndex = 0;

  /// 获取的areaCode
  late String areaCode;

  final ScrollController _scrollController = ScrollController();

  /// 下钻的方法
  void onRihInClick(AreaRegionModel areaRegionModel, int index) {
    if (areaRegionModel.grade == '2') {
      areaCode = areaRegionModel.code;
      SelectArea._completer!.complete(
        [areaRegionModel.parentCode, areaRegionModel.code],
      );
      Get.until(
        (route) {
          final backRoute = route.settings.name != "/SelectArea";
          return backRoute;
        },
      );
    } else {
      setState(() {
        areaIndex = index;
      });
      Get.to(
        () => SelectArea(
          code: areaRegionModel.code,
        ),
        preventDuplicates: false,
        transition: Transition.rightToLeftWithFade,
      );
    }
  }

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

  @override
  void dispose() {
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    final areaRegionService = Get.find<AreaRegionService>();
    final list = widget.code!.isEmpty
        ? areaRegionService.allList.where((x) => x.grade == "0").toList()
        : areaRegionService.allList
            .where((x) => x.parentCode == widget.code)
            .toList();
    return FScaffold(
      appBar: FAppBar.simple(
        title: i18nBook.organization.areaSelectionTip.t,
        onBackClicked: () => Get.back(),
      ),
      body: FSafeArea(
        child: FAlwaysScrollListView(
          scrollController: _scrollController,
          child: QuickFWidget(ScrollConfiguration(
            behavior:
                ScrollConfiguration.of(context).copyWith(scrollbars: false),
            child: FListView.builder(
              itemCount: list.length,
              itemBuilder: (context, index) {
                return SelectAreaItemRow(
                  title: areaIndex == null
                      ? FText(
                          list[index].name,
                        )
                      : list[areaIndex].name == list[index].name
                          ? FText(
                              list[index].name,
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                              ),
                            )
                          : FText(
                              list[index].name,
                            ),
                  onClick: () => onRihInClick(
                    list[index],
                    index,
                  ),
                );
              },
            ),
          )),
        ),
      ),
    );
  }
}
