import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/storage/storage.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/interfaces/contract.dart';
import 'package:vitalapp/managers/interfaces/contract_template.dart';
import 'package:vitalapp/managers/interfaces/patient.dart';
import 'package:vitalapp/managers/interfaces/service_pack.dart';
import 'package:vitalapp/pages/controllers/crowd_labels.dart';
import 'package:vitalapp/pages/home/controller.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/store/store.dart';
import 'state.dart';

class ServicePackageContractController extends FControllerBase {
  final state = ServicePackageContractState();
  final _patientManager = Get.find<IPatientManager>();
  final _servicePackManager = Get.find<IServicePackManager>();
  final _contractManager = Get.find<IContractManager>();
  final _contractTemplateManager = Get.find<IContractTemplateManager>();

  List<LabelDTO> normalOptions = [];
  PatientDTO patient = PatientDTO();
  String templateCode = '';
  @override
  void onInit() {
    // final p = Get.parameters;
    // state.patientCode = p["patientCode"]!;
    state.patientCode = Store.user.currentSelectPatientInfo?.code ?? '';
    // patientName = Store.user.currentSelectPatientInfo?.patientName ?? '';
    super.onInit();
  }

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

  Future<void> _loadContractTemplate() async {
    final contractTemplateList =
        await _contractTemplateManager.getContractTemplatePageAsync();
    templateCode = contractTemplateList?.first.code ?? '';
  }

  Future<void> _loadData() async {
    final dto = await _patientManager.getDetail(state.patientCode);

    /// server 暂时没根据人群获取服务包列表这边先用全部服务包
    final result = await _servicePackManager.getServicePackList(
      ServicePackPageRequest(
        pageIndex: 1,
        pageSize: 20,
      ),
    );
    normalOptions = Get.find<CrowdLabelsController>().state.normalOptions;
    state.servicePackageItems = result?.pageData ?? [];

    final getServiceItemResult = await _servicePackManager.getServiceItemList(
      PageRequest(
        pageIndex: 1,
        pageSize: 100,
      ),
    );
    state.serviceItems = getServiceItemResult?.pageData ?? [];
    if (dto != null) {
      dto.birthday = dto.birthday!.toLocal();
      state.updateDto(dto);
      update();
      patient = dto;
    }
  }

  String setNormalLabels(List<String> normalValueList) {
    List<String> normalLabels = [];
    for (LabelDTO i in normalOptions) {
      if (normalValueList.contains(i.code)) {
        normalLabels.add(i.labelName ?? '');
      }
    }
    String labels = normalLabels.join('、');
    if (labels.isEmpty) {
      return '暂无';
    }
    return labels;
  }

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

  bool verifyData() {
    // todo：人像采集
    if (state.userImage == null || state.userImage!.isEmpty) {
      PromptBox.toast('未进行人像拍照');
      return false;
    }

    if (state.selectedServicePackageCode.isEmpty) {
      PromptBox.toast('未选择服务包');
      return false;
    }
    return true;
  }

  Future<void> submitContract() async {
    if (state.isDenySbaVisa &&
        (state.reasonRefusal == null || state.reasonRefusal!.isEmpty)) {
      PromptBox.toast('未选择拒签原因');
      return;
    }
    await createContractRecord();
    Get.find<HomeController>().switchNavByName('/patient/detail');
  }

  List<ServiceItemDTO> getServiceItemsName(List<String> serviceItems) {
    List<ServiceItemDTO> serviceItemNames = [];
    for (var element in state.serviceItems) {
      if (serviceItems.contains(element.code)) {
        serviceItemNames.add(element);
      }
    }
    if (serviceItemNames.isEmpty) {
      return [];
    }
    return serviceItemNames.reversed.toList();
  }

  void processingPortraits() async {
    XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
    Store.app.busy = true;
    final url = await rpc.storage.upload(image!);
    state.userImage = url;
    Store.app.busy = false;
  }

  // 切换选择的服务包
  void changeServicePackage(ServicePackDTO servicePackDTO) {
    List<ServicePackDTO> selectedServicePackage = state.selectedServicePackage;
    if (state.selectedServicePackage.contains(servicePackDTO)) {
      selectedServicePackage.remove(servicePackDTO);
    } else {
      selectedServicePackage.add(servicePackDTO);
    }
    state.selectedServicePackage = selectedServicePackage;
    setSelectedServicePackages();
  }

  void setSelectedServicePackages() {
    List<String> selectedServicePackageNameList = [];
    List<String> selectedServicePackageCodeList = [];
    for (var element in state.selectedServicePackage) {
      selectedServicePackageNameList.add(element.name ?? "");
      selectedServicePackageCodeList.add(element.code ?? "");
    }
    state.selectedServicePackageName = selectedServicePackageNameList.join('、');
    state.selectedServicePackageCode = selectedServicePackageCodeList.join('、');
  }
}
