import 'dart:async';

import 'package:flutter/material.dart';

import '../../bean/result_list_bean.dart';
import '../../bean/room_list_bean.dart';
import '../home/home_model.dart';
import 'machine_page.dart';

class MachineRoomPage extends StatefulWidget {
  String deptId;

  MachineRoomPage({super.key, required this.deptId});

  @override
  State<MachineRoomPage> createState() => _MachineRoomPageState();
}

class _MachineRoomPageState extends State<MachineRoomPage> {
  late StreamSubscription subscription;
  final HomeModel _viewmodel = HomeModel();
  late RoomListBean roomListBean;

  bool isLoad = false;

  // 控制列表滚动
  final ScrollController _scrollController = ScrollController();

  // 是否正在加载更多
  bool _isLoadingMore = false;

  // 是否还有更多数据
  final bool _hasMoreData = true;
  int pageNum = 1;
  List<ResultListBean> roomList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // 监听滚动事件，实现上拉加载
    _scrollController.addListener(_scrollListener);

    subscription = _viewmodel.streamController.stream.listen((event) {
      String code = event['code'];
      if (code.isNotEmpty) {
        switch (code) {
          case "roomList":
            isLoad = true;
            roomListBean = event['data'];
            roomList.addAll(roomListBean.result);
            _isLoadingMore = false;
            // if (roomList.length == roomListBean.totalNum) {
            //   _hasMoreData = false;
            // }
            break;
        }
      }
      setState(() {});
    });

    _viewmodel.roomList(pageNum, 20, widget.deptId);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _scrollController.dispose();
    subscription.cancel();
    super.dispose();
  }

  // 滚动监听
  void _scrollListener() {
    // 判断是否滑到了列表底部
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100 && !_isLoadingMore && _hasMoreData) {
      _loadMoreData();
    }
  }

  // 下拉刷新数据
  Future<void> _refreshData() async {
    pageNum = 1;
    // roomList.clear();
    _viewmodel.roomList(pageNum, 20, widget.deptId);
  }

  // 加载更多数据
  Future<void> _loadMoreData() async {
    if (_isLoadingMore) return;
    setState(() {
      _isLoadingMore = true;
      pageNum++;
    });
    _viewmodel.roomList(pageNum, 20, widget.deptId);
  }

  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    final size = MediaQuery.of(context).size;
    final t10 = size.width / 36;
    final w25 = size.width / 14.4;
    final p5 = size.width / 72;
    final w9 = size.width / 40;
    final s21 = size.width / 17.142857142857;
    final t20 = size.width / 18;

    return Scaffold(
      backgroundColor: const Color(0xFFD8D8D8),
      body: Container(
        decoration: const BoxDecoration(
            image: DecorationImage(
          image: AssetImage('assets/images/home_bg.png'),
          fit: BoxFit.cover,
        )),
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: statusBarHeight + t10, left: t10, right: t10),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      width: w25,
                      height: w25,
                      padding: EdgeInsets.all(p5),
                      child: Image(
                        width: w9,
                        image: const AssetImage('assets/images/ic_back.png'),
                      ),
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    child: Text(
                      '机房列表',
                      style: TextStyle(fontSize: s21, fontWeight: FontWeight.w600),
                    ),
                  ),
                  Container(
                    width: w25,
                    height: w25,
                    padding: EdgeInsets.all(p5),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(top: t20, left: t10, right: t10),
                child: RefreshIndicator(
                  color: const Color(0xFF1A73EC),
                  onRefresh: _refreshData,
                  child: ListView.builder(
                      controller: _scrollController,
                      itemCount: roomList.length,
                      padding: const EdgeInsets.all(0),
                      itemBuilder: (BuildContext context, int index) {
                        return _item(index, roomList[index], context);
                      }),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _item(index, ResultListBean bean, context) {
    final size = MediaQuery.of(context).size;
    final t10 = size.width / 36;
    final s16 = size.width / 22.5;
    final t30 = size.width / 12;
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => MachinePage(
              roomId: "${bean.id}",
              roomName: "${bean.roomName}",
            ),
          ),
        );
      },
      child: Card(
        color: Colors.white,
        child: Container(
          margin: EdgeInsets.only(bottom: t10),
          child: Column(
            children: [
              Container(
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.only(left: t10, top: t10),
                child: Text(
                  "机房名: ${bean.roomName}",
                  style: TextStyle(fontSize: s16, color: const Color(0xFF666666)),
                ),
              ),
              Container(
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.only(left: t10, top: t10, right: t10),
                child: Text(
                  "地址: ${bean.roomAddress}",
                  style: TextStyle(fontSize: s16, color: const Color(0xFF666666)),
                ),
              ),
              Container(
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.only(left: t10, top: t30, right: t10),
                child: Text(
                  "ODF: ${bean.racksCount}台",
                  style: TextStyle(fontSize: s16),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
