import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:eitc_erm_dental_flutter/entity/history_item_info.dart';
import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:eitc_erm_dental_flutter/pages/history/vm/history_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_view/photo_view.dart';

import '../../app_router.gr.dart';
import 'widget/history_view_operation_view.dart';
import 'widget/history_view_title.dart';

///照片查看页面
@RoutePage(name: "photoViewRoute")
class PhotoViewPage extends ConsumerStatefulWidget {
  final HistoryItemInfo? info;

  const PhotoViewPage({super.key, required this.info});

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

class _PhotoViewPageState extends ConsumerState<PhotoViewPage> {
  @override
  void initState() {
    super.initState();
    //开启屏幕旋转
    screenEnableRotate();
  }

  @override
  void dispose() {
    super.dispose();
    //关闭屏幕旋转
    screenDisableRotate();
  }

  @override
  Widget build(BuildContext context) {
    Widget photoView = widget.info == null
        ? const SizedBox()
        : PhotoView(imageProvider: FileImage(File(widget.info!.path)));

    return Scaffold(
      body: SafeArea(
        child: Container(
          color: Colors.black,
          child: Stack(
            children: [
              photoView,
              Align(
                alignment: Alignment.topLeft,
                child: HistoryViewTitle(
                  name: widget.info?.name,
                ),
              ),
              HistoryViewOperationView(
                onUpload: () => _onUpload(context),
                onDelete: () => _onDelete(context),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _onUpload(BuildContext context) async {
    if (!await checkInternetWifi()) {
      return;
    }
    if (context.mounted) {
      context.pushRoute(UploadSelectClinicRoute(
          uploadList: [widget.info!], isFromView: true));
    }
  }

  void _onDelete(BuildContext context) async {
    bool? bo = await showDeleteAlertDialog(context, getS().deletePhotoHint);
    if (bo == null || !bo) {
      return;
    }

    bool result =
        await ref.read(historyListProvider.notifier).delete([widget.info!]);
    if (result) {
      showToast(text: getS().deleteSuccess);
      if (context.mounted) {
        Navigator.pop(context, widget.info);
      }
    } else {
      showToast(text: getS().deleteFailed);
    }
  }
}
