import 'package:chatwoot_flutter_sdk/chatwoot_sdk.dart';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';

import 'package:kaer_with_panels/app/utils/kr_secure_storage.dart';

class KRChatwootController {
  // 配置参数
  final String baseUrl = 'https://app.chatwoot.com';
  final String inboxIdentifier = 'YXQmh16ymNYW1SVybhnoQQ9w';

  /// 获取当前用户信息
  /// 建议从你的全局 UserState 或本地存储中动态获取
  ChatwootUser get chatUser {
    final appRunData = KRAppRunData.getInstance();
    final deviceId = appRunData.deviceId;
    final authType = appRunData.kr_authType;
    final account = appRunData.kr_account.value;

    // 邮箱如果是邮箱格式则使用，否则构造一个唯一的虚拟邮箱以满足格式要求
    String email = '';
    if (authType == 'device') {
      email = account.toString();
    } else {
      email = '待绑定$deviceId';
    }

    return ChatwootUser(
      identifier: account, // 必填：用于关联历史聊天记录
      name: deviceId,
      email: email,
    );
  }

  /// 处理文件/附件选择逻辑
  Future<List<String>> onFilePicker() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        allowMultiple: true,
        type: FileType.any,
      );

      if (result != null && result.paths.isNotEmpty) {
        // 过滤掉 null 路径并转换为 String 列表
        return result.paths.whereType<String>().toList();
      }
    } catch (e) {
      debugPrint("KRChatwoot: 文件选择失败 - $e");
    }
    return [];
  }

// 可以在这里添加更多业务方法，例如：
// void trackEvent(String eventName) { ... }
}