import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/quality_control.dart';
import 'package:flyinsono/pages/measure/measure_home/entitys/image_quality_controlScore_items.dart';
import 'package:flyinsono/pages/remedical/report_preview/entitys/quality_control_score_items.dart';
import 'package:flyinsono/pages/remedical/report_preview/entitys/select_qualityType.dart';
import 'package:flyinsono/pages/remote_controller/index.dart';
import 'package:get/get.dart';

class ImageQualityControl extends FStatefulWidget {
  final String remedicalCode;
  final String recordCode;
  final ReportQualityControl? imageQualityControl;
  final void Function(ReportQualityControl)? onSubmit;

  ImageQualityControl({
    required this.recordCode,
    required this.remedicalCode,
    this.imageQualityControl,
    this.onSubmit,
  });

  @override
  FState<FStatefulWidget> createState() {
    return ImageQualityControlState();
  }
}

class ImageQualityControlState extends FState<ImageQualityControl> {
  final qualityControlManager = Get.find<IQualityControlManager>();

  ///是否可编辑
  bool isEdit = true;

  ///图像清晰度
  final imageClarityController = TextEditingController();

  ///图像标记
  final imageAnnotationController = TextEditingController();

  ///图像体标
  final imageMarkerController = TextEditingController();

  ///图像居中
  final imageCenteringController = TextEditingController();

  ///阳性病灶测量
  final positiveLesionMeasurementController = TextEditingController();

  ///质控意见
  final qualityControlFeedbackController = TextEditingController();

  ///综合评分
  final overallRatingController = TextEditingController();

  final double titleWidth = 200;

  final double dialogWidth = 450;

  String? selectedValue;

  @override
  void initState() {
    if (widget.imageQualityControl != null) {
      var reportQualityControl = widget.imageQualityControl!;
      qualityControlFeedbackController.text =
          reportQualityControl.opinion ?? '';

      var scoreItems = reportQualityControl.scoreItems;
      for (QualityControlScoreItem item in scoreItems ?? []) {
        if (item.key == ImageQualityControlScoreItems.ImageClarity.name) {
          imageClarityController.text = item.score.toString();
        } else if (item.key ==
            ImageQualityControlScoreItems.ImageAnnotation.name) {
          imageAnnotationController.text = item.score.toString();
        } else if (item.key == ImageQualityControlScoreItems.ImageMarker.name) {
          imageMarkerController.text = item.score.toString();
        } else if (item.key ==
            ImageQualityControlScoreItems.ImageCentering.name) {
          imageCenteringController.text = item.score.toString();
        } else if (item.key ==
            ImageQualityControlScoreItems.PositiveLesionMeasurement.name) {
          positiveLesionMeasurementController.text = item.score.toString();
        }
      }
    }

    if (widget.imageQualityControl != null &&
        widget.imageQualityControl!.score > 0) {
      setState(() {
        isEdit = false;
      });
      _onChanged("");
    }
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      okString: isEdit ? i18nBook.common.submit.t : i18nBook.common.edit.t,
      cancelString: i18nBook.common.cancel.t,
      isDefault: true,
      title: FText(
        i18nBook.common.imageQualityControl.t,
        style: TextStyle(color: Colors.white),
      ),
      onCancel: router.back,
      onOk: () async {
        if (!isEdit) {
          setState(() {
            isEdit = !isEdit;
          });
          return;
        }
        var imageClarity = double.tryParse(imageClarityController.text);
        var imageAnnotation = double.tryParse(imageAnnotationController.text);
        var imageMarker = double.tryParse(imageMarkerController.text);
        var imageCentering = double.tryParse(imageCenteringController.text);
        var positiveLesionMeasurement =
            double.tryParse(positiveLesionMeasurementController.text);
        if (imageClarity == null ||
            imageAnnotation == null ||
            imageMarker == null ||
            imageCentering == null ||
            positiveLesionMeasurement == null ||
            qualityControlFeedbackController.text.isNullOrEmpty) {
          PromptBox.toast(i18nBook.common.scoreNotNull.t);
          return;
        }
        List<QualityControlScoreItem> scoreItems = [
          QualityControlScoreItem(
              key: ImageQualityControlScoreItems.ImageClarity.name,
              score: imageClarity),
          QualityControlScoreItem(
              key: ImageQualityControlScoreItems.ImageAnnotation.name,
              score: imageAnnotation),
          QualityControlScoreItem(
              key: ImageQualityControlScoreItems.ImageMarker.name,
              score: imageMarker),
          QualityControlScoreItem(
              key: ImageQualityControlScoreItems.ImageCentering.name,
              score: imageCentering),
          QualityControlScoreItem(
            key: ImageQualityControlScoreItems.PositiveLesionMeasurement.name,
            score: positiveLesionMeasurement,
          ),
        ];
        bool result;
        if (widget.imageQualityControl == null ||
            widget.imageQualityControl!.score == 0) {
          ///新增图像质控
          result = await qualityControlManager.addRemedicalQuality(
            recordCode: widget.recordCode,
            remedicalCode: widget.remedicalCode,
            option: qualityControlFeedbackController.text,
            scoreItems: scoreItems,
          );
        } else {
          ///修改图像质控
          result = await qualityControlManager.modifyRemedicalQuality(
            recordCode: widget.recordCode,
            remedicalCode: widget.remedicalCode,
            option: qualityControlFeedbackController.text,
            scoreItems: scoreItems,
          );
        }
        if (result) {
          widget.onSubmit?.call(ReportQualityControl(
            scoreItems: scoreItems,
            score: double.tryParse(overallRatingController.text) ?? 0,
            opinion: qualityControlFeedbackController.text,
            controlUserCode: Store.user.code,
            controlUserName: Store.user.displayName,
            controlTime: DateTime.now(),
          ));
        }
        router.back();
      },
      children: [
        FContainer(
          height: 450,
          margin: EdgeInsets.symmetric(vertical: 20),
          child: FColumn(
            children: [
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  title: i18nBook.common.imageClarity.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                    enabled: isEdit,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                    ],
                    onChanged: (v) {
                      _onChanged(v.toString());
                    },
                    textController: imageClarityController,
                  ),
                ),
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  titleWidth: titleWidth,
                  title: i18nBook.common.imageMarking.t,
                  widget: FConfigureInput(
                    enabled: isEdit,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                    ],
                    onChanged: (v) {
                      _onChanged(v.toString());
                    },
                    textController: imageAnnotationController,
                  ),
                ),
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  title: i18nBook.common.imageBodyMark.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                    enabled: isEdit,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                    ],
                    onChanged: (v) {
                      _onChanged(v.toString());
                    },
                    textController: imageMarkerController,
                  ),
                ),
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  title: i18nBook.common.imageCentering.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                      enabled: isEdit,
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(
                            RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                      ],
                      textController: imageCenteringController,
                      onChanged: (v) {
                        _onChanged(v.toString());
                      }),
                ),
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  title: i18nBook.common.lesionMeasurement.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                    enabled: isEdit,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                    ],
                    onChanged: (v) {
                      _onChanged(v.toString());
                    },
                    textController: positiveLesionMeasurementController,
                  ),
                ),
              ),
              const FSizedBox(
                height: 5,
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                    title: i18nBook.common.qualityOpinion.t,
                    titleWidth: 110,
                    widget: FSizedBox(
                      width: 270,
                      child: FTextField(
                        enabled: isEdit,
                        maxLines: 6,
                        minLines: 6,
                        decoration: InputDecoration(
                          filled: true,
                          fillColor:
                              isEdit ? Colors.transparent : Colors.grey[100],
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(4.0),
                            borderSide: BorderSide(
                              color: Colors.grey[200]!, // 这里是颜色
                              width: 1.0, // 这里是宽度
                            ),
                          ),
                        ),
                        controller: qualityControlFeedbackController,
                      ),
                    )),
              ),
              const FSizedBox(
                height: 5,
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  title: i18nBook.common.overallScore.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                    enabled: false,
                    textController: overallRatingController,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  void _onChanged(String v) {
    var totalScore = (double.tryParse(imageClarityController.text) ?? 0) +
        (double.tryParse(imageAnnotationController.text) ?? 0) +
        (double.tryParse(imageMarkerController.text) ?? 0) +
        (double.tryParse(imageCenteringController.text) ?? 0) +
        (double.tryParse(positiveLesionMeasurementController.text) ?? 0);
    overallRatingController.text = totalScore.toStringAsFixed(2);
  }
}
