import 'dart:io';

import 'package:auto_route/annotations.dart';
import 'package:eitc_erm_dental_flutter/db_util.dart';
import 'package:eitc_erm_dental_flutter/entity/db/local_patient_info.dart';
import 'package:eitc_erm_dental_flutter/global.dart';
import 'package:eitc_erm_dental_flutter/pages/history/vm/history_view_model.dart';
import 'package:eitc_erm_dental_flutter/pages/history/widget/history_item_view.dart';
import 'package:eitc_erm_dental_flutter/widget/empty_widget.dart';
import 'package:eitc_erm_dental_flutter/widget/loading_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../entity/history_item_info.dart';
import '../../funcs.dart';
import '../../widget/main_button.dart';

///选择历史记录类型
enum SelectHistoryType {
  ///照片
  photo,

  ///录像
  record,

  ///所有
  all;
}

///历史记录选择页面
@RoutePage(name: "SelectHistoryRoute")
class SelectHistoryPage extends ConsumerStatefulWidget {
  ///选择类型
  final SelectHistoryType selectType;

  ///是否过滤咨询人
  final bool isFillterPatient;

  ///是否多选
  final bool isMultiSelect;

  ///多选最大数量,0表示没有限制
  final int maxCount;

  const SelectHistoryPage(
      {super.key,
      required this.selectType,
      required this.isFillterPatient,
      this.isMultiSelect = false,
      this.maxCount = 0});

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

class _SelectHistoryPageState extends ConsumerState<SelectHistoryPage> {
  ///咨询人信息
  LocalPatientInfo? _patientInfo;

  ///记录数量
  int _historyCount = 0;

  @override
  void initState() {
    super.initState();
    _initPatientInfo();
    _initMultiSelect();
  }

  ///初始化咨询人信息
  void _initPatientInfo() async {
    if (selectedPatientId < 0) {
      _patientInfo = null;
    }
    _patientInfo = await DbUtil.instance.getLocalPatientById(selectedPatientId);
  }

  ///初始化多选
  void _initMultiSelect() {
    ProviderSubscription<AsyncValue<HistoryListData>>? listenner;
    //需要在读取到数据后,渲染完一帧才设置选择模式,否则读取不到historySelectModeProvider
    listenner = ref.listenManual(historyListProvider, (_, value) {
      if (value is! AsyncData<HistoryListData>) {
        return;
      }
      listenner?.close();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ref
            .read(historySelectModeProvider.notifier)
            .setSelectMode(widget.isMultiSelect);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _getAppBar(context),
      body: SafeArea(
          child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Column(
          children: [
            _getSelectedCount(context),
            Expanded(child: _getListWidget(context)),
            _getBottomButtons(context),
            SizedBox(
              height: 5.h,
            )
          ],
        ),
      )),
    );
  }

  ///获取appbar
  AppBar _getAppBar(BuildContext context) {
    String title = switch (widget.selectType) {
      SelectHistoryType.photo => getS().selectPhoto,
      SelectHistoryType.record => getS().selectRecord,
      SelectHistoryType.all => getS().selectPhotoAndRecord,
    };

    return AppBar(
      centerTitle: true,
      forceMaterialTransparency: true,
      title: Text(title),
      leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: Icon(
              Platform.isIOS ? Icons.arrow_back_ios_new : Icons.arrow_back)),
    );
  }

  ///获取已选择数量widget
  Widget _getSelectedCount(BuildContext context) {
    if (!widget.isMultiSelect) {
      return SizedBox();
    }
    return Row(
      children: [
        Consumer(builder: (_, tref, __) {
          int count = tref.watch(historySelectedCountProvider);
          return Text(getS().hasSelectCountItem(count));
        }),
        SizedBox(
          width: 6.w,
        ),
        const Spacer(),
        SizedBox(
            width: 25.w,
            child: Consumer(builder: (_, cref, __) {
              int count = cref.watch(historySelectedCountProvider);
              int totalCount = 0;
              HistoryListData? data = cref.read(historyListProvider).value;
              if (data != null) {
                totalCount = switch (widget.selectType) {
                  SelectHistoryType.photo => data.photoList.length,
                  SelectHistoryType.record => data.videoList.length,
                  SelectHistoryType.all => data.getMergedList(false).length,
                };
              }
              return Checkbox(
                  value: totalCount > 0 && count == totalCount,
                  shape: const CircleBorder(),
                  onChanged: _onSelectAll);
            })),
        Text(getS().selectAll),
        SizedBox(
          width: 5.w,
        ),
      ],
    );
  }

  ///获取底部按钮
  Widget _getBottomButtons(BuildContext context) {
    return widget.isMultiSelect
        ? SizedBox(
            width: double.infinity,
            child: MainButton(
                text: getS().confirm, onPressed: () => _onConfirm(context)),
          )
        : SizedBox();
  }

  Widget _getListWidget(BuildContext context) {
    return Consumer(builder: (ctx, ref, _) {
      AsyncValue<HistoryListData> value = ref.watch(historyListProvider);
      return switch (value) {
        AsyncData<HistoryListData>(value: var data) => data.isEmpty
            ? EmptyWidget(
                text: getS().noHistories,
              )
            : _getGridView(switch (widget.selectType) {
                SelectHistoryType.photo => data.photoList,
                SelectHistoryType.record => data.videoList,
                SelectHistoryType.all => data.getMergedList(true)
              }),
        _ => LoadingWidget(
            text: getS().loadingHistories,
          )
      };
    });
  }

  ///获取GridView
  Widget _getGridView(List<HistoryItemInfo> list,
      {bool shinkWarp = false, bool scrollable = true}) {
    //是否过滤咨询人
    if (widget.isFillterPatient) {
      if (_patientInfo == null) {
        list = [];
      } else {
        list = list
            .where((info) =>
                info.prefixInfo != null &&
                info.prefixInfo!.name.isNotEmpty &&
                info.prefixInfo!.name == _patientInfo!.name)
            .toList();
      }
    }

    _historyCount = list.length;

    return GridView.builder(
      shrinkWrap: shinkWarp,
      physics: scrollable
          ? const ClampingScrollPhysics()
          : const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 164.0 / 120.0,
          mainAxisSpacing: 8.r,
          crossAxisSpacing: 15.r),
      itemBuilder: (ctx, index) {
        HistoryItemInfo item = list[index];
        return GestureDetector(
          child: HistoryItemView(
            index: index,
            name: item.name,
            path: item.path,
            type: item.type,
          ),
          onTap: () => _onTap(ctx, item),
        );
      },
      itemCount: list.length,
    );
  }

  ///全选
  void _onSelectAll(bool? isSelect) {
    if (isSelect == null || !isSelect) {
      ref.read(historyListProvider.notifier).selectAll(false);
    } else {
      if (_historyCount <= 0) {
        return;
      }
      if (_historyCount > widget.maxCount) {
        showToast(text: getS().maxSelectCountXx(widget.maxCount));
        return;
      }
      ref.read(historyListProvider.notifier).selectAll(true);
    }
  }

  ///点击
  void _onTap(BuildContext context, HistoryItemInfo info) {
    if(info.isSelected)
    {
      ref.read(historyListProvider.notifier).select(info, false);
      return;
    }
    if (widget.isMultiSelect) {
      if (widget.maxCount > 0 &&
          ref.read(historySelectedCountProvider) >= widget.maxCount) {
        showToast(text: getS().maxSelectCountXx(widget.maxCount));
        return;
      }
      ref.read(historyListProvider.notifier).select(info, true);
      return;
    }
    _onSelected(context, [info]);
  }

  ///确定
  void _onConfirm(BuildContext context) {
    List<HistoryItemInfo> list =
        ref.read(historyListProvider.notifier).getSelectedItems();
    if (list.isEmpty) {
      showToast(text: getS().pleaseSelectAtLastOne);
      return;
    }
    _onSelected(context, list);
  }

  void _onSelected(BuildContext context, List<HistoryItemInfo> list) {
    Navigator.pop(context, list);
  }
}
