import 'package:eitc_erm_dental_flutter/entity/history_item_info.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../../funcs.dart';
import '../../../global.dart';
import '../../../sp_util.dart';

part 'history_view_model.g.dart';

///历史记录列表数据
class HistoryListData {
  final List<HistoryItemInfo> photoList;
  final List<HistoryItemInfo> videoList;

  HistoryListData(this.photoList, this.videoList);

  ///获取合并的列表
  List<HistoryItemInfo> getMergedList(bool sort) {
    List<HistoryItemInfo> list = [...photoList, ...videoList];
    if (sort) {
      list.sort((oi, ni) => ni.time - oi.time);
    }
    return list;
  }

  ///是否为空
  bool get isEmpty => photoList.isEmpty && videoList.isEmpty;
}

///历史记录列表
@riverpod
class HistoryList extends _$HistoryList {
  @override
  FutureOr<HistoryListData> build() async {
    String userId = await SpUtil.getUserId();
    if (userId.isEmpty) {
      return HistoryListData([], []);
    }
    //请求权限
    if (!await requestStoreagePermission()) {
      return HistoryListData([], []);
    }
    List<HistoryItemInfo> photoList = [];
    List<HistoryItemInfo> videoList = [];
    try {
      List<String>? pList = await fileChannel.invokeListMethod("getPhotoList");
      List<String>? vList = await fileChannel.invokeListMethod("getVideoList");
      if (pList != null) {
        photoList.addAll(pList
            .map((e) => HistoryItemInfo(e, 0))
            .where((e) => _validInfo(e, userId)));
        photoList.sort((oi, ni) => ni.time - oi.time);
      }
      if (vList != null) {
        videoList.addAll(vList
            .map((e) => HistoryItemInfo(e, 1))
            .where((e) => _validInfo(e, userId)));
        videoList.sort((oi, ni) => ni.time - oi.time);
      }
    } catch (e) {
      loge("读取文件列表异常", error: e);
    }
    return HistoryListData(photoList, videoList);
  }

  ///验证信息是否有效
  bool _validInfo(HistoryItemInfo info, String userId) {
    return info.isValid &&
        info.prefixInfo?.userId == userId &&
        info.prefixInfo?.idCard != null &&
        info.prefixInfo!.idCard.isNotEmpty;
  }

  ///删除
  Future<bool> delete(List<HistoryItemInfo> list) async {
    if (state.value == null) {
      return false;
    }
    bool isSuccess = true;
    var stream = Stream.fromIterable(list);
    await for (HistoryItemInfo info in stream) {
      try {
        logd("历史记录删除文件${info.path}");
        await fileChannel.invokeMethod("deleteFile", info.path);
        if (info.type == 0) {
          state.value!.photoList.remove(info);
        } else {
          state.value!.videoList.remove(info);
        }
      } catch (e) {
        loge("删除单个历史文件异常", error: e);
        isSuccess = false;
      }
    }
    ref.notifyListeners();
    ref.invalidate(historySelectedCountProvider);
    return isSuccess;
  }

  ///选择
  void select(HistoryItemInfo info, bool isSelected) {
    info.isSelected = isSelected;
    ref.invalidate(historyItemSelectedProvider(info.path));
    ref.invalidate(historySelectedCountProvider);
  }

  ///全选
  void selectAll(bool isSelected) {
    if (state.value == null) {
      return;
    }
    List<HistoryItemInfo> list = state.value!.getMergedList(false);
    for (HistoryItemInfo info in list) {
      info.isSelected = isSelected;
      ref.invalidate(historyItemSelectedProvider(info.path));
    }
    ref.invalidate(historySelectedCountProvider);
  }

  ///已选择的条目列表
  List<HistoryItemInfo> getSelectedItems() {
    if (state.value == null) {
      return [];
    }
    List<HistoryItemInfo> list = [
      ...state.value!.photoList,
      ...state.value!.videoList
    ];
    return list.where((info) => info.isSelected).toList();
  }
}

///历史记录选择模式
@riverpod
class HistorySelectMode extends _$HistorySelectMode {
  bool _isSelectMode = false;

  @override
  bool build() {
    return _isSelectMode;
  }

  ///设置选择模式
  void setSelectMode(bool isSelected) {
    _isSelectMode = isSelected;
    var notifier = ref.read(historyListProvider.notifier);
    HistoryListData? data = ref.read(historyListProvider).value;
    if (data != null) {
      for (HistoryItemInfo info in data.photoList) {
        info.isSelectMode = isSelected;
        if (!isSelected) {
          notifier.select(info, false);
        }
      }
      for (HistoryItemInfo info in data.videoList) {
        info.isSelectMode = isSelected;
        if (!isSelected) {
          notifier.select(info, false);
        }
      }
    }
    ref.invalidateSelf();
  }
}

///历史记录条目选择状态
@riverpod
bool historyItemSelected(HistoryItemSelectedRef ref, String path) {
  if (ref.read(historyListProvider).value == null) {
    return false;
  }
  HistoryItemInfo? info;
  List<HistoryItemInfo> list = [
    ...ref.read(historyListProvider).value!.photoList,
    ...ref.read(historyListProvider).value!.videoList
  ];
  for (HistoryItemInfo i in list) {
    if (i.path == path) {
      info = i;
      break;
    }
  }
  return info?.isSelected ?? false;
}

///历史记录查看类型
@riverpod
class HistoryViewType extends _$HistoryViewType {
  int _type = 0;

  @override
  int build() {
    return _type;
  }

  void setType(int type) {
    _type = type;
    ref.invalidateSelf();
  }
}

///历史记录选择数量
@riverpod
int historySelectedCount(HistorySelectedCountRef ref) {
  return ref.read(historyListProvider.notifier).getSelectedItems().length;
}
