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

import 'package:base/consts/color.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg_provider/flutter_svg_provider.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:base/consts/route_category_front_component_const.dart';
import 'package:equipment_manage/model/car_status_model.dart';
import 'package:equipment_manage/model/equipment_type_count_model.dart';
import 'package:equipment_manage/model/vehicle_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/model/warehouse_info_view_model.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/drawer/brand_drawer.dart';
import 'package:base/widgets/drawer/standard_drawer.dart';
import 'package:base/widgets/drawer/status_drawer.dart';
import 'package:base/widgets/tabbar_button.dart';

GlobalKey<_EquipmentInfoContentState> childKey = GlobalKey();

class VehicleInfo extends StatefulWidget {
  final Map params;

  VehicleInfo({@required this.params});

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

class _VehicleInfoState extends State<VehicleInfo> {
  int type = 0;

  CarStatusModel _model;
  String _brand;

  String _standard;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initThemeConfig();
  }

  String theme = '';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFEFEFEF),
      appBar: AppBar(
        titleSpacing: 0,
        automaticallyImplyLeading: false,
        title: Text(
          '装备查询',
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        // SearchBar(
        //   title: "查询装备",
        //   onTap: (){
        //     Application.navigateTo(context, Routes.commonSearchList);
        //   },
        // ),
        leading: LeadingButton(
          theme: childKey.currentState.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);
            },
          ),
        ],
      ),
      endDrawer: getDrawer(type),
      body: VehicleInfoContent(
        EquipmentTypeCountModel.fromJson(widget.params),
        callback: (i) {
          setState(() {
            type = i;
          });
        },
        key: childKey,
      ),
    );
  }

  Widget getDrawer(int type) {
    if (type == 0) {
      return StatusDrawer(
        type: "car",
        confirm: (CarStatusModel model) {
          _model = model;
          queryCarList();
          setSelectStatus();
        },
        reset: () {
          _model = null;
          setSelectStatus();
          queryCarList();
        },
      );
    } else if (type == 1) {
      return BrandDrawer(
        type: "car",
        confirm: (res) {
          _brand = res;
          queryCarList();
          setSelectStatus();
        },
        reset: () {
          _brand = null;
          setSelectStatus();
          queryCarList();
        },
      );
    } else {
      return StandardDrawer(
        type: "car",
        confirm: (res) {
          _standard = res;
          queryCarList();
          setSelectStatus();
        },
        reset: () {
          _standard = null;
          setSelectStatus();
          queryCarList();
        },
      );
    }
  }

  void queryCarList() {
    childKey.currentState.queryCarList(
        brand: _brand, carStateId: _model?.code ?? "", model: _standard);
  }

  void setSelectStatus() {
    childKey.currentState.setSelectStatus(
        standard: _standard, carState: _model?.name, brand: _brand);
  }
}

class VehicleInfoContent extends StatefulWidget {
  final EquipmentTypeCountModel model;
  final ValueChanged<int> callback;

  VehicleInfoContent(this.model, {Key key, this.callback}) : super(key: key);

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

class _EquipmentInfoContentState extends State<VehicleInfoContent> {
  String erCode;
  String orgCode;
  List<VehicleTypeCountModel> data = [];
  bool isEmpty = false;

  String _brand;
  String _status;
  String _standard;
  String theme = '';

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

  @override
  void initState() {
    super.initState();
    initThemeConfig();
    erCode = widget.model.ercode;
    orgCode = Provider.of<WarehouseInfoViewModel>(this.context, listen: false)
        .warehouseInfoModel
        ?.warehouse
        ?.orgCode;

    queryCarList();
  }

  // 设置标题选择状态
  void setSelectStatus({String brand, String carState, String standard}) {
    _brand = brand;
    _standard = standard;
    _status = carState;
    setState(() {});
  }

  // 查询三级分类车辆列表
  void queryCarList(
      {String brand = "", String carStateId = "", String model = ""}) {
    setState(() {
      isEmpty = false;
      data = [];
    });
    HttpRequest.queryCarList(erCode,
            orgCode: orgCode,
            brand: brand,
            carStateId: carStateId,
            model: model)
        .then((res) {
      if (res["status"] == 200) {
        List result = res["result"]["records"];
        List<VehicleTypeCountModel> items = [];
        for (var json in result) {
          items.add(VehicleTypeCountModel.fromJson(json));
        }
        setState(() {
          data = items;
        });
        if (items.length == 0) {
          setState(() {
            isEmpty = true;
          });
        }
      }
    }).catchError((err) {
      print(err);
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isEmpty) {
      return Column(
        children: <Widget>[
          // buildTopBar(context),
          Expanded(
            child: Center(
              child: Text("当前数据为空"),
            ),
          )
        ],
      );
    } else if (data.length == 0) {
      return Column(
        children: <Widget>[
          //buildTopBar(context),
          Expanded(
            child: Center(
              child: CupertinoActivityIndicator(),
            ),
          )
        ],
      );
    } else {
      return Column(
        children: <Widget>[
          //buildTopBar(context),
          buildList(context)
        ],
      );
    }
  }

  Widget buildTopBar(context) {
    return Container(
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          TopBarButton(
              name: "${_status != null ? _status : "状态"}",
              onPressed: () => statusClick(context)),
          TopBarButton(
            name: "${_brand != null ? _brand : "品牌"}",
            onPressed: () => brandClick(context),
          ),
          TopBarButton(
              name: "${_standard != null ? _standard : "规格"}",
              onPressed: () => standardClick(context)),
        ],
      ),
    );
  }

  // 品牌点击
  void brandClick(context) {
    if (widget.callback != null) {
      widget.callback(1);
    }
    Scaffold.of(context).openEndDrawer();
  }

  // 状态点击
  void statusClick(context) {
    if (widget.callback != null) {
      widget.callback(0);
    }
    Scaffold.of(context).openEndDrawer();
  }

  // 规格点击
  void standardClick(context) {
    if (widget.callback != null) {
      widget.callback(2);
    }
    Scaffold.of(context).openEndDrawer();
  }

  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 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.asset(
                          "assets/images/icon_default.png",
                          width: 78.px,
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.symmetric(vertical: 16.px),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Text(
                                    "${item.equipment.name}",
                                    style:
                                        Theme.of(context).textTheme.headline4,
                                  ),
//                                SizedBox(width: 5.px,),
                                  Container(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 3.px),
                                    decoration: BoxDecoration(
                                      color: Color(0xFF17baa0),
                                      borderRadius: BorderRadius.circular(3.px),
                                    ),
                                    child: Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: <Widget>[
                                        Image(
                                          image: Svg(
                                              "assets/images/icon_status.svg",
                                              size: Size(10, 10)),
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(
                                              left: 3.px, bottom: 1.px),
                                          child: Text(
                                            "${item.carState}",
                                            style:
                                                TextStyle(color: Colors.white),
                                          ),
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              ),
                              SizedBox(
                                height: 8.px,
                              ),
                              Text(
                                "${item.carNum}",
                                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: "1",
                                          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, VehicleTypeCountModel item) {
    //   final params = {
    //     "title":"车辆详情",
    //     "category":RouteCategoryFrontComponentConst.fireFightingVehicle,
    //     "extension":json.encode({"carId":item.id})
    //   };
    //   Application.navigateToPath(context, Routes.equipCarExtinguishDetail,params: params);
    // }
    getCarDel(context, item.id);
  }

//车辆详情查询跳转
  void getCarDel(BuildContext context, String carid) async {
    Future.delayed(Duration.zero, () {
      HttpRequest.getCarDel(carid).then((res) {
        // Navigator.of(context).pop();
        // restartScanning(3);
        if (res["status"] == 200) {
          // BasicBean bean = BasicBean.fromJson(res["result"]);
          // _controller?.dispose();
          // _controller = null;
          final params = {
            "title": "车辆详情",
            "category": '3',
            "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('请重新选择');
      });
    });
  }
}
