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

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/architecture/webapi/services/multipart_upload.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/components/lab_dialog.dart';
import 'package:flyinsono/lab/manager/interfaces/measure.dart';
import 'package:flyinsono/lab/manager/interfaces/project.dart';
import 'package:flyinsono/lab/style/lab_box_decoration.dart';
import 'package:flyinsono/pages/college/widgets/upload_media_library/index.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/widgets/entries_item.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:universal_html/html.dart' as html;
import 'package:fis_common/logger/logger.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:http/http.dart' as http;
import 'package:fis_common/index.dart';
import 'package:flyinsono/pages/college/widgets/upload_media_library/upload_media_library_web.dart';

class BodyMarkManager extends StatefulWidget {
  //应用名称
  final String applicationName;
  //分类名称
  final String categoryName;

  final void Function(String)? onBodyMarkSelected;

  final void Function()? onDelete;

  final bool isShowDelete;

  final String projectCode;

  BodyMarkManager({
    required this.applicationName,
    required this.categoryName,
    required this.projectCode,
    this.onBodyMarkSelected,
    this.isShowDelete = false,
    this.onDelete,
  });

  @override
  State<StatefulWidget> createState() {
    return BodyMarkManagerState();
  }
}

class BodyMarkManagerState extends State<BodyMarkManager> {
  final measureManager = Get.find<IMeasureManager>();
  final FEventHandler<double> onProcessChange = FEventHandler<double>();
  final FEventHandler<void> onCancelUpload = FEventHandler<void>();
  final fileTypes = [
    'image/jpeg',
    'image/png',
  ];
  String _selectedImage = '';
  List<String> _imageUrlList = [];
  BodyPatternsResult? _bodyPatternsInfos;
  bool _isDeleting = false;

  @override
  void initState() {
    _isDeleting = widget.isShowDelete;
    _initDatas();
    super.initState();
  }

  Future<void> _initDatas() async {
    /// 项目接口
    final projectService = Get.find<IProjectManager>();

    ResearchProjectDTO? detail = await projectService.getResearchProjectDetail(
      projectCode: widget.projectCode,
    );
    bool isAnimal = detail?.patientType == OrganizationPatientTypeEnum.Animals;
    BodyPatternsResult? result =
        await measureManager.getBodyPatternsByApplication(
      applicationName: (isAnimal || widget.applicationName.isNullOrEmpty)
          ? "Default"
          : widget.applicationName,
      categoryName: isAnimal ? "VET" : widget.categoryName,
    );
    if (result != null) {
      _bodyPatternsInfos = result;
      _imageUrlList = result.imageUrlList ?? [];
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_imageUrlList.isEmpty) {
      return SizedBox();
    }
    return SizedBox(
      width: 500,
      height: 500,
      child: Container(
        decoration: LabBoxDecoration.operatePanel,
        padding: EdgeInsets.all(10),
        child: Column(
          children: [
            Expanded(
              child: ListView(
                children: [
                  Wrap(
                    children: [
                      ..._imageUrlList.map((e) => _buildImage(e)).toList()
                    ],
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 5,
            ),
            _buildOperateButtons(),
          ],
        ),
      ),
    );
  }

  Widget _buildOperateButtons() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        ElevatedButton.icon(
          icon: const Icon(
            Icons.add,
            size: 20,
            color: LabColors.base800,
          ),
          style: ElevatedButton.styleFrom(
            elevation: 0.0,
            backgroundColor: LabColors.buttonColor,
          ),
          label: Text(
            "新增",
            style: TextStyle(
              fontSize: 16,
              color: LabColors.base800,
            ),
          ),
          onPressed: () {
            _uploadImage();
          },
        ),
        ElevatedButton.icon(
          icon: _isDeleting
              ? SizedBox.shrink()
              : const Icon(
                  Icons.delete,
                  size: 20,
                  color: LabColors.base800,
                ),
          style: ElevatedButton.styleFrom(
            elevation: 0.0,
            backgroundColor: LabColors.buttonColor,
          ),
          label: Text(
            _isDeleting ? '结束删除' : "删除",
            style: TextStyle(
              fontSize: 16,
              color: LabColors.base800,
            ),
          ),
          onPressed: () {
            widget.onDelete?.call();
            // setState(() {
            //  _isDeleting = !_isDeleting;
            //});
          },
        ),
        ElevatedButton.icon(
          icon: const Icon(
            Icons.restore,
            size: 20,
            color: LabColors.base800,
          ),
          style: ElevatedButton.styleFrom(
            elevation: 0.0,
            backgroundColor: LabColors.buttonColor,
          ),
          label: Text(
            "重置",
            style: TextStyle(
              fontSize: 16,
              color: LabColors.base800,
            ),
          ),
          onPressed: () {
            _resetImages();
          },
        ),
      ],
    );
  }

  Widget _buildImage(String e) {
    return Stack(
      children: [
        InkWell(
          onTap: () async {
            setState(() {
              _selectedImage = e;
            });
            var base64 = await downloadAndConvertToBase64(e);
            widget.onBodyMarkSelected?.call(base64);
          },
          child: Container(
            decoration: BoxDecoration(
                border: Border.all(
              color:
                  _selectedImage == e ? LabColors.base400 : Colors.transparent,
            )),
            child: Image.network(
              e,
              width: 100,
              height: 100,
              errorBuilder: (c, e, s) {
                return SizedBox(
                  width: 100,
                  height: 100,
                  child: Center(
                    child: Text(
                      '加载失败',
                      style: TextStyle(
                        fontSize: 16,
                        color: LabColors.base800,
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ),
        if (_isDeleting)
          Positioned(
            right: 0,
            top: 0,
            child: InkWell(
              onTap: () {
                _removeImage(e);
              },
              child: Icon(
                Icons.close,
                color: Colors.red,
              ),
            ),
          )
      ],
    );
  }

  Future<bool> _multipartUpload(
    html.File? file,
    int fileLength,
    int currentIndex, {
    FEventHandler<void>? onCancelUpload,
  }) async {
    // 创建一个Completer
    final completer = Completer<bool>();
    await rpc.storage.multipartUpload(
      file!,
      (v) {
        double totalProgress =
            ((currentIndex - 1) / fileLength) + ((1 / fileLength) * v);
        onProcessChange.emit(this, totalProgress);
      },
      onCancelUpload,
    ).then((result) async {
      if (result.isNotEmpty) {
        logger.i('Upload result:$result');
        // 完成上传时，设置completer完成状态并返回结果
        completer.complete(true);
        if (result.isNotEmpty) {
          setState(() {
            _imageUrlList.add(result);
          });
          _updateImageUrls();
        }
      }
    });
    // 返回completer的Future对象
    return completer.future;
  }

  Future<void> _updateImageUrls() async {
    await measureManager.saveUserDefinedBodyPattern(
      applicationName: widget.applicationName,
      categoryName: widget.categoryName,
      category: _bodyPatternsInfos?.category,
      description: _bodyPatternsInfos?.description,
      imageUrlList: _imageUrlList,
    );
  }

  Future<void> _removeImage(String e) async {
    dynamic result = await Get.dialog(
      LabDialog(
        title: "删除体标",
        content: "确定要删除当前所选体标？",
      ),
      barrierColor: LabColors.base100.withOpacity(0.1),
    );
    if (result is bool && result) {
      _imageUrlList.remove(e);
      setState(() {});
      _updateImageUrls();
    }
  }

  Future<void> _uploadImage() async {
    final fileInput = html.FileUploadInputElement()
      ..accept = fileTypes.join(',')
      ..multiple = true; // 设置支持的文件类型
    fileInput.click(); // 打开文件选择器
    await fileInput.onChange.first;
    final files = fileInput.files;
    if (files != null) {
      bool allFilesValid = true;

      for (int i = 0; i < files.length; i++) {
        if (!fileTypes.contains(files[i].type)) {
          allFilesValid = false;
          PromptBox.toast('请上传图片类型文件');
          break;
        }
      }
      if (allFilesValid) {
        Get.dialog(
          ShowProgressCircle(
            onProcessChange,
            onCancel: () {
              Get.back();
            },
          ),
        );
        for (int i = 0; i < files.length; i++) {
          await _multipartUpload(
            files[i],
            files.length,
            i + 1,
            onCancelUpload: onCancelUpload,
          );
        }
      }
    }
  }

  Future<void> _resetImages() async {
    dynamic result = await Get.dialog(
      LabDialog(
        title: "重置体标",
        content: "确定要重置体标列表里所有体标？",
      ),
      barrierColor: LabColors.base100.withOpacity(0.1),
    );
    if (result is bool && result) {
      await measureManager.resetUserBodyPatterns(
        applicationName: widget.applicationName,
        categoryName: widget.categoryName,
      );
      _initDatas();
    }
  }

  Future<String> downloadAndConvertToBase64(String url) async {
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        Uint8List bytes = response.bodyBytes;
        String base64 = base64Encode(bytes);
        return base64;
      } else {
        throw Exception('Failed to load file');
      }
    } catch (e) {
      print('Error: $e');
      return '';
    }
  }
}
