import 'package:eitc_erm_dental_flutter/entity/db/local_patient_info.dart';
import 'package:eitc_erm_dental_flutter/exts.dart';
import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:eitc_erm_dental_flutter/global.dart';
import 'package:eitc_erm_dental_flutter/pages/patient/vm/patient_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

///就诊人信息条
class PatientInfoBar extends ConsumerStatefulWidget {
  final VoidCallback onSwitchPatient;
  final VoidCallback onAddPatient;

  const PatientInfoBar(
      {super.key, required this.onSwitchPatient, required this.onAddPatient});

  @override
  ConsumerState createState() => _PatientInfoBarState();
}

class _PatientInfoBarState extends ConsumerState<PatientInfoBar> {
  bool _hasSyncPatientLIst = false;

  @override
  void initState() {
    super.initState();

    ref.listenManual(localPatientListProvider, (_, value) {
      isSyncingPatient = value is AsyncLoading;
      if (value is! AsyncData<List<LocalPatientInfo>> || _hasSyncPatientLIst) {
        return;
      }
      _hasSyncPatientLIst = true;
      logd("读取到本地咨询人数据,开始同步服务器数据");
      syncPatientList();
    });
  }

  void syncPatientList() async {
    //如果连的不是设备wifi,就同步咨询人数据
    if (await isDeviceWifi()) {
      return;
    }
    //检查新版本,之所以放在这里,是因为获取wifi名字时会申请权限
    //不能同时弹多个请求权限弹窗,所以这里请求完毕后再检查
    if (mounted) {
      checkNewVersion(context, ref);
    }
    logd("同步咨询人数据");
    ref.read(localPatientListProvider.notifier).syncPatientList();
  }

  @override
  Widget build(BuildContext context) {
    AsyncValue<List<LocalPatientInfo>> value =
        ref.watch(localPatientListProvider);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.symmetric(horizontal: 12.w),
      height: 62.h,
      decoration: BoxDecoration(
        color: context.surfaceContainerHighColor,
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: _getContent(value),
    );
  }

  ///获取内容
  Widget _getContent(AsyncValue<List<LocalPatientInfo>> value) {
    return switch (value) {
      AsyncData(value: var data) => _getSwitchPatient(data),
      AsyncError(error: var e, stackTrace: var stack) => _getError(e, stack),
      _ => _getLoading(),
    };
  }

  ///获取切换咨询人
  Widget _getSwitchPatient(List<LocalPatientInfo> list) {
    if (list.isEmpty) {
      return _getAddPatient();
    }
    //查找已选择的咨询人
    LocalPatientInfo? info =
        list.where((info) => info.id == selectedPatientId).firstOrNull;
    //如果没有就使用第一条记录,并保存id
    if (info == null) {
      info = list[0];
      setSelectedPatientId(info.id);
    }

    return Row(
      children: [
        Expanded(
            child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _getText(info.name ?? ""),
            _getText(setIdCardStar(info.idCardDecrypt))
          ],
        )),
        _getButton(getS().switchPatient, widget.onSwitchPatient),
      ],
    );
  }

  Widget _getError(Object e, StackTrace stackTrack) {
    loge("读取本地咨询人列表异常,", error: e, stackTrace: stackTrack);
    return _getAddPatient();
  }

  ///获取添加咨询人
  Widget _getAddPatient() {
    return Row(
      children: [
        Expanded(child: _getText(getS().needAddPatient)),
        _getButton(getS().addPatient, widget.onAddPatient),
      ],
    );
  }

  ///获取loading
  Widget _getLoading() {
    return Row(
      children: [
        Expanded(child: _getText(getS().syncDataWaiting)),
        SizedBox.fromSize(
          size: Size.square(25.r),
          child: CircularProgressIndicator(),
        ),
      ],
    );
  }

  ///获取文本
  Widget _getText(String text) {
    return Text(
      text,
    );
  }

  ///获取按钮
  Widget _getButton(String text, VoidCallback onPressed) {
    return InkWell(
      onTap: onPressed,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 6.h),
        decoration: BoxDecoration(
          color: context.primaryColor,
          borderRadius: BorderRadius.circular(4.r),
        ),
        child: Text(
          text,
          style: TextStyle(color: context.onPrimaryColor),
        ),
      ),
    );
  }
}
