import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/routes/routes.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../viewmodel/Hazardous_chemicals.dart';
import 'HazardousChemicals_search.dart';

/// 危化品查询
class HazardousChemicals extends StatefulWidget {
  const HazardousChemicals({Key key}) : super(key: key);

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

class _HazardousChemicalsState extends State<HazardousChemicals> {
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  int pageIndex = 0;
  int total = 0;
  String theme = '';
  final List hazardousList = [];
  String name;
  String imageUrl = '';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('危化品查询', style: Theme.of(context).appBarTheme.textTheme.headline1),
          actions: [
            Align(
                child: Padding(
              padding: const EdgeInsets.only(right: 8),
              child: GestureDetector(
                  onTap: () async {
                    String keyword = await Get.to(const HazardousChemicalsSearchPage()) as String;
                    if (keyword != null && keyword.isNotEmpty) {
                      setState(() {
                        name = keyword;
                        pageIndex = 0;
                        hazardousList.clear();
                      });
                      _loadMore();
                    }
                  },
                  child: const Icon(
                    Icons.search,
                    color: Colors.white,
                    size: 25,
                  )),
            ))
          ],
        ),
        body: Column(children: <Widget>[
          hazardousList.isNotEmpty
              ? Expanded(
                  child: SmartRefresher(
                      enablePullDown: true,
                      enablePullUp: true,
                      controller: _refreshController,
                      header: const WaterDropMaterialHeader(),
                      footer: const ClassicFooter(),
                      child: ListView.builder(
                          itemCount: hazardousList.length,
                          shrinkWrap: true,
                          itemBuilder: (BuildContext context, int index) {
                            HazardousChemicalsModel item = HazardousChemicalsModel.fromJson(hazardousList[index]);
                            ListViewItemModel listViewItemModel = ListViewItemModel(
                                title: item?.name ?? '',
                                img: '${item.image}',
                                image: (item.image != null && item.image.split(',').isNotEmpty)
                                    ? Image.network(
                                        imageUrl + item.image.split(',')[0],
                                        width: 70,
                                        fit: BoxFit.fill,
                                        errorBuilder: (
                                          BuildContext context,
                                          Object error,
                                          StackTrace stackTrace,
                                        ) {
                                          return Image.asset(
                                            'assets/images/hazardous.png',
                                            width: 70,
                                            fit: BoxFit.fill,
                                          );
                                        },
                                      )
                                    : Image.asset(
                                        'assets/images/hazardous.png',
                                        width: 70,
                                        fit: BoxFit.fill,
                                      ));
                            return PowerListViewItem(
                                listViewItemModel: listViewItemModel,
                                contentWidget: Padding(
                                    padding: const EdgeInsets.all(5.0),
                                    child: InkWell(
                                        onTap: () {
                                          Get.toNamed(JCSRoutes.hazardousChemicalsDetail, arguments: hazardousList[index]);
                                        },
                                        child: Column(children: [
                                          LabelValue(label: '类    名', value: item?.type ?? ''),
                                          const SizedBox(height: 5),
                                          LabelValue(label: '英文名', value: item?.englishName ?? ''),
                                          const SizedBox(height: 5),
                                          LabelValue(label: '分子式', value: item?.formula ?? '')
                                        ]))));
                          }),
                      onRefresh: () {
                        total = 0;
                        pageIndex = 0;
                        hazardousList.clear();
                        name = null;
                        _getData();
                      },
                      onLoading: () {
                        if (total == hazardousList.length) {
                          return;
                        }
                        pageIndex += 1;
                        _loadMore();
                      }))
              : const NoData()
        ]));
  }

  /// 查询列表数据
  Future<void> _getData() async {
    setState(() {
      pageIndex = 0;
      name = null;
      hazardousList.clear();
    });
    _loadMore();
  }

  Future<void> _loadMore() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '查询中，请稍后...');
      Map<String, dynamic> query = {'pageNum': pageIndex, 'pageSize': 10};
      if (name != null) {
        query['name'] = name;
      }
      var data = await API.getHazardousChemicals(query);
      if (hazardousList != null) {
        setState(() {
          if (data != null && data['records'].length > 0) {
            total = int.parse(data['total']) ?? 0;
            for (dynamic p in data['records']) {
              hazardousList.add(p);
            }
            _refreshController.loadComplete();
          } else {
            _refreshController.loadNoData();
          }
        });
        _refreshController.refreshCompleted();
      }
    }).whenComplete(() => Get.back());
  }
}

class PowerListViewItem extends StatelessWidget {
  ///数据model
  ListViewItemModel listViewItemModel;

  ///自定义item内容
  final Widget contentWidget;

  PowerListViewItem({@required this.listViewItemModel, @required this.contentWidget});

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: const EdgeInsets.only(left: 6, top: 6, right: 6),
        decoration: BoxDecoration(boxShadow: [CoreColors.boxShadow]),
        child: ClipRRect(
            borderRadius: FormStyles.borderRadius,
            child: Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    border: listViewItemModel.hasState
                        ? Border(left: BorderSide(color: listViewItemModel.stateColor, width: 10))
                        : null),
                child: InkWell(
                    onTap: () {
                      if (listViewItemModel.onclick != null) {
                        listViewItemModel.onclick();
                      }
                    },
                    child: Flex(direction: Axis.vertical, children: [
                      Padding(
                          padding: const EdgeInsets.only(left: 5),
                          child: Flex(direction: Axis.horizontal, children: [
                            Container(width: 97, child: listViewItemModel.image),
                            Expanded(
                              child: Flex(direction: Axis.vertical, crossAxisAlignment: CrossAxisAlignment.start, children: [
                                listViewItemModel.hasTitle
                                    ? Padding(
                                        padding: const EdgeInsets.all(5.0),
                                        child: Text(listViewItemModel.title, style: const TextStyle(fontSize: 16)))
                                    : Container(),
                                contentWidget
                              ]),
                            )
                          ])),
                      listViewItemModel.hasFooter
                          ? Container(
                              color: const Color.fromRGBO(250, 250, 250, 1.0),
                              child: Row(children: [
                                Padding(
                                    padding: const EdgeInsets.only(left: 10, top: 5, right: 5, bottom: 5),
                                    child: Text(listViewItemModel.footer, style: const TextStyle(color: Colors.black54)))
                              ]))
                          : Container(),
                    ])))));
  }
}

class ListViewItemModel {
  ///是否含有状态
  bool hasState;

  ///状态颜色
  Color stateColor;

  ///标题内容
  bool hasTitle;

  ///是否含有标题
  String title;

  ///页脚内容
  bool hasFooter;

  ///是否含有页脚
  String footer;

  ///列表点击事件
  Function onclick;

  /// 左侧显示图片
  String img;
  Image image;

  ListViewItemModel(
      {this.hasState = false,
      this.stateColor,
      this.hasTitle = true,
      this.title,
      this.hasFooter = false,
      this.img,
      this.image,
      this.footer,
      this.onclick})
      : assert(hasState || stateColor == null, 'stateColor不能为空'),
        assert(hasTitle || title == null, 'title不能为空'),
        assert(hasFooter || footer == null, 'footer不能为空');
}
