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

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

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

class EquipmentSecondInfo extends StatelessWidget {
  final RouteModel routeModel;

  EquipmentSecondInfo({@required this.routeModel});

  @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>[
        //       SizedBox(width: 20.px,)
        //     ],
        //   ),
        //   body:
        EquipmentSecondInfoContent(
      routeModel: routeModel,
    );
    //);
  }
}

class EquipmentSecondInfoContent extends StatefulWidget {
  final RouteModel routeModel;

  EquipmentSecondInfoContent({this.routeModel});

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

class _EquipmentInfoContentState extends State<EquipmentSecondInfoContent> {
  List<EquipmentSecondModel> 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();
    final param = widget.routeModel.extension;
    String id = param["id"];
    String name = param["name"];

    HttpRequest.getEquipmentList(id, name: name).then((res) {
      if (res["status"] == 200) {
        List result = res["result"];
        List<EquipmentSecondModel> items = [];
        for (var json in result) {
          items.add(EquipmentSecondModel.fromJson(json));
        }

        setState(() {
          data = items;
        });

        if (result.length == 0) {
          FlutterToast.toastCenter('暂无该类装备');
          // setState(() {
          //   isEmpty = true;
          // });
        }
      } else {
        // 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>[
            SizedBox(
              width: 20.px,
            )
          ],
        ),
        body: data.length == 0 ? Container() : buildList(context));
  }

  Widget buildList(BuildContext context) {
    return ListView.separated(
        padding: EdgeInsets.all(10.px),
        itemBuilder: (ctx, index) {
          final item = data[index];
          return Card(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6.px)),
            elevation: 4,
            shadowColor: Color.fromRGBO(69, 91, 99, 0.08),
            margin: EdgeInsets.zero,
            child: InkWell(
              onTap: () => click(context, item),
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(20.px, 28.px, 15.px, 28.px),
                    child: Image.network(
                      item.img ?? "assets/images/icon_default.png",
                      width: 78.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,
                          ),
                          SizedBox(
                            height: 8.px,
                          ),
                          Text(
                            "标识码  ${item.qrCode}",
                            style: Theme.of(context)
                                .textTheme
                                .headline6
                                .copyWith(color: Color(0xFF666666)),
                          ),
                          SizedBox(
                            height: 3.px,
                          ),
                          Text(
                            "${item.brand}",
                            style: Theme.of(context)
                                .textTheme
                                .headline6
                                .copyWith(color: Color(0xFF666666)),
                          ),
                          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 click(context, EquipmentSecondModel item) {
    getEquipmentDel(context, item.qrCode);
  }

//装备详情查询跳转
  void 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('请重新选择');
      });
    });
  }
}
