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/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 QualityControl extends FStatefulWidget {
  final String recordCode;
  final String reportCode;
  final ReportQualityControl? qualityControlDatas;
  final void Function(ReportQualityControl)? onSubmit;

  QualityControl({
    required this.recordCode,
    required this.reportCode,
    this.qualityControlDatas,
    this.onSubmit,
  });

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

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

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

  ///基本信息
  final baseInfoController = TextEditingController();

  ///报告描述及测量
  final reportDescriptionController = TextEditingController();

  ///超声提示
  final ultrasoundGuidanceController = TextEditingController();

  ///报告图像清晰
  final reportImageClarityController = TextEditingController();

  ///其他(是否漏诊误诊)
  final otherDiagnosisAccuracyController = TextEditingController();

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

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

  final double titleWidth = 200;

  final double dialogWidth = 450;

  String? selectedValue;

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

      var scoreItems = reportQualityControl.scoreItems;
      for (QualityControlScoreItem item in scoreItems ?? []) {
        if (item.key == QualityControlScoreItems.BaseInfo.name) {
          baseInfoController.text = item.score.toString();
        } else if (item.key ==
            QualityControlScoreItems.ReportDescription.name) {
          reportDescriptionController.text = item.score.toString();
        } else if (item.key ==
            QualityControlScoreItems.UltrasoundGuidance.name) {
          ultrasoundGuidanceController.text = item.score.toString();
        } else if (item.key ==
            QualityControlScoreItems.ReportImageClarity.name) {
          reportImageClarityController.text = item.score.toString();
        } else if (item.key ==
            QualityControlScoreItems.OtherDiagnosisAccuracy.name) {
          otherDiagnosisAccuracyController.text = item.score.toString();
        }
      }
    }

    if (widget.qualityControlDatas != null &&
        widget.qualityControlDatas!.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.reportQualityControl.t,
        style: TextStyle(color: Colors.white),
      ),
      onCancel: router.back,
      onOk: () async {
        if (!isEdit) {
          setState(() {
            isEdit = !isEdit;
          });
          return;
        }
        var baseInfoScore = double.tryParse(baseInfoController.text);
        var reportDescriptionScore =
            double.tryParse(reportDescriptionController.text);
        var ultrasoundScore =
            double.tryParse(ultrasoundGuidanceController.text);
        var reportImageClarityScore =
            double.tryParse(reportImageClarityController.text);
        var otherDiagnosisAccuracyScore =
            double.tryParse(otherDiagnosisAccuracyController.text);
        if (baseInfoScore == null ||
            reportDescriptionScore == null ||
            ultrasoundScore == null ||
            reportImageClarityScore == null ||
            otherDiagnosisAccuracyScore == null ||
            qualityControlFeedbackController.text.isNullOrEmpty) {
          PromptBox.toast('所有评分项不可为空');
          return;
        }
        List<QualityControlScoreItem> scoreItems = [
          QualityControlScoreItem(
              key: QualityControlScoreItems.BaseInfo.name,
              score: baseInfoScore),
          QualityControlScoreItem(
              key: QualityControlScoreItems.ReportDescription.name,
              score: reportDescriptionScore),
          QualityControlScoreItem(
              key: QualityControlScoreItems.UltrasoundGuidance.name,
              score: ultrasoundScore),
          QualityControlScoreItem(
              key: QualityControlScoreItems.ReportImageClarity.name,
              score: reportImageClarityScore),
          QualityControlScoreItem(
            key: QualityControlScoreItems.OtherDiagnosisAccuracy.name,
            score: otherDiagnosisAccuracyScore,
          ),
        ];
        bool result;
        if (widget.qualityControlDatas == null ||
            widget.qualityControlDatas!.score == 0) {
          ///新增报告质控
          result = await qualityControlManager.addRecordReportQuality(
              recordCode: widget.recordCode,
              reportCode: widget.reportCode,
              option: qualityControlFeedbackController.text,
              scoreItems: scoreItems);
        } else {
          ///修改报告质控
          result = await qualityControlManager.modifyRecordReportQuality(
            recordCode: widget.recordCode,
            reportCode: widget.reportCode,
            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.basicInfoScore.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                    enabled: isEdit,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                    ],
                    onChanged: (v) {
                      _onChanged(v.toString());
                    },
                    textController: baseInfoController,
                  ),
                ),
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  titleWidth: titleWidth,
                  title: i18nBook.common.reportDescriptionMeasurement.t,
                  widget: FConfigureInput(
                    enabled: isEdit,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                    ],
                    onChanged: (v) {
                      _onChanged(v.toString());
                    },
                    textController: reportDescriptionController,
                  ),
                ),
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  title: i18nBook.common.ultrasoundSuggestion.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                    enabled: isEdit,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                    ],
                    onChanged: (v) {
                      _onChanged(v.toString());
                    },
                    textController: ultrasoundGuidanceController,
                  ),
                ),
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  title: i18nBook.common.reportImageClarity.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                      enabled: isEdit,
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(
                            RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                      ],
                      textController: reportImageClarityController,
                      onChanged: (v) {
                        _onChanged(v.toString());
                      }),
                ),
              ),
              FConfigureLayoutStyle(
                width: dialogWidth,
                child: FConfigureLayout(
                  title: i18nBook.common.otherMisdiagnosis.t,
                  titleWidth: titleWidth,
                  widget: FConfigureInput(
                    enabled: isEdit,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(
                          RegExp(r'^\d+\.?\d*')), // 允许输入数字和小数点
                    ],
                    onChanged: (v) {
                      _onChanged(v.toString());
                    },
                    textController: otherDiagnosisAccuracyController,
                  ),
                ),
              ),
              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(baseInfoController.text) ?? 0) +
        (double.tryParse(reportDescriptionController.text) ?? 0) +
        (double.tryParse(ultrasoundGuidanceController.text) ?? 0) +
        (double.tryParse(reportImageClarityController.text) ?? 0) +
        (double.tryParse(otherDiagnosisAccuracyController.text) ?? 0);
    overallRatingController.text = totalScore.toStringAsFixed(2);
  }
}
