import 'package:fis_common/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

import 'index.dart';

class WxConsultationCreateController extends GetxController {
  WxConsultationCreateController();

  final state = WxConsultationCreateState();

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  /// 表单数据
  String _patientName = '';
  int _patientSex = 0;
  String _patientAge = '';
  DateTime _birthday = DateTime.now();
  String _contactInfo = '';
  String _patientID = '';
  String _history = '';
  String _primaryDiagnosis = '';
  OrganBaseInfo? _hospital;
  DoctorInfo? _expert;
  DateTime _consultationDate = DateTime.now();
  String? _inspectionItems;
  String _scanDoctorName = '';
  TerminalInfo? _deviceModel;

  /// 外部数据
  List<OrganBaseInfo> hospitalList = [];
  List<DoctorInfo> expertList = [];
  List<String> inspectionItemsList = [];
  List<TerminalInfo> deviceModelList = [];

  String get patientName => _patientName;
  int get patientSex => _patientSex;
  String get patientAge => _patientAge;
  DateTime get birthday => _birthday;
  String get contactInfo => _contactInfo;
  String get patientID => _patientID;
  String get history => _history;
  String get primaryDiagnosis => _primaryDiagnosis;
  OrganBaseInfo? get hospital => _hospital;
  DoctorInfo? get expert => _expert;
  DateTime get consultationDate => _consultationDate;
  String? get inspectionItems => _inspectionItems;
  String get scanDoctorName => _scanDoctorName;
  TerminalInfo? get deviceModel => _deviceModel;

  set patientName(value) {
    _patientName = value;
    update();
  }

  set patientSex(value) {
    _patientSex = value;
    update();
  }

  set patientAge(value) {
    _patientAge = value;
    update();
  }

  set birthday(value) {
    _birthday = value;
    update();
  }

  set contactInfo(value) {
    _contactInfo = value;
    update();
  }

  set patientID(value) {
    _patientID = value;
    update();
  }

  set history(value) {
    _history = value;
    update();
  }

  set primaryDiagnosis(value) {
    _primaryDiagnosis = value;
    update();
  }

  set hospital(OrganBaseInfo? value) {
    _hospital = value;
    update();
  }

  set expert(DoctorInfo? value) {
    _expert = value;
    update();
  }

  set consultationDate(value) {
    _consultationDate = value;
    update();
  }

  set inspectionItems(String? value) {
    _inspectionItems = value;
    update();
  }

  set scanDoctorName(value) {
    _scanDoctorName = value;
    update();
  }

  set deviceModel(TerminalInfo? value) {
    _deviceModel = value;
    update();
  }

  // 姓名校验
  String? validateName(String? value) {
    if (value.isNullOrWhiteSpace) {
      return '请输入病人名称';
    }
    return null;
  }

  // 年龄校验
  String? validateAge(String? value) {
    if (value.isNullOrWhiteSpace) {
      return '请输入病人年龄';
    }
    return null;
  }

  // 手机号码校验
  String? validateContactInfo(String? value) {
    if (value.isNullOrWhiteSpace) {
      return '请输入手机号码';
    }
    return null;
  }

  // 病人ID校验
  String? validatePatientID(String? value) {
    if (value.isNullOrWhiteSpace) {
      return '请输入病人ID';
    }
    return null;
  }

  // 病史校验
  String? validateHistory(String? value) {
    if (value.isNullOrWhiteSpace) {
      return '请输入既往病史';
    }
    return null;
  }

  // 初步诊断校验
  String? validatePrimaryDiagnosis(String? value) {
    if (value.isNullOrWhiteSpace) {
      return '请输入初步诊断';
    }
    return null;
  }

  // 会诊医院校验
  String? validateHospitalId(OrganBaseInfo? value) {
    if (value == null) {
      return '请选择会诊医院';
    }
    return null;
  }

  /// 会诊专家校验
  String? validateExpertId(DoctorInfo? value) {
    if (value == null) {
      return '请选择会诊专家';
    }
    return null;
  }

  /// 扫查医生
  String? validateScanDoctorName(String? value) {
    if (value.isNullOrWhiteSpace) {
      return '请输入扫查医生';
    }
    return null;
  }

  /// 检查部位
  String? validateInspectItems(String? value) {
    if (value.isNullOrWhiteSpace) {
      return '请选择检查部位';
    }
    return null;
  }

  /// 设备型号
  String? validateDeviceModel(TerminalInfo? value) {
    if (value == null) {
      return '请选择设备型号';
    }
    return null;
  }

  // 表单提交
  void handleSubmit() async {
    final form = formKey.currentState;
    if (form == null) return;
    if (form.validate()) {
      form.save();
      final openId = Store.user.token;

      String result =
          await rpc.appletAPI.createConsultationAsync(CreateConsultationRequest(
        openId: openId,
        patientName: patientName,
        patientSex:
            patientSex == 0 ? PatientGenderEnum.Male : PatientGenderEnum.Female,
        patientAge: patientAge,
        birthday: birthday,
        contactInfo: contactInfo,
        patientID: patientID,
        history: history,
        primaryDiagnosis: primaryDiagnosis,
        hospitalId: hospital?.organizationId ?? '',
        expertId: expert?.id ?? '',
        consultationDate: consultationDate,
        inspectionItems: inspectionItems,
        scanDoctorName: scanDoctorName,
        deviceModel: deviceModel?.model ?? '',
        terminalId: deviceModel?.id ?? '',
      ));
      print("会诊创建 $result");
      if (result.isNullOrWhiteSpace) {
        Get.snackbar(
          "失败",
          "会诊创建失败，请重试",
        );
      } else {
        print("会诊创建成功 $result");
        Get.back(result: true);
      }
    }
  }

  /// 载入下拉选择器数据 [会诊医院] [会诊专家] [检查部位] [设备型号]
  void _loadSelectData() async {
    final openId = Store.user.token;
    final List<OrganBaseInfo> hospitalList =
        await rpc.appletAPI.getHospitalsAsync(
      GetHospitalsRequest(
        openId: openId,
      ),
    );

    final List<TerminalInfo> deviceModelList =
        await rpc.appletAPI.getTerminalListAsync(
      GetTerminalListRequest(
        openId: openId,
      ),
    );
    final List<String> inspectionItemsList =
        await rpc.appletAPI.getScanLocationsAsync(
      GetScanLocationsRequest(
        openId: openId,
      ),
    );
    this.hospitalList = hospitalList;
    this.deviceModelList = deviceModelList;
    this.inspectionItemsList = inspectionItemsList;
    update();
  }

  /// 更新会诊医院，联动更新会诊专家下拉选项
  void updateHospital(OrganBaseInfo? hospital) async {
    this.hospital = hospital;
    this.expert = null;
    if (hospital == null) {
      this.expertList = [];
      update();
      return;
    }
    final openId = Store.user.token;
    final List<DoctorInfo> expertList = await rpc.appletAPI.getExpertsAsync(
      GetExpertsRequest(
        openId: openId,
        organizationId: hospital.organizationId ?? '',
      ),
    );
    this.expertList = expertList;
    update();
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    _loadSelectData();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
