import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/appointment_consultation.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/simple_Info.dart';
import 'package:get/get.dart';

/// 特殊多选下拉框
class FSpecialMultiSelectPopup<T, TValue> extends FStatefulWidget {
  /// 数据源
  final List<T> source;

  /// 选中值列表
  final List<String>? value;

  /// 选中名字列表
  final List<String>? valueName;

  /// 下拉选中的值
  final ValueCallback? onChangeIndex;

  /// 下拉选中的值
  final ValueCallback? onChangeString;

  /// 最大人数
  final int? maxMembers;

  /// 弹出框的高度
  final double? height;

  FSpecialMultiSelectPopup({
    Key? key,
    required this.source,
    this.onChangeIndex,
    this.onChangeString,
    this.value,
    this.valueName,
    this.maxMembers,
    this.height,
  }) : super(key: key);

  @override
  FState<FSpecialMultiSelectPopup> createState() => _FMultiSelectPopupState();
}

class _FMultiSelectPopupState extends FState<FSpecialMultiSelectPopup> {
  final ScrollController _scrollController = ScrollController();
  List<String> _selectIndexList = [];
  List<String> _selectNameList = [];

  /// 这边是组件外部点击取消重置状态
  List<String> _oldSelectIndexList = [];
  List<String> _oldSelectNameList = [];
  final fontStyle = TextStyle(
    fontSize: 14,
  );

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      height: widget.height ?? 500,
      child: FAlwaysScrollListView(
        scrollController: _scrollController,
        child: QuickFWidget(ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: FListView.builder(
            controller: _scrollController,
            shrinkWrap: true,
            itemCount: widget.source.length,
            itemBuilder: (BuildContext context, int index) {
              return FMaterial(
                color: Colors.white,
                child: FInkWell(
                  onTap: () {
                    setState(() {
                      String userCode;
                      String personName;
                      var sourceValue = widget.source[index];
                      if (sourceValue.value is SimpleInfoItem) {
                        userCode = sourceValue.value.itemCode;
                        personName = sourceValue.value.name ?? '';
                      } else {
                        userCode = widget.source[index].value.userCode;
                        personName = widget.source[index].value.personName;
                      }
                      if (_selectIndexList.contains(userCode)) {
                        _selectIndexList.remove(userCode);
                        _selectNameList.remove(personName);
                      } else {
                        if (_selectIndexList.length <
                            (widget.maxMembers ?? 4)) {
                          _selectNameList.add(personName);
                          _selectIndexList.add(userCode);
                        } else {
                          PromptBox.toast(i18nBook.realTimeConsultation
                              .theUpperLimitHasBeenReached.t);
                          return;
                        }
                      }

                      widget.onChangeIndex!(
                        _selectIndexList.toSet().toList(),
                      );
                      widget.onChangeString!(
                        _selectNameList.toSet().toList(),
                      );
                    });
                  },
                  child: FContainer(
                    padding: EdgeInsets.symmetric(
                      vertical: 15,
                    ),
                    margin: EdgeInsets.symmetric(
                      horizontal: 15,
                    ),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Color.fromRGBO(231, 231, 231, 1),
                          width: 0.5,
                        ),
                      ),
                    ),
                    child: _buildChoiceRow(index),
                  ),
                ),
              );
            },
          ),
        )),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _selectIndexList = widget.value ?? [];
    _selectNameList = widget.valueName ?? [];
    _oldSelectIndexList.addAll(widget.value ?? []);
    _oldSelectNameList.addAll(widget.valueName ?? []);
    Get.find<IAppointmentConsultation>()
        .onCancelAddedParticipant
        .addListener(_onCancelAddedParticipant);
  }

  ///编辑所选的行
  FWidget _buildChoiceRow(int index) {
    var sourceValue = widget.source[index];
    String userCode;
    String personName;
    String role;
    String headImageUrl;
    List<String> areasOfExpertise;
    if (sourceValue.value is SimpleInfoItem) {
      userCode = sourceValue.value.itemCode;
      personName = sourceValue.value.name ?? '';
      role = sourceValue.value.role ?? '';
      headImageUrl = sourceValue.value.image ?? '';
      areasOfExpertise = sourceValue.value.des ?? [];
    } else {
      userCode = widget.source[index].value.userCode;
      personName = widget.source[index].value.personName;
      role = widget.source[index].value.role;
      headImageUrl = widget.source[index].value.headPortrait;
      areasOfExpertise = widget.source[index].value.areasOfExpertise ?? [];
    }

    return FRow(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        FExpanded(
          child: FRow(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              FExpanded(
                child: FRow(
                  children: [
                    _buildImage(headImageUrl),
                    FExpanded(
                      child: FColumn(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          FText(
                            personName,
                            style: fontStyle,
                          ),
                          if (role.isNotEmpty)
                            FText(
                              role.toString(),
                              style: fontStyle,
                            ),
                          if (areasOfExpertise.isNotEmpty)
                            FText(
                              i18nBook.user.skilledAreaWithDevider.t +
                                  areasOfExpertise.join(
                                    "，",
                                  ),
                              style: fontStyle,
                              overflow: TextOverflow.ellipsis,
                            ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              FContainer(
                width: 25,
                height: 25,
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Color.fromRGBO(141, 141, 141, 1),
                    width: 0.5,
                  ),
                ),
                child: _selectIndexList.contains(userCode)
                    ? FContainer(
                        decoration: BoxDecoration(
                          color: Theme.of(context).primaryColor,
                        ),
                        child: FCenter(
                          child: FContainer(
                            child: FIcon(
                              Icons.check,
                              size: 20,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      )
                    : FContainer(),
              ),
            ],
          ),
        ),
        FSizedBox(
          width: 15,
        ),
      ],
    );
  }

  FWidget _buildImage(String? isImage) {
    var child;
    isImage!.isEmpty
        ? child = FImage.asset(
            'assets/images/avatar_man.png',
            width: 50,
            height: 50,
            fit: BoxFit.cover,
          )
        : child = FImage.network(
            isImage,
            width: 50,
            height: 50,
            fit: BoxFit.cover,
          );
    return FContainer(
      margin: EdgeInsets.only(
        right: 15,
      ),
      child: FClipRRect(
        borderRadius: BorderRadius.circular(
          25,
        ),
        child: child,
      ),
    );
  }

  /// 取消事件的监听
  void _onCancelAddedParticipant(sender, e) {
    if (e) {
      widget.onChangeIndex!(
        _oldSelectIndexList.toSet().toList(),
      );
      widget.onChangeString!(
        _oldSelectNameList.toSet().toList(),
      );
    }
  }
}
