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

import 'wx_screen_direction_lock.dart';

/// 小程序的横竖屏布局控制器，如果当前屏幕方向与 [direction] 不一致，则切换布局
class WxScreenDirectionContainer extends StatefulWidget {
  final Widget verticalLayout;
  final Widget horizontalLayout;

  /// 布局切换事件
  final ValueCallback<ScreenDirection>? onDirectionChanged;
  const WxScreenDirectionContainer({
    Key? key,
    required this.verticalLayout,
    required this.horizontalLayout,
    this.onDirectionChanged,
  }) : super(key: key);

  @override
  State<WxScreenDirectionContainer> createState() =>
      _WxScreenDirectionContainerState();
}

class _WxScreenDirectionContainerState
    extends State<WxScreenDirectionContainer> {
  Size kScreenSize = Size.zero;
  ScreenDirection kScreenDirection = Get.width > Get.height
      ? ScreenDirection.horizontal
      : ScreenDirection.vertical;

  @override
  Widget build(BuildContext context) {
    if (kScreenDirection == ScreenDirection.vertical) {
      return widget.verticalLayout;
    } else {
      return widget.horizontalLayout;
    }
  }

  @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);
  }

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

  void _onWindowResize(e) {
    final ScreenDirection newScreenDirection =
        _getScreenDirectionBySize(Get.size);
    setState(() {
      kScreenSize = e;
      kScreenDirection = newScreenDirection;
    });
    print("屏幕方向变化：$newScreenDirection");
    if (widget.onDirectionChanged != null) {
      widget.onDirectionChanged!(newScreenDirection);
    }
  }
}
