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

import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/consts/route_category_front_component_const.dart';
import 'package:base/model/warehouse_info_view_model.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/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';
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 '../model/car_status_model.dart';
import '../model/equipment_type_count_model.dart';
import '../model/vehicle_type_count_model.dart';
import '../routes/routes.dart';

GlobalKey<_EquipmentInfoContentState> childKey = GlobalKey();

class VehicleInfo extends StatefulWidget {
  final Map params;

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

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

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

  CarStatusModel _model;
  String _brand;

  String _standard;
  String theme = '';

  Future<void> initThemeConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    initThemeConfig();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFEFEFEF),
      appBar: AppBar(
        titleSpacing: 0,
        automaticallyImplyLeading: false,
        title: const Text(
          '装备查询',
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        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);
            },
          ),
        ],
      ),
      endDrawer: getDrawer(type),
      body: VehicleInfoContent(
        EquipmentTypeCountModel.fromJson(widget.params),
        theme,
        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;
  final String theme;

  const VehicleInfoContent(this.model, this.theme, {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;

  @override
  void initState() {
    super.initState();
    erCode = widget.model.ercode;
    orgCode = Provider.of<WarehouseInfoViewModel>(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 (final json in result) {
          items.add(VehicleTypeCountModel.fromJson(json));
        }
        setState(() {
          data = items;
        });
        if (items.isEmpty) {
          setState(() {
            isEmpty = true;
          });
        }
      }
    }).catchError((err) {
      print(err);
    });
  }

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

  Widget buildTopBar(context) {
    return Container(
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          TopBarButton(name: "${_status ?? "状态"}", onPressed: () => statusClick(context)),
          TopBarButton(
            name: "${_brand ?? "品牌"}",
            onPressed: () => brandClick(context),
          ),
          TopBarButton(name: "${_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: const 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: item.equipment.img == null
                            ? Image.asset(
                                'assets/images/icon_default.png',
                                package: ExternalAssetsPackageKey.BASE,
                                width: 78.px,
                              )
                            : Image.network(
                                item.equipment.img,
                                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,
                                  ),
                                  Container(
                                    padding: EdgeInsets.symmetric(horizontal: 3.px),
                                    decoration: BoxDecoration(
                                      color: const Color(0xFF17baa0),
                                      borderRadius: BorderRadius.circular(3.px),
                                    ),
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: <Widget>[
                                        const 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: const TextStyle(color: Colors.white),
                                          ),
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              ),
                              SizedBox(
                                height: 8.px,
                              ),
                              Text(
                                '${item.carNum}',
                                style: Theme.of(context).textTheme.headline6.copyWith(color: const Color(0xFF666666)),
                              ),
                              SizedBox(
                                height: 3.px,
                              ),
                              Text(
                                '${item.brand}',
                                style: Theme.of(context).textTheme.headline6.copyWith(color: const Color(0xFF666666)),
                              ),
                              SizedBox(
                                height: 5.px,
                              ),
                              RichText(
                                text: TextSpan(text: '数量', style: const TextStyle(color: Color(0xFF666666)), children: [
                                  WidgetSpan(
                                      child: SizedBox(
                                    width: 15.px,
                                  )),
                                  TextSpan(text: '1${item.unitName}', 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 click(context, VehicleTypeCountModel item) {
    getCarDel(context, item.id);
  }

//车辆详情查询跳转
  Future<void> getCarDel(BuildContext context, String carid) async {
    Future.delayed(Duration.zero, () {
      HttpRequest.getCarDel(carid).then((res) {
        if (res['status'] == 200) {
          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((_) {
        FlutterToast.toastCenter('请重新选择');
      });
    });
  }
}
