/// @author ilex.h

import 'package:flutter/material.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:get/get.dart';

import './../../../../entity/Page.dart';
import './../../../../routes/routes.dart';
import './../../../../services/api.dart';
import './../../../../utils/orientation_helper.dart';
import './../../../common/no_data.dart';

/// 视频监控列表
class MonitorVideoList extends StatefulWidget {
  const MonitorVideoList({Key key}) : super(key: key);

  @override
  _MonitorVideoListState createState() => _MonitorVideoListState();
}

class _MonitorVideoListState extends State<MonitorVideoList> {
  final List<Map<String, dynamic>> _data = [];

  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  final AmosPage _page = AmosPage(current: 1);

  bool isCard = false;

  /// 图片服务器前缀
  String imagePrefix = '';

  @override
  void initState() {
    super.initState();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imagePrefix = value;
      });
    });
    _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('视频监控列表'),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              isCard ? Icons.list : Icons.grid_view,
              color: Colors.white,
            ),
            onPressed: () {
              setState(() {
                isCard = !isCard;
              });
            },
          )
        ],
      ),
      body: _data.isNotEmpty ? _buildBody(context) : const EmptyData(),
    );
  }

  Widget _buildBody(BuildContext context) {
    return isCard ? _buildGridList(context) : _buildList(context);
  }

  Widget _buildList(BuildContext context) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      controller: _refreshController,
      header: const WaterDropMaterialHeader(),
      footer: const ClassicFooter(),
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: ListView.builder(
        itemCount: _data.length,
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          Map<String, dynamic> item = _data[index];
          String address = (item['address'] ?? '').toString();
          String name = (item['name'] ?? '').toString();
          int num = index + 1;
          return CommonCard(
            margin: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: ListTile(
                  title: Text(
                    '$num. $name',
                    style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0),
                  ),
                  subtitle: Container(
                    margin: const EdgeInsets.only(top: 6.0),
                    child: LabelValue(label: '安装位置', value: address),
                  ),
                  trailing: Icon(
                    Icons.chevron_right,
                    color: Theme.of(context).primaryColor,
                  ),
                  leading: Icon(
                    AmosIcon.webcam,
                    color: Theme.of(context).primaryColor,
                    size: 36,
                  ),
                  onTap: () {
                    Get.toNamed(JCSRoutes.monitorVideoDetail, arguments: item).then((value) {
                      OrientationHelper.setPortraitUp();
                    });
                  }),
            ),
          );
        },
      ),
    );
  }

  Widget _buildGridList(BuildContext context) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      controller: _refreshController,
      header: const WaterDropMaterialHeader(),
      footer: const ClassicFooter(),
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: GridView.builder(
        padding: const EdgeInsets.all(12.0),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,

          /// 每行显示2列
          mainAxisSpacing: 16.0,

          /// 每行的间距
          crossAxisSpacing: 6.0,

          /// 每列的间距
          childAspectRatio: 1,

          /// 显示区域宽高比
        ),
        itemCount: _data.length,
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          Map<String, dynamic> item = _data[index];
          String name = (item['name'] ?? '').toString();
          String address = (item['address'] ?? '').toString();
          String img = item['img']?.toString();

          if (!AmosValidate.isValidUrl(img)) {
            if (img != null && img.isNotEmpty) {
              img = Utils.completeUrl(imagePrefix, img);
            }
          }

          return TouchCallBack2(
              child: CommonCard(
                margin: EdgeInsets.zero,
                child: Column(children: [
                  Expanded(flex: 5, child: AmosImageIcon(image: img ?? 'assets/video_thumb.png')),
                  Expanded(
                    flex: 3,
                    child: ListTile(
                      contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                      tileColor: Colors.black87,
                      title: Text(
                        name,
                        style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0, color: Colors.white70),
                      ),
                      subtitle: Container(
                        margin: const EdgeInsets.only(top: 6.0),
                        child: Text(
                          address,
                          style: const TextStyle(fontSize: 14.0, color: Colors.white70),
                        ),
                      ),
                    ),
                  ),
                ]),
              ),
              onTap: () async {
                await Get.toNamed(JCSRoutes.monitorVideoDetail, arguments: item);
                OrientationHelper.setPortraitUp();
              });
        },
      ),
    );
  }

  void _onRefresh() {
    _page.current = 1;
    _data.clear();
    _getData();

    _refreshController.refreshCompleted();
  }

  void _onLoading() {
    _page.current += 1;
    _getData();

    _refreshController.loadComplete();
  }

  Future<void> _getData() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.equipMonitorVideoList(_page.current, _page.size);
      Get.back();
      if (data != null) {
        if ((data['records'] ?? []).length == 0) {
          _refreshController.loadNoData();
          return;
        }
        setState(() {
          _data.addAll(data['records'].cast<Map<String, dynamic>>());
        });
      }
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
    });
  }
}
