import 'dart:convert';

import 'package:fis_jsonrpc/services/followUp.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:intl/intl.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/interfaces/follow_up.dart';
import 'package:vitalapp/pages/check/follow_up/controller.dart';
import 'package:vitalapp/pages/check/follow_up/widgets/follow_up_from.dart';
import 'package:vitalapp/pages/check/follow_up_record/state.dart';
import 'package:vitalapp/pages/check/widgets/configurable_card.dart';
import 'package:vitalapp/store/store.dart';

class FollowUpRecordController extends FControllerBase {
  FollowUpRecordController();
  final state = FollowUpRecordState();
  final _followUpManager = Get.find<IFollowUpManager>();
  late String patientCode;
  late String patientName;
  late FollowUpController _followUpController;
  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  _initData() {
    update(["contract_records"]);
    patientCode = Store.user.currentSelectPatientInfo?.code ?? '';
    patientName = Store.user.currentSelectPatientInfo?.patientName ?? '';
    _getFollowUpRecordList();
    _followUpController = Get.put(FollowUpController());
  }

  Future<void> _getFollowUpRecordList() async {
    try {
      var result = await _followUpManager.getFollowUpRecordList(
          followUpKeyValue.keys.toList(), patientCode);
      if (result != null) {
        state.followUpDTOList = result;
      }
    } catch (e) {
      return;
    }
  }

  Future<void> updateFollowUp(key, code, data) async {
    List<String> followUpPhotos = [];
    if (_followUpController.state.followUpPhoto?.isNotEmpty ?? false) {
      followUpPhotos = [_followUpController.state.followUpPhoto!];
    }
    final result = await _followUpManager.updateFollowUp(
      UpdateFollowUpRequest(
        key: key,
        followUpData: data,
        followUpTime: _followUpController.state.followUpTime,
        nextFollowUpTime: _followUpController.state.nextFollowUpTime,
        followUpMode: _followUpController.state.followUpMode ??
            FollowUpModeEnum.Outpatient,
        code: code,
        followUpPhotos: followUpPhotos,
      ),
    );
    if (result ?? false) {
      PromptBox.toast('保存成功');
    } else {
      PromptBox.toast('保存失败');
    }
  }

  ///读取静态Html
  Future<String> loadingLocalAsset(String key) async {
    String tableName = "";
    if (key == 'GXY') {
      tableName = 'assets/docs/highBloodPressureTable.html';
    } else if (key == 'TNB') {
      tableName = 'assets/docs/diabetesTable.html';
    }

    ///加载
    String htmlData = await rootBundle.loadString(tableName);
    print("加载数据完成 $htmlData");
    return htmlData;
  }

  Future<List> getFollowUpTableData(FollowUpRecordDTO dto, int index) async {
    var currentFollowUp = dto.followUpRecordDatas?[index];
    var followUpTableData = await _followUpManager
        .getFollowUpRecordListByYearAsync(GetFollowUpRecordListByYearRequest(
      year: (currentFollowUp?.followUpTime?.year ?? DateTime.now().year)
          .toString(),
      keys: [currentFollowUp?.key ?? ''],
      patientCode: patientCode,
    ));
    List tableData = [];

    followUpTableData?.first.followUpRecordDatas?.forEach((element) {
      Map followUp = {
        "Follow_Time": element.followUpTime != null
            ? DateFormat("yyyy-MM-dd").format(element.followUpTime!.toLocal())
            : "",
        "Follow_Type": '${(element.followUpMode?.index ?? 0) + 1} ',
        "Next_Follow_Up_Time": element.nextFollowUpTime != null
            ? DateFormat("yyyy-MM-dd")
                .format(element.nextFollowUpTime!.toLocal())
            : "",
      };
      followUp.addAll(jsonDecode(element.followUpData ?? ''));
      tableData.add(followUp);
    });

    return tableData;
  }

  Future<String> loadLocalAsset(String key) async {
    String tableName = "";
    if (key == 'GXY') {
      tableName = 'assets/docs/highBloodPressureTable.html';
    } else if (key == 'TNB') {
      tableName = 'assets/docs/diabetesTable.html';
    }

    ///加载
    String htmlData = await rootBundle.loadString(tableName);
    print("加载数据完成 $htmlData");
    return htmlData;
  }

  Future<void> showDialogBox(String initialData, String jsonData) async {
    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,
            child: InAppWebView(
              initialData: InAppWebViewInitialData(
                data: '<body style="padding:30px 100px;">$initialData </body>',
                mimeType: 'text/html',
                encoding: 'utf-8',
              ),
              onWebViewCreated: (controller) {
                controller.evaluateJavascript(
                    source: "window.tableData = $jsonData;");
              },
              onConsoleMessage: (controller, consoleMessage) {
                // print(consoleMessage);
              },
            ),
          ),
        ),
      ],
    ));
  }

  Future<void> toFollowUpDetailPage(int index, FollowUpRecordDTO dto) async {
    var tableData = await getFollowUpTableData(dto, index);
    var initialData =
        await loadLocalAsset(dto.followUpRecordDatas?[index].key ?? '');
    var jsonData = jsonEncode(tableData);

    showDialogBox(initialData, jsonData);
  }

  toCheckPage(FollowUpRecordDataDTO dataDTO) async {
    _followUpController.state.followUpTime = dataDTO.followUpTime;
    _followUpController.state.nextFollowUpTime = dataDTO.nextFollowUpTime;
    _followUpController.state.followUpMode = dataDTO.followUpMode;
    Get.to(
      ConfigurableCard(
        cardKey: dataDTO.key!,
        examData: dataDTO.followUpData,
        followUpWidget: const FollowUpFrom(),
        patientCode: patientCode,
        callBack: (key, code, data) async {
          await updateFollowUp(key, dataDTO.code, data);
          await _getFollowUpRecordList();
          return true;
        },
      ),
      transition: Transition.rightToLeft,
    );
  }

  final Map<String, String> followUpKeyValue = {
    'FJHSFFW': "肺结核随访服务",
    'FJHRHSF': "肺结核入户随访",
    'GXB': "冠心病",
    'NCZ': "脑卒中",
    'YZJSZASFFW': "严重精神障碍随访服务",
    'YZJSZAGRXXBC': "严重精神障碍个人信息补充",
    'TNB': "2型糖尿病",
    'GXY': "高血压",
    'LNRZYYJKGLFWJL': "老年人中医药健康管理服务记录表",
    'LNRSHZLNLPGB': "老年人生活自理能力评估表",
    'YCF_CH42TJKJCLB': "产后42天健康检查列表",
    'YCF_CHFSLB': "产后访视列表",
    'YCF_2_5CCQSFLB': "2~5次产前随访列表",
    'YCF_DYCCQJCLB': "第一次产前检查列表",
    'YCF_JBXX': "基本信息",
    'ET_ZYYJKGLLB': "儿童中医药健康管理列表",
    'ET_3_6SETJKJCLB': "3~6岁儿童健康检查列表",
    'ET_1_2SETJKJCLB': "1~2岁儿童健康检查列表",
    'ET_1SNETJKJCLB': "1岁内儿童健康检查列表",
    'ET_XSEFSLB': "新生儿访视列表",
  };

  String getFollowUpValueByKey(String key) {
    if (followUpKeyValue[key] != null) {
      return followUpKeyValue[key]!;
    } else {
      return "";
    }
  }

  String followUpStateTransition(FollowUpStateEnum state) {
    switch (state) {
      case FollowUpStateEnum.NoFollowUp:
        return "未随访";
      case FollowUpStateEnum.FollowUpVisit:
        return "已随访";
      case FollowUpStateEnum.Cancelled:
        return "已作废";
      default:
        return "";
    }
  }

  MaterialColor followUpStateColors(FollowUpStateEnum state) {
    switch (state) {
      case FollowUpStateEnum.NoFollowUp:
        return Colors.grey;
      case FollowUpStateEnum.Cancelled:
        return Colors.red;
      case FollowUpStateEnum.FollowUpVisit:
        return Colors.green;
      default:
        return Colors.blue;
    }
  }

  String getFollowUpMode(FollowUpModeEnum? modeEnum) {
    switch (modeEnum) {
      case FollowUpModeEnum.Outpatient:
        return "门诊";
      case FollowUpModeEnum.Phone:
        return "电话";
      case FollowUpModeEnum.Visit:
        return "家庭";
      default:
        return "";
    }
  }
}
