import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.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:fis_ui/widgets/progressbar/progressbar.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:get/get.dart';
import 'package:flyinsono/utils/export_status_type.dart';

class ExportDialog extends StatefulWidget implements FPage {
  ExportDialog({
    Key? key,
    this.pageName = 'ExportDialog',
  }) : super(key: key);
  @override
  final String pageName;

  @override
  State<ExportDialog> createState() => _ExportDialogState();
}

class _ExportDialogState extends State<ExportDialog> {
  final controller = Get.find<ConsultationController>();

  FWidget title(String name, String value, double textWidth) {
    return FRow(
      children: [
        FContainer(
          width: 40,
          child: FText(
            '$name',
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        FContainer(
          width: textWidth,
          child: FText('$value'),
        ),
      ],
    );
  }

  FWidget child(BuildContext context) {
    return FObx(() => (controller.state.isExporting ||
            controller.state.exportState == ExportStatusType.Finished)
        ? FContainer(
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: FColumn(
              children: [
                FSizedBox(
                  height: 50,
                ),
                FProgeressbar(
                    percentage: controller.state.exportProgress,
                    lineHeight: 20,
                    animation: true,
                    animationDuration: 200,
                    animateFromLastPercentage: true,
                    alignment: MainAxisAlignment.spaceBetween,
                    child: Text(
                      _getProgressDisplay(controller.state.exportProgress),
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ),
                    //trailing: Icon(Icons.check, color: GFColors.SUCCESS),
                    backgroundColor: Colors.black26,
                    progressBarColor: Colors.blue),
                FSizedBox(
                  height: 15,
                ),
                FText(_getProgressStatus(controller.state.exportState),
                    style: TextStyle(fontSize: 16, color: Colors.blue)),
                FSizedBox(
                  height: 25,
                ),
              ],
            ),
          )
        : FContainer(
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: FColumn(
              children: [
                FSizedBox(
                  height: 15,
                ),
                FContainer(
                  margin: EdgeInsets.all(8),
                  color: Colors.white,
                  child: FRow(
                    children: [
                      FExpanded(
                        child: FContainer(
                          child: FRow(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              FText(i18nBook.remedical.exportItems.t),
                              FSizedBox(
                                width: 20,
                              ),
                              FRow(
                                ///包裹子布局
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  _buildExportItem(
                                      i18nBook.remedical.examReport.t, 0),
                                  FSizedBox(
                                    width: 20,
                                  ),
                                  _buildExportItem(
                                      i18nBook.remedical.scanImage.t, 2),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                FSizedBox(
                  height: 15,
                ),
              ],
            ),
          ));
  }

  void onConfirmed() {
    if (controller.state.endDateTime.isBefore(controller.state.startDateTime)) {
      PromptBox.toast(i18nBook.remedical.errorScanData.t);
    } else {
      controller.export();
    }
  }

  @override
  void initState() {
    super.initState();
    controller.state.isExporting = false;
    controller.state.exportState = ExportStatusType.Starting;
  }

  @override
  FWidget build(BuildContext context) {
    return FStack(
      children: [
        QuickFWidget(
          ModalBarrier(
            color: Colors.black.withOpacity(0.5),
            onDismiss: () {
              if (controller.state.isExporting) {
                _showCancelConfirmDialog(this.widget);
              } else {
                Get.back();
              }
            },
          ),
        ),
        FSimpleDialog(
          onClose: () {
            if (controller.state.isExporting) {
              _showCancelConfirmDialog(this.widget);
            } else {
              Get.back();
            }
          },
          onCancel: () {
            print("onCancel:");
          },
          onOk: () {
            print("onOk:");
          },
          title: FText(
            i18nBook.remedical.export.t,
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
            ),
          ),
          insetPadding: EdgeInsets.symmetric(vertical: 150),
          children: [
            FContainer(
              width: 600,
              child: child(context),
            ),
          ],
          okString: i18nBook.common.confirm.t,
          cancelString: i18nBook.common.cancel.t,
          backgroundColor: Colors.white,
          bottomButton: FContainer(
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(vertical: 15),
            child: FFlex(
              direction: Axis.horizontal,
              mainAxisSize: MainAxisSize.min,
              children: [
                FObx(() => (controller.state.isExporting ||
                        controller.state.exportState ==
                            ExportStatusType.Finished)
                    ? FText("")
                    : FElevatedButton(
                        name: "confirm",
                        businessParent: this.widget,
                        onPressed: () => onConfirmed(),
                        style: ButtonStyle(
                          padding: MaterialStateProperty.all(
                            EdgeInsets.symmetric(
                              vertical: 15,
                              horizontal: 25,
                            ),
                          ),
                        ),
                        child: FText(i18nBook.common.confirm.t),
                      )),
                FObx(() => controller.state.isExporting
                    ? FText("")
                    : FSizedBox(
                        width: 20,
                      )),
                FObx(
                  () => FOutlinedButton(
                    name: "back",
                    businessParent: this.widget,
                    onPressed: () {
                      print(controller.state.exportState);
                      if (controller.state.exportState !=
                              ExportStatusType.Finished &&
                          controller.state.isExporting == true) {
                        _showCancelConfirmDialog(this.widget);
                      } else {
                        router.back();
                      }
                    },
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(
                        Colors.white,
                      ),
                      padding: MaterialStateProperty.all(
                        EdgeInsets.symmetric(vertical: 15, horizontal: 25),
                      ),
                    ),
                    child: FText(
                      controller.state.exportState == ExportStatusType.Finished
                          ? i18nBook.common.confirm.t
                          : i18nBook.common.cancel4Btn.t,
                      style: TextStyle(
                        color: Color.fromRGBO(61, 146, 252, 1),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  _showCancelConfirmDialog(FInteractiveContainer businessParent) {
    FConfirmAlert.show(
        context: Get.context!,
        businessParent: businessParent,
        title: i18nBook.common.tip.t,
        subTitle: i18nBook.remedical.exportAbortingTip.t,
        confrimLabel: i18nBook.common.confirm.t,
        cancelLabel: i18nBook.common.cancel.t,
        onConfirm: () async {
          router.back();
          Future.delayed(Duration(milliseconds: 400), () {
            controller.abortExport();
          });
        });
  }

  FWidget _buildExportItem(String name, int index) {
    return FObx(() => FInkWell(
          onTap: () {
            var oldOne = controller.state.selectedExportItems.toList();
            if (oldOne.contains(index)) {
              if (oldOne.length > 1) {
                oldOne.remove(index);
              }
            } else {
              oldOne.add(index);
            }
            controller.state.selectedExportItems = oldOne;
          },
          child: FContainer(
            width: 120,
            padding: EdgeInsets.symmetric(vertical: 10),
            alignment: Alignment.center,
            child: FText(
              name,
              style: TextStyle(
                color: controller.state.selectedExportItems.contains(index)
                    ? Colors.white
                    : Colors.black,
              ),
            ),
            decoration: BoxDecoration(
              color: controller.state.selectedExportItems.contains(index)
                  ? FTheme.ins.colorScheme.primary
                  : Colors.white,
              border: Border.all(
                color: Color.fromRGBO(
                  141,
                  141,
                  141,
                  1,
                ),
                width: 0.5,
              ),
            ),
          ),
        ));
  }

  String _getProgressStatus(ExportStatusType stateEnum) {
    if (stateEnum == ExportStatusType.Downloading) {
      return i18nBook.remedical.downloading.t;
    }
    if (stateEnum == ExportStatusType.Packaging) {
      return i18nBook.remedical.packaging.t;
    }
    if (stateEnum == ExportStatusType.Finished) {
      return CartSystemPlatform.isCartSystemVersion
          ? i18nBook.remedical.exportFinishedWithSlectedPath.t
          : i18nBook.remedical.exportFinished.t;
    }
    if (stateEnum == ExportStatusType.Cancelled) {
      return i18nBook.realTimeConsultation.exportFailed.t;
    }
    return i18nBook.realTimeConsultation.exporting.t;
  }

  String _getProgressDisplay(double exportState) {
    if (controller.state.exportProgress == 1.0) {
      return "100%";
    }
    return (controller.state.exportProgress * 100).toStringAsPrecision(2) + "%";
  }
}
