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

import 'package:flutter/cupertino.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_rx/src/rx_workers/rx_workers.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/data/bean/upload_info.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:keyboard/utils/atmob_log.dart';
import 'package:keyboard/utils/toast_util.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../../../data/api/request/intimacy_reply_analyze_request.dart';
import '../../../../data/api/response/intimacy_analyze_reply_config_response.dart';
import '../../../../data/api/response/intimacy_reply_analyze_response.dart';
import '../../../../data/bean/option_select_config.dart';
import '../../../../data/bean/option_select_item.dart';
import '../../../../data/bean/reply_mode.dart';
import '../../../../data/repository/account_repository.dart';
import '../../../../data/repository/intimacy_analyze_repository.dart';
import '../../../../dialog/login/login_dialog.dart';
import '../../../../utils/clipboard_util.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/upload/upload_file_manager.dart';
import '../../../../utils/upload/upload_scene_type.dart';
import '../../../../utils/upload/upload_state.dart';
import '../../../store/new_discount/new_discount_page.dart';
import '../../../store/store_page.dart';

/// 识图回复Controller
@injectable
class ScanImageReplyController extends BaseController {
  final String _tag = "ScanImageReplyController";

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

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

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

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

  AccountRepository accountRepository;

  /// 回复语气选项列表
  RxList<OptionSelectConfig> replyToneOptionSelectConfigList =
      <OptionSelectConfig>[].obs;

  /// 当前选择的语气
  Rxn<OptionSelectItem> currentSelectReplyToneOption = Rxn();

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

  /// 上传图片列表
  Rxn<UploadInfo> uploadInfo = Rxn();

  /// Ai模型列表
  RxList<ReplyMode> replyModelList = <ReplyMode>[].obs;

  /// 当前应用的Ai模型
  Rxn<ReplyMode> currentReplyMode = Rxn();

  /// 回复语气列表
  RxList<String> replyToneList = <String>[].obs;

  /// 是否有识别结果
  Rx<bool> hasScanResult = false.obs;

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

  @override
  void onInit() {
    super.onInit();
    // 监听配置更新，刷新选项列表
    AtmobLog.d(_tag, "监听 <识图回复> 配置更新，刷新选项列表");
    ever(intimacyAnalyzeConfigHelper.intimacyAnalyzeReplyConfig, (
      IntimacyAnalyzeReplyConfigResponse? config,
    ) {
      if (config != null) {
        _initReplyToneOptionSelectConfigList(config);
        _initReplyModeList(config);
      }
    });
  }

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

  /// 初始化回复语气列表
  void _initReplyToneOptionSelectConfigList(
    IntimacyAnalyzeReplyConfigResponse config,
  ) {
    // 语气列表
    var toneList = config.tones ?? [];
    if (toneList.isNotEmpty) {
      var newList =
          toneList.map((item) {
            return OptionSelectItem(
              "${item.emoji} ${item.title}",
              // 提交给服务端的数据，不能包含表情字符
              item.title ?? "",
            );
          }).toList();

      replyToneOptionSelectConfigList.clear();
      replyToneOptionSelectConfigList.add(
        OptionSelectConfig(StringName.chooseReplyTone, "", newList),
      );
      replyToneOptionSelectConfigList.refresh();
    }
  }

  /// 初始化回复模式
  void _initReplyModeList(IntimacyAnalyzeReplyConfigResponse config) {
    var modeList = config.modes;
    replyModelList.addAll(modeList);
    replyModelList.refresh();

    // 默认选中第一个模式
    if (modeList.isNotEmpty) {
      currentReplyMode.value = replyModelList[0];
      currentReplyMode.refresh();
    }
  }

  /// 选中回复语气的选项
  void selectReplyToneOption(
    OptionSelectConfig rowConfig,
    OptionSelectItem optionItem,
  ) {
    // 先全部反选
    rowConfig.options =
        rowConfig.options.map((ele) {
          ele.selected = false;
          return ele;
        }).toList();
    // 再勾选当前的选中项
    optionItem.selected = true;
    // 由于Rx响应式变量，无法监听对象中嵌套对象的某个属性的变化，导致页面不会刷新，需要手动刷新页面
    replyToneOptionSelectConfigList.refresh();

    // 保存当前选择的语气选项
    currentSelectReplyToneOption.value = optionItem;
  }

  /// 重置回复语气选项
  void resetReplyToneOption() {
    var newConfigList =
        replyToneOptionSelectConfigList.toList().map((
          OptionSelectConfig rowConfig,
        ) {
          // 全部取消选中
          var newOptionList =
              rowConfig.options.map((item) {
                item.selected = false;
                return item;
              }).toList();
          rowConfig.options = newOptionList;
          return rowConfig;
        }).toList();
    replyToneOptionSelectConfigList.value = newConfigList;
    replyToneOptionSelectConfigList.refresh();
  }

  /// 切换回复模型
  void switchReplyMode(ReplyMode newMode) {
    currentReplyMode.value = newMode;
  }

  /// 点击上传截图按钮
  void clickUploadScreenshotBtn(BuildContext context) async {
    // 分析中，禁止上传
    if (isResultGenerating.value) {
      ToastUtil.show(StringName.intimacyAnalyseIngPleaseWait);
      return;
    }
    // 跳转到图片选择，并返回选择的图片列表
    List<AssetEntity>? selectedAssetList = await ImagePickerUtil.pickImage(
      context,
      // 只能最多上传1张图片
      maxAssetsCount: 1,
    );
    // 切换为上传页
    if (selectedAssetList?.isNotEmpty == true) {
      // 重置数据
      _resetData();
      // 上传图片
      _handleSelectedAssetUpload(selectedAssetList!);
    }
  }

  /// 点击再试试按钮
  void clickRetryBtn() {
    // 分析中，重试
    if (isResultGenerating.value) {
      ToastUtil.show(StringName.intimacyAnalyseIngPleaseWait);
      return;
    }
    _resetData();
  }

  /// 重置数据
  void _resetData() {
    isResultGenerating.value = false;
    hasScanResult.value = false;
    replyToneList.clear();
    resetReplyToneOption();
    currentSelectReplyToneOption.value = null;
  }

  /// 点击获取回复按钮
  void clickGetReplyBtn() 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 = [uploadInfo.value?.fileBackendPath ?? ""];
    // 选择的回复语气
    String title = currentSelectReplyToneOption.value?.value ?? "";
    // 当前选择的回复模式
    String mode = currentReplyMode.value?.value ?? "";

    if (imageList.isEmpty) {
      ToastUtil.show(StringName.noUploadScreenshotTip);
      return;
    }
    if (title.isEmpty) {
      ToastUtil.show(StringName.noChooseReplyToneTip);
      return;
    }
    if (mode.isEmpty) {
      ToastUtil.show(StringName.noChooseModeTip);
      return;
    }

    // 切换为生成中
    isResultGenerating.value = true;
    hasScanResult.value = false;

    replyToneList.clear();
    // 添加一条，正在回复的条目
    replyToneList.add("");
    replyToneList.refresh();

    // 请求分析截图
    try {
      IntimacyReplyAnalyzeResponse response = await intimacyAnalyzeRepository
          .intimacyReplyAnalyze(
            IntimacyReplyAnalyzeRequest(imageList, title, mode),
          );
      var newList = response.list ?? [];

      // 刷新列表
      replyToneList.clear();
      replyToneList.addAll(newList);
      replyToneList.refresh();

      // 改为已有识别结果
      hasScanResult.value = true;
    } catch (error) {
      // 发生异常
      isResultGenerating.value = false;
      hasScanResult.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);
      }
    } finally {
      // 生成结束
      isResultGenerating.value = false;
    }
  }

  /// 删除上传信息
  void deleteUploadInfo(UploadInfo info) {
    uploadFileManager.deleteUploadInfo(info);
    uploadInfo.value = info;
    uploadInfo.refresh();
  }

  /// 处理文件上传
  void _handleSelectedAssetUpload(List<AssetEntity> selectedAssetList) async {
    for (var entity in selectedAssetList) {
      // 获取文件路径
      File? file = await entity.file;
      if (file == null) {
        continue;
      }
      // 添加到上传列表
      uploadInfo.value = 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,
            );
          }
        },
      );
    }
  }

  /// 更新上传信息
  void _updateUploadInfo(UploadInfo info) {
    // 更新上传信息
    uploadInfo.value = info;
    uploadInfo.refresh();
  }

  /// 是否正在上传
  bool _isUploading() {
    return uploadInfo.value?.uploadState == UploadState.uploading.state;
  }

  /// 拷贝回复语气
  void copyReplyTone(String replyTone) {
    ClipboardUtil.copyToClipboard(replyTone);
    ToastUtil.show(StringName.copySuccess);
  }
}
