import 'package:auto_route/auto_route.dart';
import 'package:eitc_erm_dental_flutter/app_router.gr.dart';
import 'package:eitc_erm_dental_flutter/entity/clinic_info.dart';
import 'package:eitc_erm_dental_flutter/entity/history_item_info.dart';
import 'package:eitc_erm_dental_flutter/exts.dart';
import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:eitc_erm_dental_flutter/http/api_exception.dart';
import 'package:eitc_erm_dental_flutter/pages/upload/vm/upload_view_model.dart';
import 'package:eitc_erm_dental_flutter/widget/custom_divider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

///上传选择医院页面
@RoutePage(name: "uploadSelectClinicRoute")
class UploadSelectClinicPage extends StatefulWidget {
  final List<HistoryItemInfo> uploadList;

  ///是否是从查看页面上传
  final bool isFromView;

  const UploadSelectClinicPage(
      {super.key, required this.uploadList, required this.isFromView});

  @override
  State<UploadSelectClinicPage> createState() => _UploadSelectClinicPageState();
}

class _UploadSelectClinicPageState extends State<UploadSelectClinicPage> {
  bool _isExpand = false;
  List<ClinicInfo> _clinicList = [];
  bool _isToUpload = false;

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

  @override
  void dispose() {
    super.dispose();
    //如果不是前往上传页且是从查看页面上传,就恢复屏幕旋转
    if (!_isToUpload && widget.isFromView) {
      screenEnableRotate();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
          child: SizedBox.expand(
        child: Padding(
          padding: EdgeInsets.fromLTRB(34.w, 52.h, 34.w, 24.h),
          child: Column(
            children: [
              Text(
                getS().pleaseSelectUploadClinic,
                style: context.titleLarge,
              ),
              SizedBox(
                height: 24.h,
              ),
              _isExpand
                  ? _getList(context, _clinicList)
                  : Consumer(builder: (ctx, ref, _) {
                      AsyncValue<List<ClinicInfo>> value =
                          ref.watch(clinicListProvider);
                      return switch (value) {
                        AsyncData(value: var data) =>
                          data.isEmpty ? _getEmpty() : _getSelector(ctx, data),
                        AsyncError(:final error) =>
                          _getError(ApiException.from(error)),
                        _ => Expanded(
                              child: Center(
                            child: CircularProgressIndicator(),
                          )),
                      };
                    }),
            ],
          ),
        ),
      )),
    );
  }

  ///获取错误Widget
  Widget _getError(ApiException exception) {
    return Expanded(
        child: Center(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(
            Icons.error,
            color: Colors.red,
          ),
          SizedBox(
            width: 5.w,
          ),
          Text(
            "${exception.message}",
            style: const TextStyle(color: Colors.red),
          )
        ],
      ),
    ));
  }

  ///获取无数据Widget
  Widget _getEmpty() {
    return Expanded(
        child: Center(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.error),
          SizedBox(
            width: 5.w,
          ),
          Text(getS().noData),
        ],
      ),
    ));
  }

  ///返回选择器样式的第一条医院名字widget
  Widget _getSelector(BuildContext context, List<ClinicInfo> list) {
    _clinicList = list;
    return GestureDetector(
      onTap: () {
        setState(() {
          _isExpand = true;
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 14.h),
        decoration: BoxDecoration(
            color: context.surfaceContainerHighColor,
            borderRadius: BorderRadius.circular(8.r)),
        child: Row(
          children: [
            Expanded(child: Text(list[0].clinicName ?? "")),
            const Icon(Icons.arrow_drop_down_outlined)
          ],
        ),
      ),
    );
  }

  ///获取列表Widget
  Widget _getList(BuildContext context, List<ClinicInfo> list) {
    return Container(
      decoration: BoxDecoration(
          color: context.surfaceContainerHighColor,
          borderRadius: BorderRadius.circular(8.r)),
      child: ListView.separated(
          shrinkWrap: true,
          itemBuilder: (ctx, index) {
            ClinicInfo info = list[index];
            return InkWell(
              onTap: () => _onSelectClinic(info),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 14.h),
                child: Row(
                  children: [
                    Expanded(child: Text(info.clinicName ?? "")),
                    //每行都增加一个透明的箭头,以保证高度和未点击列表前的高度一致
                    const Icon(
                      Icons.arrow_drop_down_outlined,
                      color: Colors.transparent,
                    )
                  ],
                ),
              ),
            );
          },
          separatorBuilder: (_, __) => const CustomDivider(
                height: 0.0,
              ),
          itemCount: list.length),
    );
  }

  ///当选择了医院
  void _onSelectClinic(ClinicInfo info) async {
    logd("选择了医院,${info.toString()}");
    if (info.clinicApiUrl.isNullOrEmpty ||
        !(info.clinicApiUrl!.startsWith("http://") ||
            info.clinicApiUrl!.startsWith("https://"))) {
      logd("医院上传地址为空或不是以http://、https://开头");
      return;
    }

    String? deviceModel = await getDeviceModel();
    if (deviceModel.isNullOrEmpty) {
      logd("设备型号为空,无法上传");
      return;
    }
    logd("设备型号=$deviceModel");
    if (mounted) {
      _isToUpload = true;
      AutoRouter.of(context).popAndPush(UploadRoute(
          uploadList: widget.uploadList,
          clinicInfo: info,
          isFromView: widget.isFromView));
    }
  }
}
