import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/dialog/login/login_dialog.dart';
import 'package:keyboard/module/store/new_discount/new_discount_page.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../../../data/api/request/intimacy_reply_chat_request.dart';
import '../../../../data/api/response/intimacy_analyze_chat_config_response.dart';
import '../../../../data/api/response/intimacy_chat_analyze_response.dart';
import '../../../../data/bean/member_info.dart';
import '../../../../data/bean/option_select_config.dart';
import '../../../../data/bean/option_select_item.dart';
import '../../../../data/bean/upload_info.dart';
import '../../../../data/repository/account_repository.dart';
import '../../../../data/repository/intimacy_analyze_repository.dart';
import '../../../../utils/atmob_log.dart';
import '../../../../utils/error_handler.dart';
import '../../../../utils/http_handler.dart';
import '../../../../utils/image_picker_util.dart';
import '../../../../utils/intimacy_analyze_config_helper.dart';
import '../../../../utils/sse_parse_util.dart';
import '../../../../utils/toast_util.dart';
import '../../../../utils/upload/upload_file_manager.dart';
import '../../../../utils/upload/upload_scene_type.dart';
import '../../../../utils/upload/upload_state.dart';
import '../../../store/store_page.dart';

/// 对话分析Controller
@injectable
class ConversationAnalysisController extends BaseController {
  final String _tag = "ConversationAnalysisController";

  /// 上传场景
  final UploadSceneType uploadSceneType = UploadSceneType.conversationAnalysis;

  /// 亲密度分析帮助类
  IntimacyAnalyzeConfigHelper intimacyAnalyzeConfigHelper;

  /// 文件上传管理器
  UploadFileManager uploadFileManager;

  /// 亲密度分析模块的Repository
  IntimacyAnalyzeRepository intimacyAnalyzeRepository;

  /// 用户信息Repository
  AccountRepository accountRepository;

  /// 是否是上传页
  Rx<bool> isUploadPage = false.obs;

  /// 当前用户信息
  Rxn<MemberInfo> get userInfo => accountRepository.memberStatusInfo;

  /// 选项列表
  RxList<OptionSelectConfig> optionSelectConfigList =
      <OptionSelectConfig>[].obs;

  /// 当前选择的选项
  Rxn<OptionSelectItem> currentSelectOption = Rxn();

  /// 报告数据
  RxString reportData = ''.obs;

  /// 是否生成中
  RxBool isResultGenerating = false.obs;

  /// 上传图片列表
  RxList<UploadInfo> uploadInfoList = <UploadInfo>[].obs;

  /// 对话分析的订阅（SSE）
  StreamSubscription<Message>? _intimacyChatAnalyzeSubscription;

  ConversationAnalysisController(
    this.intimacyAnalyzeConfigHelper,
    this.uploadFileManager,
    this.intimacyAnalyzeRepository,
    this.accountRepository,
  );

  @override
  void onInit() {
    super.onInit();
    // 监听配置更新，刷新选项列表
    AtmobLog.d(_tag, "监听 <对话分析> 配置更新，刷新选项列表");
    ever(intimacyAnalyzeConfigHelper.intimacyAnalyzeChatConfig, (
      IntimacyAnalyzeChatConfigResponse? config,
    ) {
      if (config != null) {
        _initOptionSelectConfigList(config);
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    // 初次加载配置
    var config = intimacyAnalyzeConfigHelper.intimacyAnalyzeChatConfig.value;
    if (config != null) {
      _initOptionSelectConfigList(config);
    }
  }

  @override
  void onClose() {
    // 删除文件上传记录
    uploadFileManager.deleteUploadInfoBySceneType(uploadSceneType);
    // 取消SSE流数据订阅
    _intimacyChatAnalyzeSubscription?.cancel();
    super.onClose();
  }

  /// 初始化选项列表
  void _initOptionSelectConfigList(IntimacyAnalyzeChatConfigResponse config) {
    optionSelectConfigList.clear();

    // 对于Ta
    var forTaConfig = config.forTa;
    if (forTaConfig != null && forTaConfig.isNotEmpty) {
      var itemList =
          forTaConfig.map((item) {
            var title = item.title;
            return OptionSelectItem(title, title);
          }).toList();
      optionSelectConfigList.add(
        OptionSelectConfig(StringName.forTa, "", itemList),
      );
    }
    // 对于我
    var forMeConfig = config.forMe;
    if (forMeConfig != null) {
      var itemList =
          forMeConfig.map((item) {
            var title = item.title;
            return OptionSelectItem(title, title);
          }).toList();
      optionSelectConfigList.add(
        OptionSelectConfig(StringName.forMe, "", itemList),
      );
    }

    optionSelectConfigList.refresh();
  }

  /// 选中选项
  void selectOption(OptionSelectConfig rowConfig, OptionSelectItem optionItem) {
    // 更新当前选中项
    currentSelectOption.value = optionItem;

    // 将所有预测方向都反选
    for (var config in optionSelectConfigList) {
      config.options =
          config.options.map((ele) {
            ele.selected = false;
            return ele;
          }).toList();
    }
    // 再勾选当前的选中项
    optionItem.selected = true;
    // 由于Rx响应式变量，无法监听对象中嵌套对象的某个属性的变化，导致页面不会刷新，需要手动刷新页面
    optionSelectConfigList.refresh();
  }

  /// 点击解锁按钮
  void clickUnlockBtn(BuildContext context) async {
    // 跳转去会员活动页
    NewDiscountPage.start();
  }

  /// 点击查看分析按钮
  void clickLookAnalyseBtn(BuildContext context) async {
    // 非Vip，跳转到商店页
    bool isVip = accountRepository.memberStatusInfo.value?.isMember ?? false;
    if (!isVip) {
      ToastUtil.show(StringName.needVipTip);
      NewDiscountPage.start();
      return;
    }

    // 上传中，禁止处理
    if (_isUploading()) {
      ToastUtil.show(StringName.uploadingTip);
      return;
    }

    // 上传的图片后端地址
    List<String> imageList =
        uploadInfoList.map((item) {
          return item.fileBackendPath ?? "";
        }).toList();
    // 选择的标题
    String title = currentSelectOption.value?.value ?? "";

    if (imageList.isEmpty) {
      ToastUtil.show(StringName.noUploadConversationImageTip);
      return;
    }
    if (title.isEmpty) {
      ToastUtil.show(StringName.noChooseOptionTip);
      return;
    }

    // 切换为生成报告
    isUploadPage.value = false;
    isResultGenerating.value = true;
    reportData.value = "";

    Stream<Message> stream = await intimacyAnalyzeRepository
        .intimacyChatAnalyze(IntimacyChatAnalyzeRequest(imageList, title));
    _intimacyChatAnalyzeSubscription = stream.listen(
      (message) {
        // 流数据更新
        String json = message.data;
        // 解析json为实体类
        IntimacyChatAnalyzeResponse response =
            IntimacyChatAnalyzeResponse.fromJson(jsonDecode(json));
        String reportContent = response.choices?[0].delta?.content ?? "";
        reportData.value = (reportData.value + reportContent);
      },
      onError: (error) {
        // 发生错误
        isResultGenerating.value = false;
        AtmobLog.e(_tag, error.toString());
        if (error is ServerErrorException) {
          // 需要Vip权限
          if (error.code == 1005) {
            ToastUtil.show(error.message);
            NewDiscountPage.start();
          } else {
            ToastUtil.show(error.message);
          }
        } else {
          ErrorHandler.toastError(error);
        }
      },
      onDone: () {
        // 流关闭
        isResultGenerating.value = false;
      },
    );
  }

  /// 点击上传按钮
  void clickUploadBtn(BuildContext context) async {
    // 计算还可以上传多少张图片
    int count =
        intimacyAnalyzeConfigHelper.getMaxAssetsCount() - uploadInfoList.length;
    // 跳转到图片选择，并返回选择的图片列表
    List<AssetEntity>? selectedAssetList = await ImagePickerUtil.pickImage(
      context,
      maxAssetsCount: count,
    );
    // 选择了图片，切换到上传视图
    if (selectedAssetList != null) {
      if (selectedAssetList.isNotEmpty) {
        _handleSelectedAssetUpload(selectedAssetList);
        isUploadPage.value = true;
      }
    }
  }

  /// 删除上传信息
  void deleteUploadInfo(UploadInfo uploadInfo) {
    uploadFileManager.deleteUploadInfo(uploadInfo);
    uploadInfoList.removeWhere((item) {
      return item.id == uploadInfo.id;
    });
    uploadInfoList.refresh();
  }

  /// 是否正在上传
  bool _isUploading() {
    var list = uploadInfoList.toList();

    for (var item in list) {
      if (item.uploadState == UploadState.uploading.state) {
        return true;
      }
    }

    return false;
  }

  /// 处理文件上传
  void _handleSelectedAssetUpload(List<AssetEntity> selectedAssetList) async {
    for (var entity in selectedAssetList) {
      // 获取文件路径
      File? file = await entity.file;
      if (file == null) {
        continue;
      }
      // 添加到上传列表
      uploadInfoList.add(
        uploadFileManager.uploadFile(
          sceneType: uploadSceneType,
          file: file,
          onUploadInfoUpdateCallback: (uploadInfo) {
            // 上传信息更新时回调，更新UI
            _updateUploadInfo(uploadInfo);
          },
          onUploadFailCallback: (error) {
            // 接口业务异常
            if (error is ServerErrorException) {
              ErrorHandler.toastError(error);
            } else {
              // 其他异常
              ErrorHandler.toastError(
                error,
                message: StringName.noUploadScreenshotTip,
              );
            }
          },
        ),
      );
      uploadInfoList.refresh();
    }
  }

  /// 更新上传信息
  void _updateUploadInfo(UploadInfo uploadInfo) {
    // 更新上传信息
    var newList = [...uploadInfoList];
    newList.map((item) {
      if (item.id == uploadInfo.id) {
        return uploadInfo;
      }
      return item;
    }).toList();
    uploadInfoList.value = newList;
  }
}
