import 'dart:convert';
import 'dart:typed_data';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/common/page_helper.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/controller.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as html;
import 'package:fis_common/logger/logger.dart';

///词条字典导入对话框
class ImportThesaurusDialog extends FStatefulWidget implements FPage {
  ImportThesaurusDialog({
    Key? key,
    this.onOkTap,
    this.thesaurusInfo,
    this.onCancelTap,
  }) : super(key: key);
  final ValueCallback<bool>? onOkTap;
  final VoidCallback? onCancelTap;
  final ThesaurusDTO? thesaurusInfo;

  @override
  FState<ImportThesaurusDialog> createState() => _ImportThesaurusDialogState();

  @override
  String get pageName => "ImportThesaurusDialog";
}

///词条字典编辑对话框状态
class _ImportThesaurusDialogState extends FState<ImportThesaurusDialog> {
  @override
  FWidget build(BuildContext context) {
    var realController = Get.find<VocabularyEntryController>();
    return FSimpleDialog(
      title: FText(
        i18nBook.remedical.vocImport.t,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      isDefault: true,
      cancelString: i18nBook.common.cancel.t,
      okString: i18nBook.laboratory.upload.t,
      onOk: () async {
        await realController.importVoc();
        realController.state.importThesaurusName = "";
        realController.state.editingThesaurusName = "";
        realController.state.importThesaurusTemplateInfoDTO = null;
        router.back();
      },
      onCancel: () {
        realController.state.importThesaurusName = "";
        realController.state.editingThesaurusName = "";
        realController.state.importThesaurusTemplateInfoDTO = null;
        router.back();
      },
      insetPadding: const EdgeInsets.symmetric(vertical: 100),
      children: [
        FContainer(
          width: 520,
          height: 150,
          padding: const EdgeInsets.only(
            left: 25,
            right: 25,
          ),
          child: _getBodyElement(),
        ),
      ],
    );
  }

  _getBodyElement() {
    var realController = Get.find<VocabularyEntryController>();
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _EntryClassifcationItem(
          isRequire: true,
          inputWidget: FRow(
            children: [
              FExpanded(
                child: FContainer(
                  height: 45,
                  child: FRow(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      FObx(
                        () => FBorderInput(
                          hintSize: 16,
                          contentSize: 16,
                          maxLength: PageHelper.maxInputLength_general(),
                          borderColor: Color(0xffdcdfe6),
                          height: 40,
                          hintText:
                              i18nBook.remedical.vocTemplateSelectionTip.t,
                          controller: TextEditingController(
                            text: realController.state.importThesaurusName,
                          ),
                          enabled: realController
                                  .state.importThesaurusName.isNotEmpty
                              ? true
                              : false,
                          onChanged: (value) {
                            realController.state.editingThesaurusName = value;
                          },
                        ),
                      ),
                      const FSizedBox(
                        width: 10,
                      ),
                    ],
                  ),
                ),
              ),
              FElevatedButton(
                child: FText(i18nBook.remedical.importVoc.t),
                onPressed: () async {
                  try {
                    var file = await _pickAndUploadJson();

                    var jsonString = utf8.decode(file.data);
                    var json = jsonDecode(jsonString);
                    var dynamicJsonList = json as List<dynamic>;
                    List<ThesaurusInfoDTO> vocList = [];
                    dynamicJsonList.forEach((element) {
                      vocList.add(ThesaurusInfoDTO.fromJson(element));
                    });
                    realController.state.importThesaurusTemplateInfoDTO =
                        ThesaurusTemplateInfoDTO(thesaurusList: vocList);
                    var jsonStr = realController
                        .state.importThesaurusTemplateInfoDTO!
                        .toJson();
                    print(jsonStr);
                    if (jsonStr.toString() == "{}") {
                      PromptBox.toast(
                          i18nBook.remedical.vocTemplateFormatErrTip.t);
                    }
                    realController.state.importThesaurusName = "";
                    realController.state.importThesaurusName = file.name;
                    realController.state.editingThesaurusName = "";
                    realController.state.editingThesaurusName = file.name;
                  } catch (e) {
                    PromptBox.toast(
                        i18nBook.remedical.vocTemplateFormatErrTip.t);
                    logger.e("Import voc error", e);
                  }
                },
                businessParent: widget,
                name: "ImportVoc",
                style: ElevatedButton.styleFrom(
                  elevation: 0,
                  padding: EdgeInsets.symmetric(
                    vertical: 15,
                    horizontal: 25,
                  ),
                ),
              )
            ],
          ),
          title: i18nBook.remedical.vocBaseName.t,
        ),
      ],
    );
  }

  Future<FileImportInfo> _pickAndUploadJson() async {
    final fileInput = html.FileUploadInputElement()
      ..accept = 'application/json'; // 设置支持的文件类型
    fileInput.click(); // 打开文件选择器
    await fileInput.onChange.first;
    final file = fileInput.files!.first;
    final allowedFileTypes = [
      'application/json',
    ];

    if (!allowedFileTypes.contains(file.type)) {
      // 如果文件类型不符合要求，则提示用户重新选择文件
      PromptBox.toast(i18nBook.remedical.vocSelectionValidationTip.t);
      return FileImportInfo("empty", Uint8List(0));
    }
    //final fileName = file.name;
    final reader = html.FileReader();

    reader.readAsArrayBuffer(file);
    await reader.onLoadEnd.first;
    final data = reader.result;
    var listData = (data as Uint8List);
    return FileImportInfo(file.name.split('.')[0], listData);
  }
}

class FileImportInfo {
  final String name;
  final Uint8List data;

  FileImportInfo(this.name, this.data);
}

///循环字典条目
class _EntryClassifcationItem extends FisView<VocabularyEntryController> {
  _EntryClassifcationItem({
    required this.title,
    required this.inputWidget,
    this.isRequire = false,
  });
  final String title;
  final FWidget inputWidget;
  final bool? isRequire;
  final TextStyle labelStyle = TextStyle(fontSize: 16);
  @override
  FWidget build(BuildContext context) {
    return FRow(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        FContainer(
          child: FText.rich(
            TextSpan(
              children: [
                TextSpan(
                  text: title,
                  style: labelStyle,
                ),
                isRequire!
                    ? TextSpan(
                        text: ' *',
                        style: labelStyle.copyWith(color: Colors.red),
                      )
                    : const TextSpan(),
              ],
            ),
          ),
        ),
        FExpanded(
          child: FContainer(
            margin: const EdgeInsets.symmetric(
              horizontal: 15,
            ),
            child: inputWidget,
          ),
        )
      ],
    );
  }
}
