import 'dart:convert';
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/rpc.dart';
import 'package:flyinsono/utils/export_status_type.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/controller/real_time_consultation_controller.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

enum ConsultationExportEnum {
  consultationRecord,
  consultationImage,
  consultationReport,
}

class FExportStateDialog extends FStatelessWidget implements FPage {
  @override
  final String pageName;
  final controller = Get.find<RealTimeConsultationController>();
  FExportStateDialog({
    Key? key,
    this.pageName = 'FExportStateDialog',
  }) : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return FStack(
      children: [
        QuickFWidget(
          ModalBarrier(
            color: Colors.black.withOpacity(0.5),
            onDismiss: () {
              print("${controller.state.isExporting}");
              if (controller.state.isExporting) {
                _showConfirmDialog(this);
              } else {
                Get.back();
              }
            },
          ),
        ),
        FSimpleDialog(
          onClose: () {
            if (controller.state.isExporting) {
              _showConfirmDialog(this);
            } 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,
          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,
                        onPressed: () {},
                        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,
                    onPressed: () {
                      if (controller.state.exportState !=
                              ExportStatusType.Finished &&
                          controller.state.isExporting == true) {
                        _showConfirmDialog(this);
                      } else {
                        Get.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),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  FWidget child(BuildContext context) {
    return FObx(() => 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),
                ),
                backgroundColor: Colors.black26,
                progressBarColor: Colors.blue,
              ),
              FSizedBox(
                height: 15,
              ),
              FText(
                _getProgressStatus(
                  controller.state.exportState,
                ),
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.blue,
                ),
              ),
              FSizedBox(
                height: 25,
              ),
            ],
          ),
        ));
  }

  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),
        ),
      ],
    );
  }

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

  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;
  }

  _showConfirmDialog(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 {
        Get.back();
        rpc.platform.abortExportOperation();
      },
    );
  }
}

class FRealTimeConsultationExport extends FStatefulWidget implements FPage {
  const FRealTimeConsultationExport({super.key});

  @override
  FState<FRealTimeConsultationExport> createState() =>
      _FRealTimeConsultationExportState();

  @override
  String get pageName => 'FRealTimeConsultationExport';
}

class _FRealTimeConsultationExportState
    extends FState<FRealTimeConsultationExport> {
  /// 选中的类型
  List<ConsultationExportEnum> selectExportDate = [
    ConsultationExportEnum.consultationRecord
  ];
  final controller = Get.find<RealTimeConsultationController>();

  String _getFileNameByExportType(ConsultationExportEnum element) {
    if (element == ConsultationExportEnum.consultationRecord) {
      return i18nBook.realTimeConsultation.consultationRecord.t;
    }
    if (element == ConsultationExportEnum.consultationReport) {
      return i18nBook.realTimeConsultation.consultationReport.t;
    }
    if (element == ConsultationExportEnum.consultationImage) {
      return i18nBook.realTimeConsultation.consultationImage.t;
    }
    return i18nBook.realTimeConsultation.consultationExport.t;
  }

  String _getExportFileName(List<ConsultationExportEnum> exportEnums) {
    var finalName = "";
    exportEnums.forEach((element) {
      var partName = _getFileNameByExportType(element);
      if (finalName.isEmpty) {
        finalName += partName;
      } else {
        finalName += "+$partName";
      }
    });
    return finalName;
  }

  FWidget _buildExportDateCard(
    String title,
    ConsultationExportEnum value,
  ) {
    bool isChecked = selectExportDate.contains(value);
    FWidget _titleText;
    BoxDecoration _exportDateBoxDecoration;
    if (isChecked) {
      _titleText = FText(
        title,
        style: TextStyle(
          color: Colors.white,
        ),
      );
      _exportDateBoxDecoration = BoxDecoration(
        color: FTheme.ins.colorScheme.primary,
      );
    } else {
      _titleText = FText(
        title,
      );
      _exportDateBoxDecoration = BoxDecoration(
        border: Border.all(
          color: FTheme.ins.colorScheme.line,
        ),
      );
    }
    return FContainer(
      height: 40,
      margin: EdgeInsets.symmetric(
        horizontal: 10,
      ),
      child: FInkWell(
        child: FContainer(
          padding: EdgeInsets.symmetric(
            vertical: 8,
            horizontal: 20,
          ),
          decoration: _exportDateBoxDecoration,
          child: FCenter(child: _titleText),
        ),
        onTap: () {
          setState(() {
            if (selectExportDate.contains(value)) {
              if (selectExportDate.length == 1) {
                return;
              }
              selectExportDate.remove(value);
            } else {
              selectExportDate.add(value);
            }
          });
        },
      ),
    );
  }

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

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      insetPadding: EdgeInsets.zero,
      backgroundColor: Colors.white,
      title: FText(
        i18nBook.remedical.export.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      bottomButton: FContainer(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 15),
        child: FFlex(
          direction: Axis.horizontal,
          mainAxisSize: MainAxisSize.min,
          children: [
            FElevatedButton(
              name: "confirm",
              businessParent: this.widget,
              onPressed: () => exportConsultationZip(),
              style: ButtonStyle(
                padding: MaterialStateProperty.all(
                  EdgeInsets.symmetric(
                    vertical: 15,
                    horizontal: 25,
                  ),
                ),
              ),
              child: FText(i18nBook.common.confirm.t),
            ),
            FSizedBox(
              width: 20,
            ),
            FOutlinedButton(
              name: "back",
              businessParent: this.widget,
              onPressed: () {
                Get.back();
              },
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(
                  Colors.white,
                ),
                padding: MaterialStateProperty.all(
                  EdgeInsets.symmetric(vertical: 15, horizontal: 25),
                ),
              ),
              child: FText(
                i18nBook.common.cancel4Btn.t,
                style: TextStyle(
                  color: Color.fromRGBO(61, 146, 252, 1),
                ),
              ),
            ),
          ],
        ),
      ),
      children: [
        FContainer(
          margin: EdgeInsets.symmetric(horizontal: 30, vertical: 30),
          child: FRow(
            children: [
              FExpanded(
                child: _buildExportDateCard(
                  i18nBook.realTimeConsultation.exportConsultationRecords.t,
                  ConsultationExportEnum.consultationRecord,
                ),
              ),
              FExpanded(
                child: _buildExportDateCard(
                  i18nBook.realTimeConsultation.exportConsultationImage.t,
                  ConsultationExportEnum.consultationImage,
                ),
              ),
              FExpanded(
                child: _buildExportDateCard(
                  i18nBook.realTimeConsultation.exportConsultationReport.t,
                  ConsultationExportEnum.consultationReport,
                ),
              )
            ],
          ),
        )
      ],
    );
  }

  /// 导出压缩包
  Future<void> exportConsultationZip() async {
    router.back();
    var result = await controller.listController.exportConsultationsAsync(
      isExportConsultation: selectExportDate.contains(
        ConsultationExportEnum.consultationRecord,
      ),
      isExportConsultationFileData: selectExportDate.contains(
        ConsultationExportEnum.consultationImage,
      ),
      isExportReport: selectExportDate.contains(
        ConsultationExportEnum.consultationReport,
      ),
    );
    if ((result.consultationList?.isEmpty ?? true) &&
        (result.reportList?.isEmpty ?? true) &&
        (result.consultationFileDatalList?.isEmpty ?? true)) {
      PromptBox.toast(i18nBook.errorCodes.errorCode4056.t);
      return;
    }

    var resultJsonString = jsonEncode(result);

    String fileName = _getExportFileName(selectExportDate) +
        DateFormat('yyyyMMddHHmmss').format(DateTime.now());
    await rpc.platform.exportConsultationZipFile(resultJsonString, fileName);
    controller.state.isExporting = true;
    router.dialog(() => FExportStateDialog(), isShowBarrier: false);
  }
}
