import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/controller/im_user_info_controller.dart';
import 'package:loopin/IM/im_friend_listeners.dart';
import 'package:loopin/components/my_qrcode.dart';
import 'package:loopin/components/my_toast.dart';
import 'package:loopin/components/scan_util.dart';
import 'package:loopin/utils/index.dart';
import 'package:loopin/utils/scan_code_type.dart';

class AddFriend extends StatefulWidget {
  const AddFriend({super.key});
  @override
  State<AddFriend> createState() => _AddFriendState();
}

class _AddFriendState extends State<AddFriend> {
  final TextEditingController txtcontroller = TextEditingController();
  final FocusNode focusNode = FocusNode();

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

  void handleScanResult(String code) {
    logger.w('扫码结果11111111111111111111111：$code');

    // 使用外部枚举的方法检查扫码类型
    final scanType = ScanCodeType.fromCode(code);
    if (scanType != null) {
      final value = code.substring(scanType.prefix.length + 1); // 获取后缀值
      _processScanCode(scanType, value);
    } else {
      // 未知类型的码
      Get.snackbar('未知的二维码类型', '无法识别此二维码: $code');
    }
  }

  // 处理不同类型的扫码结果
  void _processScanCode(ScanCodeType type, String value) {
    switch (type) {
      case ScanCodeType.verification:
        _handleVerificationCode(value);
        break;
      case ScanCodeType.friend:
        _handleFriendCode(value);
        break;
      case ScanCodeType.promotion:
        _handlePromotionCode(value);
        break;
    }
  }

  // 处理核销码
  void _handleVerificationCode(String value) async {
    logger.w('处理核销码: $value');
    // 带着核销码，跳转到商家的商品详情页面，引导商家去手动点击核销按钮
    final controller = Get.find<ImUserInfoController>();
    final role = controller.role.value;
    final isSeller = Utils.hasRole(role, 2);
    if (isSeller) {
      // 带着核销码，跳转到商家的商品详情页面，引导商家去手动点击核销按钮
      Get.toNamed('/sellerOrder/detail', arguments: {'writeOffCodeId': value});
    } else {
      //
      MyToast().tip(title: '无法识别');
    }
    // Get.toNamed('/sellerOrder/detail', arguments: {'writeOffCodeId': value});
  }

  // 处理好友码
  void _handleFriendCode(String value) {
    logger.w('处理好友码: $value');
    // 模仿抖音，去个人页面手动点击关注
    final myID = Get.find<ImUserInfoController>().userID.value;
    if (myID != value) {
      Get.toNamed('/vloger', arguments: {'memberId': value});
    } else {
      MyToast().tip(title: '这是给别人扫的，扫自己没用', position: 'top');
    }
  }

  // 处理推广码
  void _handlePromotionCode(String value) {
    logger.w('处理推广码: $value');
    Get.toNamed('/vloger', arguments: {'memberId': value});
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        focusNode.unfocus();
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('添加好友'),
          titleTextStyle: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
          centerTitle: true,
        ),
        body: ListView(
          children: [
            // 搜索框
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: TextField(
                controller: txtcontroller,
                focusNode: focusNode,
                decoration: InputDecoration(
                  hintText: '请输入昵称',
                  prefixIcon: const Icon(Icons.search),
                  suffixIcon: TextButton(
                    child: Text('搜索'),
                    onPressed: () {
                      // 点击按钮搜索
                      final value = txtcontroller.text.trim();
                      if (value.isNotEmpty) {
                        // 跳转搜索页
                        focusNode.unfocus();
                        Get.toNamed(
                          '/search-result',
                          arguments: {'searchWords': value, 'tab': 2},
                        );
                      }
                    },
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(30),
                    borderSide: BorderSide.none,
                  ),
                  filled: true,
                  fillColor: Colors.grey[200],
                ),
                onSubmitted: (value) {
                  if (value.trim().isNotEmpty) {
                    // 跳转搜索页
                    focusNode.unfocus();
                    Get.toNamed(
                      '/search-result',
                      arguments: {'searchWords': value, 'tab': 2},
                    );
                  }
                },
              ),
            ),

            const Divider(),

            // 功能入口
            _buildEntry(
              icon: Icons.qr_code_scanner,
              title: "扫一扫",
              onTap: () {
                // Get.snackbar("扫一扫", "跳转到扫码页面");
                ScanUtil.openScanner(onResult: handleScanResult);
              },
            ),
            // _buildEntry(
            //   icon: Icons.contacts,
            //   title: "手机联系人",
            //   onTap: () {},
            // ),
            // _buildEntry(
            //   icon: Icons.people_alt_outlined,
            //   title: "好友推荐",
            //   onTap: () {},
            // ),

            SizedBox(height: 20),

            // 我的二维码
            MyQrcode(),
          ],
        ),
      ),
    );
  }

  Widget _buildEntry({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(icon, color: Colors.blue),
      title: Text(title),
      trailing: const Icon(Icons.arrow_forward_ios, size: 16),
      onTap: onTap,
    );
  }
}
