import 'dart:convert';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:vnoteapp/architecture/defines.dart';
import 'package:vnoteapp/managers/interfaces/contract.dart';
import 'package:vnoteapp/managers/interfaces/contract_template.dart';
import 'package:vnoteapp/store/store.dart';

import 'state.dart';

class ContractTemplateController extends FControllerBase {
  final state = ContractTemplateControllerState();
  final contractTemplateManager = Get.find<IContractTemplateManager>();
  final _contractManager = Get.find<IContractManager>();
  PatientDTO patient = PatientDTO();
  String servicePackageNames = "";
  String servicePackageCodes = "";
  String serviceTime = "1";
  String serviceStartDate = "";
  String base64Image = "";
  String notes = "";
  @override
  void onInit() {
    final p = Get.parameters;
    state.templateCode = p["templateCode"]!;
    patient = PatientDTO.fromJson(json.decode(p["patientInfo"]!));
    servicePackageNames = p["servicePackageNames"] ?? '';
    servicePackageCodes = p["servicePackageCodes"] ?? '';
    serviceTime = p["serviceTime"] ?? '1';
    serviceStartDate = p["serviceStartDate"] ?? '';
    base64Image = p["base64Image"] ?? '';
    notes = p["notes"] ?? '';
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    _loadData();
  }

  Future<void> _loadData() async {
    final dto = await contractTemplateManager
        .getContractTemplateDetail(state.templateCode);
    if (dto != null) {
      state.templateContent = dto.templateContent ?? '';
      getkey();
    }
  }

  void getkey() {
    RegExp regExp = RegExp(r'#(.*?)#');
    // Iterable<Match> matches = regExp.allMatches(state.templateContent);
    // for (Match match in matches) {
    //   String? key = match.group(1);
    // }
    String replacedString = state.templateContent.replaceAllMapped(
      regExp,
      (match) {
        String? key = match.group(1);
        String value = getValueForKey(key ?? ''); // 自定义函数，根据键获取真实值
        return value;
      },
    );
    state.templateContent = replacedString;
  }

  Future<void> createContractRecord() async {
    await _contractManager.createContractRecordAsync(
      CreateContractRecordRequest(
        contractedPatient: patient.code,
        contractedTime: DateTime.now(),
        serviceStartDate: DateTime.parse(serviceStartDate),
        serviceEndDate: DateTime.parse(serviceStartDate)
            .add(Duration(days: 365 * int.parse(serviceTime))),
        contractedFileUrl: state.templateContent,
        servicePacks: servicePackageCodes.split('、'),
        photos: ["data:image/png;base64,$base64Image"],
        notes: notes,
      ),
    );
  }

  String getValueForKey(String key) {
    // 根据键获取真实值的逻辑
    // 这里可以根据你的实际需求进行相应的处理
    if (key == 'doctorName') {
      return Store.user.principalName;
    } else if (key == 'doctorTel') {
      return Store.user.principalPhone;
    } else if (key == 'serviceTel') {
      return Store.user.organizationPhone;
    } else if (key == 'serviceAgency') {
      return Store.user.organizationName;
    } else if (key == 'patientName') {
      return patient.patientName ?? '';
    } else if (key == 'patientAddress') {
      return patient.patientAddress ?? '';
    } else if (key == 'cardNo') {
      return patient.cardNo ?? '';
    } else if (key == 'phone') {
      return patient.phone ?? '';
    } else if (key == 'servicesPackageContent') {
      return servicePackageNames;
    } else if (key == 'signaturePartyA') {
      return '<img src=${Store.user.signature}  style="width: 110px; height: 30px;" alt="图片">';
    } else if (key == 'signaturePartyB') {
      if (state.userSignature.isEmpty) {
        return '';
      } else {
        return '<img src=${state.userSignature}  style="width: 110px; height: 30px;" alt="图片">';
      }
    } else if (key == 'signatureDate') {
      return '';
    }

    return ''; // 如果找不到对应的键值，可以返回null或者其他默认值
  }
}
