import 'dart:convert';
import 'dart:typed_data';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/rpc.dart';

/// 自定义图像数据渲染器
class CustomImageLoader extends StatefulWidget {
  const CustomImageLoader({super.key, required this.fileToken});
  final String fileToken;
  @override
  State<CustomImageLoader> createState() => _CustomImageLoaderState();
}

class _CustomImageLoaderState extends State<CustomImageLoader> {
  // 通过 fileToken 调接口获取图片数据,获取完数据后加载图像
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Uint8List>(
      future: _getImageData(),
      builder: (BuildContext context, AsyncSnapshot<Uint8List> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return Center(child: Text('加载失败，请重试'));
          }
          return Image.memory(snapshot.data!);
        } else {
          return Center(child: CircularProgressIndicator());
        }
      },
    );
  }

  Future<Uint8List> _getImageData() async {
    final String openId = Store.user.token;
    AppletAPIDownloadFileResult result =
        await rpc.appletAPI.downloadFileAsync(DownloadFileRequest(
      openId: openId,
      fileToken: widget.fileToken,
    ));
    final String? fileBytesBase64 = result.fileString;
    if (fileBytesBase64 == null) {
      throw Exception("fileBytes is null");
    }
    return base64Decode(fileBytesBase64);
  }
}
