import 'dart:convert';

import 'package:fis_jsonrpc/services/exam.m.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/storage/text_storage.dart';
import 'package:vitalapp/architecture/utils/datetime.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/interfaces/exam.dart';
import 'package:vitalapp/managers/interfaces/health_check_record.dart';
import 'package:vitalapp/pages/check/health_check_record/components/health_check.dart';
import 'package:vitalapp/pages/check/health_check_record/state.dart';
import 'package:vitalapp/pages/check/models/form.dart';
import 'package:vitalapp/store/store.dart';

class HealthCheckRecordController extends FControllerBase {
  HealthCheckRecordController();
  final state = HealthCheckRecordState();
  final _healthCheckRecordManager = Get.find<IHealthCehckRecordManager>();
  final _examManager = Get.find<IExamManager>();

  late String patientCode;

  List<MenuItem> menuList = [
    MenuItem(label: "一般状况", value: 'ZZYBZK'),
    MenuItem(label: "辅助检查", value: 'FZJC'),
    MenuItem(label: "生活方式", value: 'SHFS'),
    MenuItem(label: "脏器及查体", value: 'ZQCT'),
    MenuItem(label: "现存主要健康问题", value: 'XCZYWT'),
    MenuItem(label: "住院及用药情况", value: 'ZYYYFMYGHYFJZS'),
    MenuItem(label: "健康评价及指导", value: 'JKPJJZD'),
  ];
  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  _initData() {
    update(["contract_records"]);
    patientCode = Store.user.currentSelectPatientInfo?.code ?? '';
    _getExamRecordList();
  }

  Future<void> _getExamRecordList() async {
    try {
      var result =
          await _healthCheckRecordManager.getExamRecordList(patientCode);
      if (result != null) {
        state.examRecordDTOList = result;
      }
    } catch (e) {
      print(e);
      return;
    }
  }

  Future<void> updateExamByBatchNumberAsync(key, batchNumber, data) async {
    TextStorage template = TextStorage(
      fileName: key,
      directory: "patient/$patientCode/exam",
    );
    final result = await _examManager
        .updateExamByBatchNumberAsync(UpdateExamByBatchNumberRequest(
      key: key,
      batchNumber: batchNumber,
      examData: data,
      patientCode: patientCode,
    ));
    if (result ?? false) {
      try {
        template.save(data);
        PromptBox.toast('保存成功');
        await _getExamRecordList();
      } catch (err) {
        print('🥟');
        PromptBox.toast('保存失败');
      }
    }
  }

  ///读取静态Html
  Future<String> loadingLocalAsset() async {
    ///加载
    String htmlData = await rootBundle.loadString('assets/docs/examTable.html');
    print("加载数据完成 $htmlData");
    return htmlData;
  }

  Future<void> toExamDetailPage(int index, ExamRecordDTO dto) async {
    var initialData = await loadingLocalAsset();
    var examRecordDatas = state.examRecordDTOList[index].examRecordDatas;
    Map<String, dynamic> examData = {};
    examRecordDatas?.forEach((element) {
      examData.addAll(jsonDecode(element.examData ?? '{}'));
    });
    // 将数据转换为 JSON 字符串
    var jsonData = jsonEncode({
      "patientInfo": {
        "patientName": dto.patientName,
      },
      "examData": examData,
      "docterName": dto.examDoctor,
      "examTime":
          DataTimeUtils.formatDateString(dto.examTime ?? DateTime.now()),
    });
    _openExamDetail(initialData, jsonData);
  }

  Future<void> toCheckPage(
    ExamRecordDTO dto,
    List<ExamRecordDataDTO>? dataDTO,
    int index,
  ) async {
    Get.dialog(
      HealthCheckDialog(
        examRecord: dto,
        examRecordDatas: dataDTO,
        index: index,
      ),
    );
  }

  String getHealthCheckRecordType(String key) {
    switch (key) {
      case 'ZZYBZK':
        return '症状、一般状况';
      case 'SHFS':
        return '生活方式';
      case 'ZQCT':
        return '脏器、查体';
      case 'FZJC':
        return '辅助检查';
      case 'XCZYWT':
        return '现存主要问题';
      case 'ZYYYFMYGHYFJZS':
        return '住院、用药、非免疫规划预防接种史';
      case 'JKPJJZD':
        return '健康评价及指导';
      default:
        return "";
    }
  }

  String examStateTransition(ExamStateEnum state) {
    switch (state) {
      case ExamStateEnum.Unchecked:
        return "未体检";
      case ExamStateEnum.Invalid:
        return "已作废";
      case ExamStateEnum.Inspected:
        return "已体检";
      default:
        return "";
    }
  }

  MaterialColor examStateColors(ExamStateEnum state) {
    switch (state) {
      case ExamStateEnum.Unchecked:
        return Colors.grey;
      case ExamStateEnum.Invalid:
        return Colors.red;
      case ExamStateEnum.Inspected:
        return Colors.green;
      default:
        return Colors.blue;
    }
  }

  void _openExamDetail(
    String initialData,
    String jsonData,
  ) {
    // 将 JSON 字符串作为参数传递给 evaluateJavascript 方法
    Get.dialog(Column(
      children: [
        Container(
          width: 900,
          alignment: Alignment.centerRight,
          padding: const EdgeInsets.only(right: 20, top: 10),
          color: Colors.white,
          child: IconButton(
            onPressed: () {
              Get.back();
            },
            icon: const Icon(
              Icons.close,
            ),
          ),
        ),
        Expanded(
          child: SizedBox(
            width: 900,
            height: double.maxFinite,
            child: InAppWebView(
              initialData: InAppWebViewInitialData(
                data: '<body style="padding:30px 100px;">$initialData </body>',
                mimeType: 'text/html',
                encoding: 'utf-8',
              ),
              onWebViewCreated: (controller) {
                controller.evaluateJavascript(
                    source: "window.globalData = $jsonData;");
              },
              onConsoleMessage: (controller, consoleMessage) {
                // print(consoleMessage);
              },
            ),
          ),
        ),
      ],
    ));
  }
}
