import 'dart:typed_data';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/controller.dart';
import 'package:flyinsono/rpc.dart';
import 'package:universal_html/html.dart' as html;
import 'package:fis_common/env/env.dart';

/// 最右边的词条
class EntriesBody extends FisView<VocabularyEntryController>
    implements FInteractiveContainer {
  @override
  final String pageName;

  EntriesBody({this.pageName = 'EntriesBody'});

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      margin: EdgeInsets.only(
        top: 10,
        right: 10,
        bottom: 10,
      ),
      // width: 400,
      child: FColumn(
        children: [
          FSizedBox(
            height: 15,
          ),
          FObx(() {
            if (controller.state.selectedKey.isNotEmpty) {
              return FObx(
                () => controller.state.isEnableEdit
                    ? FRow(
                        children: [
                          const FSizedBox(
                            width: 20,
                          ),
                          EntriesBottomItem(
                            businessParent: this,
                            itemTitle: i18nBook.remedical.createVoc.t,
                            onClick: () => controller.personalEntryController
                                .openVocabularyDialogPage(null, this),
                          ),
                          const FSizedBox(
                            width: 10,
                          ),
                        ],
                      ) as FWidget
                    : const FSizedBox(),
              );
            } else {
              return const FSizedBox();
            }
          }),
          FExpanded(
            child: FObx(
              () => controller.state.vocabularyCard.length == 0
                  ? NoDataWidget() as FWidget
                  : FContainer(
                      child: _EntriesItem(this),
                    ),
            ),
          ),
        ],
      ),
    );
  }
}

/// 词条的点击按钮
class EntriesBottomItem extends FisView<VocabularyEntryController> {
  /// 点击事件
  final void Function()? onClick;
  EntriesBottomItem(
      {required this.businessParent,
      required this.itemTitle,
      required this.onClick});

  ///父级节点
  final FInteractiveContainer businessParent;

  /// 词条库名称
  final String itemTitle;

  @override
  FWidget build(BuildContext context) {
    return FElevatedButton(
      businessParent: this.businessParent,
      name: "$itemTitle",
      onPressed: () => onClick!.call(),
      style: ButtonStyle(
        padding: MaterialStateProperty.all(
          EdgeInsets.symmetric(
            vertical: 15,
            horizontal: 25,
          ),
        ),
      ),
      child: FText(itemTitle),
    );
  }
}

/// 无数据的组件
class NoDataWidget extends FStatelessWidget {
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      margin: EdgeInsets.only(top: 80),
      child: FColumn(
        children: [
          FCenter(
            child: FImage.asset(
              "assets/images/no_data.png",
              width: 300,
              height: 300,
              fit: BoxFit.cover,
            ),
          ),
          FText(i18nBook.common.noneDataTip.t),
        ],
      ),
    );
  }
}

/// 创建词条库 刷新等功能
class EntriesFunction extends FisView<VocabularyEntryController> {
  ///父级节点
  final FPage businessParent;

  EntriesFunction(this.businessParent);

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      margin: EdgeInsets.only(
        left: 20,
        right: 10,
      ),
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          FGestureDetector(
            name: "openEditVocabularyEntryPage",
            businessParent: businessParent,
            onTap: () => controller.personalEntryController
                .openEditVocabularyEntryPage(),
            child: FContainer(
              decoration: new BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(8.0),
                ), //圆角弧度
              ),
              height: 34,
              child: FMouseRegion(
                cursor: SystemMouseCursors.click,
                child: FCenter(
                  child: FRow(
                    children: [
                      FIcon(
                        Icons.add_box_outlined,
                        size: 24,
                        color: Theme.of(context).primaryColor,
                      ),
                      FText(
                        i18nBook.remedical.createThesaurus.t,
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.black,
                          height: 1,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          FGestureDetector(
            name: "import",
            businessParent: businessParent,
            onTap: () async {
              await controller.openVocImportPage();
            },
            child: FContainer(
              decoration: new BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(8.0),
                ), //圆角弧度
              ),
              height: 34,
              child: FMouseRegion(
                cursor: SystemMouseCursors.click,
                child: FCenter(
                  child: FRow(
                    children: [
                      FIcon(
                        Icons.download_outlined,
                        size: 24,
                        color: Theme.of(context).primaryColor,
                      ),
                      FText(
                        i18nBook.remedical.importVoc.t,
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.black,
                          height: 1,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          FGestureDetector(
            name: "export",
            businessParent: businessParent,
            onTap: () async {
              var exportInfo = await controller.getVocJsonBinary();
              Uint8List memoryFileData = exportInfo.data;
              String fileName = '${exportInfo.name}.json';
              String mimeType = 'application/json';
              if (FPlatform.isMacOS || FPlatform.isWindows) {
                await rpc.platform
                    .setBytesToExport(exportInfo.dataStr, fileName);
              } else {
                _exportMemoryFile(memoryFileData, fileName, mimeType);
              }
            },
            child: FContainer(
              decoration: new BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(8.0),
                ), //圆角弧度
              ),
              height: 34,
              child: FMouseRegion(
                cursor: SystemMouseCursors.click,
                child: FCenter(
                  child: FRow(
                    children: [
                      FIcon(
                        Icons.upload_outlined,
                        size: 24,
                        color: Theme.of(context).primaryColor,
                      ),
                      FText(
                        i18nBook.remedical.export.t,
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.black,
                          height: 1,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          FGestureDetector(
            name: "refresh",
            businessParent: this.businessParent,
            onTap: () {
              controller.searchEntryInfos();
            },
            child: FContainer(
              decoration: new BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(8.0)), //圆角弧度
              ),
              height: 34,
              child: FMouseRegion(
                cursor: SystemMouseCursors.click,
                child: FCenter(
                  child: FRow(
                    children: [
                      FIcon(
                        Icons.refresh,
                        size: 24,
                        color: Theme.of(context).primaryColor,
                      ),
                      FText(
                        i18nBook.common.refresh.t,
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.black,
                          height: 1,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _exportMemoryFile(Uint8List fileData, String fileName, String mimeType) {
    final blob = html.Blob([fileData], mimeType);
    final url = html.Url.createObjectUrlFromBlob(blob);
    html.AnchorElement anchorElement = html.AnchorElement(href: url);
    anchorElement.download = fileName;
    anchorElement.click();
    html.Url.revokeObjectUrl(url);
  }
}

class _EntriesItem extends FisView<VocabularyEntryController> {
  FInteractiveContainer businessParent;
  _EntriesItem(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    return FReorderableListView(
      shrinkWrap: true,
      buildDefaultDragHandles: false,
      children: controller.state.vocabularyCard
          .map(
            (item) => FContainer(
              key: Key(
                item.thesaurusItemCode.toString(),
              ),
              padding: EdgeInsets.only(top: 15),
              child: SwipeCard(
                child: FColumn(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    FContainer(
                      child: FText(
                        i18nBook.remedical.description.t,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    FRow(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        FExpanded(
                          child: FContainer(
                            child: FText(
                              item.thesaurusItemDescription ?? '',
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              // softWrap: true,
                            ),
                          ),
                        )
                      ],
                    ),
                    FSizedBox(
                      height: 5,
                    ),
                    FContainer(
                      child: FText(
                        i18nBook.remedical.summary.t,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    FRow(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        FExpanded(
                          child: FContainer(
                            child: FText(
                              item.thesaurusItemConclusion ?? '',
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                            ),
                          ),
                        )
                      ],
                    ),
                    FSizedBox(
                      height: 10,
                    ),
                  ],
                ),
                onTap: () => controller.personalEntryController
                    .openVocabularyDialogPage(item, businessParent),
                isActive: false,
              ),
            ),
          )
          .toList(),
      onReorder: (int oldIndex, int newIndex) {
        /// 拖拽的方法
      },
    );
  }
}
