import 'package:flutter/material.dart';
import 'package:flyinsono/managers/interfaces/group.dart';
import 'package:flyinsono/pages/user/group_chat/widgets/group_members.dart';
import 'package:flyinsono/pages/user/group_chat/widgets/widgets.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/rpc.dart';
import '../index.dart';
import 'package:fis_i18n/i18n.dart';

/// 侧面信息抽屉
class InfoDrawer extends GetView<GroupChatController> {
  const InfoDrawer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Center(
        child: Container(
          width: double.infinity,
          padding: EdgeInsets.all(10),
          child: LayoutBuilder(builder: (context, constraints) {
            final maxHeight = constraints.maxHeight;
            return ListView(
              children: [
                Container(
                  constraints: BoxConstraints(
                    minHeight: maxHeight,
                  ),
                  // color: Colors.yellow,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        children: [
                          Text(
                            i18nBook.user.groupChatInfo.t,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          SizedBox(height: 10),
                          _buildGroupMember(),
                          SizedBox(height: 10),
                          _buildGroupDevice(),
                        ],
                      ),
                      // Column(
                      //   children: [
                      //     SizedBox(height: 20),
                      //     _buildCleanChatRecord(),
                      //     SizedBox(height: 10),
                      //     _buildExitGroup(),
                      //   ],
                      // ),
                    ],
                  ),
                ),
              ],
            );
          }),
        ),
      ),
    );
  }

  /// 构建群聊成员组
  Widget _buildGroupMember() {
    return Container(
      child: Obx(
        () {
          bool isShowAll = controller.state.totalMemberNum <= 8;
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                margin: EdgeInsets.only(bottom: 10, left: 5),
                child: Text(
                  i18nBook.user.groupMembersCount
                      .translate([controller.state.totalMemberNum]),
                ),
              ),
              GridView.builder(
                physics: NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemCount: isShowAll ? controller.state.totalMemberNum : 8,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  mainAxisSpacing: 5,
                  crossAxisSpacing: 5,
                  childAspectRatio: 0.8,
                ),
                itemBuilder: (context, index) {
                  return _buildMemberAvatar(
                    controller.eightMembers[index],
                  );
                },
              ),
              _buildViewAllButton(true),
            ],
          );
        },
      ),
    );
  }

  /// 构建群聊设备组
  Widget _buildGroupDevice() {
    return Container(
      child: Obx(
        () {
          bool isShowAll = controller.state.totalDeviceNum <= 8;

          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                margin: EdgeInsets.only(bottom: 10, left: 5),
                child: Text(
                  i18nBook.user.ultrasoundCount
                      .translate([controller.state.totalDeviceNum]),
                ),
              ),
              GridView.builder(
                physics: NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemCount: isShowAll ? controller.state.totalDeviceNum : 8,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  mainAxisSpacing: 5,
                  crossAxisSpacing: 5,
                  childAspectRatio: 0.8,
                ),
                itemBuilder: (context, index) {
                  return _buildDeviceAvatar(
                    controller.eightDevices[index],
                  );
                },
              ),
              _buildViewAllButton(false),
            ],
          );
        },
      ),
    );
  }

  static const _C_DEFAULT_MEMBER_URL = "assets/images/avatar_man.png";
  static const _C_DEFAULT_DEVICE_URL = "assets/images/mock_terminal.png";

  /// 构建群成员的头像和名字
  Widget _buildMemberAvatar(UserExtendDTO user) {
    return Container(
      padding: EdgeInsets.all(5),
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
            ),
            clipBehavior: Clip.antiAlias,
            child: AspectRatio(
              aspectRatio: 1,
              child: Image.network(
                user.headImageUrl ?? '',
                fit: BoxFit.fill,
                errorBuilder: (context, error, stackTrace) => Image.asset(
                  _C_DEFAULT_MEMBER_URL,
                  fit: BoxFit.fill,
                ),
              ),
            ),
          ),
          Expanded(
            child: FittedBox(
              fit: BoxFit.scaleDown,
              child: AbbreviatedText(
                child: Text(
                  user.displayName ?? "",
                  style: TextStyle(
                    fontSize: 12,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建超声机的头像和名字
  Widget _buildDeviceAvatar(DeviceInfoDTO device) {
    return Container(
      padding: EdgeInsets.all(5),
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
            ),
            clipBehavior: Clip.antiAlias,
            child: AspectRatio(
              aspectRatio: 1,
              child: Image.network(
                device.headPicUrl ?? '',
                fit: BoxFit.fill,
                errorBuilder: (context, error, stackTrace) => Image.asset(
                  _C_DEFAULT_DEVICE_URL,
                  fit: BoxFit.fill,
                ),
              ),
            ),
          ),
          Expanded(
            child: FittedBox(
              fit: BoxFit.scaleDown,
              child: AbbreviatedText(
                child: Text(
                  device.displayName ?? "",
                  style: TextStyle(
                    fontSize: 12,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建查看全部按钮
  Widget _buildViewAllButton(bool isMember) {
    return Container(
      width: double.infinity,
      child: TextButton(
        style: TextButton.styleFrom(
          foregroundColor: Colors.grey,
        ),
        onPressed: () {
          if (isMember) {
            Get.dialog(
              GroupMembersView(
                getMembersFunc: (keyword, index) async {
                  final groupManager = Get.find<IGroupManager>();
                  return await groupManager.getGroupUserSimpleItems(
                    userGroupCode: controller.userGroupCode,
                    keyword: keyword,
                    pageIndex: index,
                  );
                },
                isUserMember: true,
              ),
            );
          } else {
            Get.dialog(
              GroupMembersView(
                getMembersFunc: (keyword, index) async {
                  final groupManager = Get.find<IGroupManager>();
                  return await groupManager.getGroupDeviceSimpleItems(
                    userGroupCode: controller.userGroupCode,
                    keyword: keyword,
                    pageIndex: index,
                  );
                },
              ),
            );
          }
        },
        child: Text(
          isMember
              ? i18nBook.user.viewAllGroupMembers.t
              : i18nBook.user.viewAllUltrasounds.t,
          style: TextStyle(color: Colors.grey),
        ),
      ),
    );
  }

  /// 清空聊天记录按钮
  Widget _buildCleanChatRecord() {
    return Container(
      width: double.infinity,
      child: OutlinedButton(
        onPressed: () {},
        style: OutlinedButton.styleFrom(
          side: BorderSide(color: Colors.red),
          foregroundColor: Colors.red,
          // backgroundColor: Colors.white,
        ),
        child: Text(
          "清空群聊记录",
          style: TextStyle(color: Colors.red),
        ),
      ),
    );
  }

  /// 退出群聊按钮
  Widget _buildExitGroup() {
    return Container(
      width: double.infinity,
      child: OutlinedButton(
        onPressed: () {},
        style: OutlinedButton.styleFrom(
          side: BorderSide(color: Colors.red),
          foregroundColor: Colors.red,
          // backgroundColor: Colors.white,
        ),
        child: Text(
          "退出群聊",
          style: TextStyle(color: Colors.red),
        ),
      ),
    );
  }
}
