import 'dart:convert';

import 'package:fis_jsonrpc/services/patient.m.dart';
import 'package:fis_jsonrpc/services/patientExtension.m.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/managers/interfaces/patient.dart';
import 'package:vitalapp/pages/patient/detail/controller.dart';
import 'package:vitalapp/store/store.dart';

import 'state.dart';

class PatientInfoController extends FControllerBase {
  final state = PatientInfoState();
  final _patientManager = Get.find<IPatientManager>();

  @override
  void onInit() {
    // final p = Get.parameters;
    // state.code = p["code"]!;
    state.code = Store.user.currentSelectPatientInfo?.code ?? '';
    super.onInit();
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    _loadData();
  }

  Future<void> _loadData() async {
    final dto = await _patientManager.getDetail(state.code);
    if (dto != null) {
      dto.birthday = dto.birthday!.toLocal();
      state.updateDto(dto);
    }

    getPatientExtensionDetailAsync();
  }

  Future<bool> updatePatientAsync() async {
    await createPatientExtensionAsync();
    UpdatePatientRequest request = UpdatePatientRequest(
      token: Store.user.token,
      code: state.code,
      patientName: state.name,
      phone: state.phoneNo,
      cardNo: state.cardNo,
      nationality: state.nation,
      birthday: state.birthday,
      cardType: state.cardType,
      patientGender: state.gender,
      patientAddress: state.address,
      permanentResidenceAddress: state.permanentResidenceAddress,
    );

    // String patientInfo = jsonEncode(patientInfoDto);

    final result = await _patientManager.updatePatientAsync(request);

    return result;
  }

  Future<bool> createPatientExtensionAsync() async {
    var healthModel = HealthModel(
      historyDrugAllergies: state.historyDrugAllergies,
      historyExposure: state.historyExposure,
      historyPreviousDisease: state.historyPreviousDisease,
      historyPreviousDiseaseOther: state.historyPreviousDiseaseOther,
      historyPreviousDiseaseOccupationalDisease:
          state.historyPreviousDiseaseOccupationalDisease,
      historyPreviousDiseaseMalignancy: state.historyPreviousDiseaseMalignancy,
      operation: state.operation,
      trauma: state.trauma,
      transfusion: state.transfusion,
      father: state.father,
      fatherOther: state.fatherOther,
      mother: state.mother,
      motherOther: state.motherOther,
      sibling: state.sibling,
      siblingOther: state.siblingOther,
      children: state.children,
      childrenOther: state.childrenOther,
      historyGenetic: state.historyGenetic,
      historyGeneticName: state.historyGeneticName,
      disabilitySituation: state.disabilitySituation,
      disabilitySituationOther: state.disabilitySituationOther,
      kitchenExhaustFacilities: state.kitchenExhaustFacilities,
      fuel: state.fuel,
      fuelOther: state.fuelOther,
      drinkingWater: state.drinkingWater,
      drinkingWaterOther: state.drinkingWaterOther,
      toilet: state.toilet,
      animalPen: state.animalPen,
      historyDrugAllergiesOther: state.historyDrugAllergiesOther,
      operationOne: state.operationOne,
      operationTwo: state.operationTwo,
      traumaOne: state.traumaOne,
      traumaTwo: state.traumaTwo,
      transfusionOne: state.transfusionOne,
      transfusionTwo: state.transfusionTwo,
      diseaseDiagnosisTime: state.diseaseDiagnosisTime,
      workUnit: state.workUnit,
      contactName: state.contactName,
      contactPhone: state.contactPhone,
      permanentlyResideType: state.permanentlyResideType,
      bloodType: state.bloodType,
      rh: state.rh,
      educationLevel: state.educationLevel,
      career: state.career,
      maritalStatus: state.maritalStatus,
      providerPayments: state.providerPayments,
      providerPaymentsOther: state.providerPaymentsOther,
    ).toJson();
    if (state.healthCode.isNotEmpty) {
      var request = UpdatePatientExtensionRequest(
          code: state.healthCode,
          token: Store.user.token,
          patientCode: state.code,
          key: "PatientHealthInfo",
          extensionData: jsonEncode(healthModel));

      var result = await _patientManager.updatePatientExtensionAsync(request);
      if (result) {}
    } else {
      var request = CreatePatientExtensionRequest(
          token: Store.user.token,
          patientCode: state.code,
          key: "PatientHealthInfo",
          extensionData: jsonEncode(healthModel));

      var result = await _patientManager.createPatientExtensionAsync(request);
      if (result.isNotEmpty) {
        state.healthCode = result;
      }
    }

    ///更新
    return true;
  }

  Future<void> getPatientExtensionDetailAsync() async {
    var request = GetPatientExtensionByCodeAndKeyRequest(
      token: Store.user.token,
      patientCode: state.code,
      key: "PatientHealthInfo",
    );
    var result = await _patientManager
        .getPatientExtensionDetailByCodeAndKeyAsync(request);
    if (result != null) {
      state.healthCode = result.code!;
      var mapList = jsonDecode(result.extensionData ?? "");
      var healthModel = HealthModel.fromJson(mapList);
      state.historyDrugAllergies = healthModel.historyDrugAllergies ?? [];
      state.historyExposure = healthModel.historyExposure ?? [];
      state.historyPreviousDisease = healthModel.historyPreviousDisease ?? [];
      state.historyPreviousDiseaseOther =
          healthModel.historyPreviousDiseaseOther ?? '';
      state.historyPreviousDiseaseOccupationalDisease =
          healthModel.historyPreviousDiseaseOccupationalDisease ?? '';
      state.historyPreviousDiseaseMalignancy =
          healthModel.historyPreviousDiseaseMalignancy ?? '';
      state.operation = healthModel.operation ?? '';
      state.trauma = healthModel.trauma ?? '';
      state.transfusion = healthModel.transfusion ?? '';
      state.father = healthModel.father ?? [];
      state.fatherOther = healthModel.fatherOther ?? '';
      state.mother = healthModel.mother ?? [];
      state.motherOther = healthModel.motherOther ?? '';
      state.sibling = healthModel.sibling ?? [];
      state.siblingOther = healthModel.siblingOther ?? '';
      state.children = healthModel.children ?? [];
      state.childrenOther = healthModel.childrenOther ?? '';
      state.historyGenetic = healthModel.historyGenetic ?? '';
      state.historyGeneticName = healthModel.historyGeneticName ?? '';
      state.disabilitySituation = healthModel.disabilitySituation ?? [];
      state.disabilitySituationOther =
          healthModel.disabilitySituationOther ?? '';
      state.kitchenExhaustFacilities =
          healthModel.kitchenExhaustFacilities ?? '';
      state.fuel = healthModel.fuel ?? '';
      state.fuelOther = healthModel.fuelOther ?? '';
      state.drinkingWater = healthModel.drinkingWater ?? '';
      state.drinkingWaterOther = healthModel.drinkingWaterOther ?? '';
      state.toilet = healthModel.toilet ?? '';
      state.animalPen = healthModel.animalPen ?? '';
      state.historyDrugAllergiesOther =
          healthModel.historyDrugAllergiesOther ?? '';
      state.operationOne = healthModel.operationOne;
      state.operationTwo = healthModel.operationTwo;
      state.transfusionOne = healthModel.transfusionOne;
      state.transfusionTwo = healthModel.transfusionTwo;
      state.traumaOne = healthModel.traumaOne;
      state.traumaTwo = healthModel.traumaTwo;
      state.diseaseDiagnosisTime = healthModel.diseaseDiagnosisTime;

      state.workUnit = healthModel.workUnit ?? '';
      state.contactName = healthModel.contactName ?? '';
      state.contactPhone = healthModel.contactPhone ?? '';
      state.permanentlyResideType = healthModel.permanentlyResideType ?? '';
      state.bloodType = healthModel.bloodType ?? '';
      state.rh = healthModel.rh ?? '';
      state.educationLevel = healthModel.educationLevel ?? '';
      state.career = healthModel.career ?? '';
      state.maritalStatus = healthModel.maritalStatus ?? '';
      state.providerPayments = healthModel.providerPayments ?? '';
      state.providerPaymentsOther = healthModel.providerPaymentsOther ?? '';
    }
  }

  Future<void> changePatient() async {
    PatientDTO? patientInfoDto = await _patientManager
        .getDetail(Store.user.currentSelectPatientInfo!.code!);
    Store.user.currentSelectPatientInfo = patientInfoDto;
    state.updateDto(patientInfoDto!);
    Get.find<PatientDetailController>().loadData();
  }

  /// 切换导航锚点
  void switchAnchor(NavAnchorType anchor) {
    state.anchor = anchor;
  }
}
