import 'package:fis_ui/utils/sizer/sizer.dart';
import 'package:flutter/material.dart';

enum ScreenDirection {
  /// 竖屏
  vertical,

  /// 横屏
  horizontal,
}

/// 小程序的屏幕旋转控制器，如果当前屏幕方向与 [direction] 不一致，则会提示用户旋转屏幕
class WxScreenDirectionLock extends StatefulWidget {
  final Widget page;
  final ScreenDirection direction;
  const WxScreenDirectionLock({
    Key? key,
    required this.page,
    required this.direction,
  }) : super(key: key);

  @override
  State<WxScreenDirectionLock> createState() => _WxScreenDirectionLockState();
}

class _WxScreenDirectionLockState extends State<WxScreenDirectionLock> {
  Size kScreenSize = Size.zero;
  ScreenDirection kScreenDirection = ScreenDirection.vertical;

  @override
  Widget build(BuildContext context) {
    if (kScreenDirection == widget.direction) {
      return widget.page;
    } else {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              RotatedBox(
                quarterTurns:
                    kScreenDirection == ScreenDirection.vertical ? 0 : 1,
                child: Icon(
                  Icons.screen_rotation,
                  size: 100,
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                "请旋转屏幕至${kScreenDirection == ScreenDirection.vertical ? '横屏' : '竖屏'}",
                style: TextStyle(fontSize: 20),
              ),
            ],
          ),
        ),
      );
    }
  }

  @override
  void dispose() {
    Sizer.ins.removeListener(_onWindowResize);
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    Sizer.ins.addListener(_onWindowResize);
    kScreenSize = Sizer.ins.size;
    kScreenDirection = _getScreenDirectionBySize(kScreenSize);
    print("初始时屏幕尺寸 $kScreenSize 方向 $kScreenDirection");
  }

  ScreenDirection _getScreenDirectionBySize(Size size) {
    if (size.width > size.height) {
      return ScreenDirection.horizontal;
    } else {
      return ScreenDirection.vertical;
    }
  }

  void _onWindowResize(e) {
    setState(() {
      kScreenSize = e;
      kScreenDirection = _getScreenDirectionBySize(kScreenSize);
    });
  }
}
