import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/pages/organization/org_personnel/controller.dart';
import 'package:flyinsono/pages/user/user_device/controller.dart';
import 'package:get/get.dart';

// List<String> shareList = [];

class OrgMember extends StatefulWidget implements FInteractiveContainer {
  @override
  final String pageName = 'OrgMember';

  ///标题
  final FWidget title;

  ///位置文字
  final FWidget positationalText;

  ///图像
  final FWidget? image;

  ///是否图像
  final bool? isImage;

  ///提示文字
  final String? hintText;

  ///点击事件
  final Function(String userId, bool isChecked) onClick;

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

  ///列表对象
  final UserDTO listObject;

  /// 初始选中状态
  final bool initCheckedStatus;

  const OrgMember({
    Key? key,
    required this.title,
    required this.positationalText,
    required this.listObject,
    required this.onClick,
    this.image,
    this.initCheckedStatus = false,
    this.isImage = false,
    this.hintText = '',
    this.imageUrl = '',
  }) : super(key: key);

  @override
  State<OrgMember> createState() => _OrgMemberState();
}

///选择用户
class SelectUser extends StatefulWidget implements FPage {
  final String? code;
  final String? name;
  @override
  final String pageName;
  SelectUser({
    Key? key,
    this.pageName = 'LabeledCheckbox',
    this.name = '',
    this.code = '',
  }) : super(key: key);

  set value(String value) {}

  @override
  State<SelectUser> createState() => _SelectUser();
}

class _OrgMemberState extends State<OrgMember> {
  /// 当前选中状态
  bool currentCheckedStatus = false;
  @override
  FWidget build(BuildContext context) {
    return FMaterial(
      color: Colors.white,
      child: FColumn(
        children: [
          FSlidable(
            child: FInkWell(
              onTap: () {
                setState(() {
                  currentCheckedStatus = !currentCheckedStatus;
                });
                widget.onClick(
                    widget.listObject.userCode!, currentCheckedStatus);
              },
              child: FContainer(
                margin: EdgeInsets.symmetric(
                  horizontal: 20,
                ),
                padding: EdgeInsets.symmetric(
                  horizontal: 13,
                  vertical: 10,
                ),
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Color.fromRGBO(228, 228, 228, 1),
                  ),
                  borderRadius: BorderRadius.all(Radius.circular(4)),
                ),
                child: FContainer(
                  child: FRow(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      FRow(
                        children: [
                          widget.image!,
                          FSizedBox(
                            width: 12,
                          ),
                          FColumn(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              widget.title,
                              FSizedBox(
                                height: 3,
                              ),
                              widget.positationalText,
                            ],
                          ),
                        ],
                      ),
                      QuickFWidget(
                        Checkbox(
                          value: currentCheckedStatus,
                          onChanged: (v) {
                            widget.onClick(widget.listObject.userCode!, v!);
                            setState(
                              () {
                                currentCheckedStatus = v;
                              },
                            );
                            // widget.onClick.call();
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          FSizedBox(
            height: 15,
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    currentCheckedStatus = widget.initCheckedStatus;
  }
}

class _SelectUser extends State<SelectUser> {
  final orgPesonnelController = Get.find<OrgPesonnelController>();
  final controller = Get.put(DeviceController());
  final ScrollController _scrollController = ScrollController();

  /// 初始时已分享的用户
  List<String> sharedUserList = [];

  @override
  FWidget build(BuildContext context) {
    FWidget titleName() {
      return widget.name!.isNotEmpty
          ? FMaterial(
              color: Colors.white,
              child: FColumn(
                children: [
                  FContainer(
                    padding: EdgeInsets.symmetric(horizontal: 20),
                    height: 50,
                    decoration: BoxDecoration(
                      color: Colors.white,
                    ),
                    alignment: Alignment.centerLeft,
                    child: FText(
                      widget.name!,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  FContainer(
                    margin: EdgeInsets.symmetric(horizontal: 20),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Color.fromRGBO(245, 245, 245, 1),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            )
          : FText('');
    }

    FWidget _buildImage(String? isImage) {
      var child;
      isImage!.isEmpty
          ? child = FImage.asset('assets/images/avatar_man.png')
          : child = FImage.network(isImage);
      return child;
    }

    return FScaffold(
      appBar: FAppBar(
        title: FText(i18nBook.user.shareDevice.t),
        actions: [
          FGestureDetector(
            name: "submitMobileUsers",
            businessParent: widget,
            behavior: HitTestBehavior.opaque,
            onTap: () {
              controller.submitMobileUsers();
            },
            child: FContainer(
              padding: EdgeInsets.all(15),
              child: FCenter(
                child: FText(i18nBook.common.confirm.t),
              ),
            ),
          ),
          FSizedBox(
            width: 15,
          )
        ],
        centerTitle: true,
        elevation: 0,
        leading: FIconButton(
          businessParent: widget,
          name: "back",
          icon: FIcon(Icons.arrow_back_ios_new),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: FMaterial(
        color: Colors.white,
        child: FSafeArea(
          child: FColumn(
            children: [
              titleName(),
              FExpanded(
                child: FObx(() {
                  /// 所有用户
                  final tableDataSource = orgPesonnelController
                      .state.tableDataSource
                      .where((element) => element.userCode != Store.user.code)
                      .toList();
                  return FAlwaysScrollListView(
                    scrollController: _scrollController,
                    child: QuickFWidget(ScrollConfiguration(
                      behavior: ScrollConfiguration.of(context)
                          .copyWith(scrollbars: false),
                      child: FListView.builder(
                        shrinkWrap: true,
                        controller: _scrollController,
                        itemCount: tableDataSource.length,
                        itemBuilder: (context, index) {
                          return OrgMember(
                            image: FCircleAvatar(
                              child: _buildImage(
                                  '${tableDataSource.toList()[index].headImageUrl}'),
                            ),
                            title: FText(
                              '${tableDataSource.toList()[index].displayName}',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 15,
                              ),
                            ),
                            listObject: tableDataSource[index],
                            positationalText: FText(
                              '${tableDataSource.toList()[index].positionName}',
                              style: TextStyle(
                                color: Color.fromRGBO(143, 141, 140, 1),
                                fontSize: 14,
                              ),
                            ),
                            onClick: onItemClick,
                            initCheckedStatus: sharedUserList.contains(
                                tableDataSource.toList()[index].userCode),
                          );
                        },
                      ),
                    )),
                  );
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    sharedUserList =
        controller.state.tableDataSource.map((e) => e.userCode!).toList();
    super.initState();
  }

  /// 选中事件发生时更新 state.shareUserSelectList
  void onItemClick(String userId, bool status) {
    if (status) {
      sharedUserList.add(userId);
    } else {
      sharedUserList.remove(userId);
    }
    controller.state.shareUserSelectList = sharedUserList.toSet().toList();
  }
}
