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

import 'package:base/consts/color.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:base/consts/route_category_front_component_const.dart';
import 'package:equipment_manage/model/equipment_type_count_model.dart';
import 'package:equipment_manage/routes/routes.dart';
import 'package:base/services/application.dart';
import 'package:base/utils/request.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/tabbar_button.dart';

class EquipmentInfo extends StatelessWidget {
  final Map params;
  EquipmentInfo({@required this.params});

  @override
  Widget build(BuildContext context) {
    return
        // Scaffold(
        // backgroundColor: Color(0xFFEFEFEF),
        //   appBar: AppBar(
        //     titleSpacing:0,
        //     automaticallyImplyLeading: false,
        //     title: Text('装备查询'),
        //     centerTitle: true,
        //     // SearchBar(
        //     //   title: "查询装备",
        //     //   onTap: (){
        //     //     Application.navigateTo(context, Routes.commonSearchList);
        //     //   },
        //     // ),
        //     leading: LeadingButton(
        //       theme: childKey.currentState.theme,
        //     ),
        //     actions: <Widget>[
        //       Container(
        //         padding: EdgeInsets.symmetric(horizontal: 10.px),
        //         child: SvgButton(
        //           src:"assets/images/icons/scan.png",
        //           size: 30.px,
        //           imageSize: 18.px,
        //           onTap: (){
        //             final params = {
        //               "title":"查询",
        //               "category":RouteCategoryFrontComponentConst.query
        //             };
        //             Application.navigateToPath(context, Routes.equipWareHousing,params: params);
        //           },
        //         ),
        //       )
        //     ],
        //   ),
        // body:
        EquipmentInfoContent(EquipmentTypeCountModel.fromJson(params));
    //);
  }
}

class EquipmentInfoContent extends StatefulWidget {
  final EquipmentTypeCountModel model;
  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.length == 0) {
          setState(() {
            isEmpty = true;
          });
        }
      }
    }).catchError((err) {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xFFEFEFEF),
        appBar: AppBar(
          titleSpacing: 0,
          automaticallyImplyLeading: false,
          title: Text('装备查询'),
          centerTitle: true,
          // SearchBar(
          //   title: "查询装备",
          //   onTap: (){
          //     Application.navigateTo(context, Routes.commonSearchList);
          //   },
          // ),
          leading: LeadingButton(
            theme: theme,
          ),
          actions: <Widget>[
            GestureDetector(
              child: Container(
                child: Icon(
                  Icons.crop_free,
                  color: GetConfig.getColor(theme),
                ),
                padding: EdgeInsets.only(right: 5),
              ),
              onTap: () {
                final params = {
                  "title": "查询",
                  "category": RouteCategoryFrontComponentConst.query
                };
                Application.navigateToPath(context, Routes.equipWareHousing,
                    params: params);
              },
            ),
          ],
        ),
        body: data.isEmpty
            ? const Center(
                child: CupertinoActivityIndicator(),
              )
            : 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: 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.asset(
                          "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: 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: 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);
    //   getEquipmentDel(context, item.ercode);
  }
  //装备详情查询跳转
  // getEquipmentDel(BuildContext context, String carid) async{
  //   Future.delayed(Duration.zero, () {
  //     HttpRequest.getEquipDel(carid).then((res) {
  //       //restartScanning(3);
  //       if (res["status"] == 200) {
  //         // _controller?.dispose();
  //         // _controller = null;
  //
  //         final params = {
  //           "title": "装备详情",
  //           "category": '1',
  //           "item":  "",
  //           "extension":json.encode(res["result"])
  //         };
  //
  //         Application.navigateToPath(context, Routes.vehicleHomePage,params: params);
  //
  //       } else {
  //
  //         Navigator.of(context).pop();
  //         FlutterToast.toastCenter(res['message']);
  //       }
  //     }).catchError((_) {
  //
  //       Navigator.of(context).pop();
  //       FlutterToast.toastCenter('请重新选择');
  //     });
  //   });
  // }

}
