import 'dart:convert';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';

import 'package:base/consts/color.dart';
import 'package:base/consts/route_category_front_component_const.dart';
import 'package:base/services/application.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:base/utils/request.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/tabbar_button.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../model/equipment_type_count_model.dart';
import '../routes/routes.dart';

class EquipmentInfo extends StatelessWidget {
  final Map params;

  const EquipmentInfo({@required this.params});

  @override
  Widget build(BuildContext context) {
    return EquipmentInfoContent(EquipmentTypeCountModel.fromJson(params));
  }
}

class EquipmentInfoContent extends StatefulWidget {
  final EquipmentTypeCountModel model;

  const EquipmentInfoContent(this.model);

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

class _EquipmentInfoContentState extends State<EquipmentInfoContent> {
  List<EquipmentTypeCountModel> data = [];

  bool isEmpty = false;
  String theme = '';

  initThemeConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        this.theme = preferences.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    initThemeConfig();
    String id = widget.model.ercode;
    HttpRequest.queryEquipmentCount(id).then((res) {
      if (res["status"] == 200) {
        List result = res["result"];
        List<EquipmentTypeCountModel> items = [];
        for (var json in result) {
          items.add(EquipmentTypeCountModel.fromJson(json));
        }
        setState(() {
          data = items;
        });

        if (items.isEmpty) {
          FlutterToast.toastCenter('暂无该类装备');
        }
      } else {}
    }).catchError((err) {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFFEFEFEF),
        appBar: AppBar(
          titleSpacing: 0,
          automaticallyImplyLeading: false,
          title: const Text('装备查询'),
          centerTitle: true,
          leading: LeadingButton(
            theme: theme,
          ),
          actions: <Widget>[
            GestureDetector(
              child: Container(
                child: Icon(
                  Icons.crop_free,
                  color: GetConfig.getColor(theme),
                ),
                padding: const EdgeInsets.only(right: 5),
              ),
              onTap: () {
                final params = {'title': '查询', 'category': RouteCategoryFrontComponentConst.query};
                Application.navigateToPath(context, Routes.equipWareHousing, params: params);
              },
            ),
          ],
        ),
        body: data.isEmpty
            ? Container()
            : Column(
                children: <Widget>[
                  // buildTopBar(),
                  buildList(context)
                ],
              ));
  }

  Widget buildTopBar() {
    return Container(
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          TopBarButton(
            name: "区域",
          ),
          TopBarButton(
            name: "品牌",
          ),
          TopBarButton(
            name: "规格",
          ),
        ],
      ),
    );
  }

  Widget buildList(BuildContext context) {
    return Expanded(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 8.px, vertical: 5.px),
        child: ListView.separated(
            padding: EdgeInsets.only(top: 5.px),
            itemBuilder: (ctx, index) {
              final item = data[index];
              return InkWell(
                onTap: () => onTap(context, item),
                child: Card(
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.px)),
                  elevation: 4,
                  shadowColor: const Color.fromRGBO(69, 91, 99, 0.08),
                  margin: EdgeInsets.zero,
                  child: Row(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.fromLTRB(20.px, 15.px, 15.px, 15.px),
                        child: Image.network(
                          item.img ?? 'assets/images/icon_default.png',
                          width: 50.px,
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.symmetric(vertical: 16.px),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                '${item.name}',
                                style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 16.px),
                              ),
                              SizedBox(
                                height: 5.px,
                              ),
                              RichText(
                                text: TextSpan(text: '数量', style: const TextStyle(color: Color(0xFF666666)), children: [
                                  WidgetSpan(
                                      child: SizedBox(
                                    width: 15.px,
                                  )),
                                  TextSpan(text: '${item.amount}', style: Theme.of(context).textTheme.headline3)
                                ]),
                              )
                            ],
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(right: 16.px),
                        child: const Icon(
                          Icons.keyboard_arrow_right,
                          color: Color(0xFFdddddd),
                        ),
                      )
                    ],
                  ),
                ),
              );
            },
            separatorBuilder: (ctx, index) {
              return SizedBox(
                height: 10.px,
              );
            },
            itemCount: data.length),
      ),
    );
  }

  void onTap(BuildContext context, EquipmentTypeCountModel item) {
    final params = {
      'category': RouteCategoryFrontComponentConst.equipment,
      'extension': json.encode({'id': item.ercode, 'name': item.name})
    };
    Application.navigateToPath(context, Routes.equipmentSecondInfo, params: params);
  }
}
