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/services/application.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:base/utils/request.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/common_card_item.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 '../../model/equipment_type_model.dart';
import '../../routes/routes.dart';

class CategoryDetailList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CategoryDetailListContent();
  }
}

class CategoryDetailListContent extends StatefulWidget {
  @override
  _CategoryDetailListState createState() => _CategoryDetailListState();
}

class _CategoryDetailListState extends State<CategoryDetailListContent> {
  int _index = 0;

  List<EquipmentTypeModel> leftItems = [];
  List<EquipmentTypeCountModel> rightItems = [];

  // 数据是否为空
  bool isEmpty = false;

  String theme = '';

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

  @override
  void initState() {
    super.initState();
    initThemeConfig();
    HttpRequest.queryEquipmentType().then((res) {
      if (res['status'] == 200) {
        List result = res['result'];
        List<EquipmentTypeModel> items = [];
        for (final json in result) {
          items.add(EquipmentTypeModel.fromJson(json));
        }
        setState(() {
          leftItems = items;
        });
        if (items.isEmpty) return;
        // 获取默认列表
        getRightList(items[0].id);
      }
    }).catchError((err) {});
  }

  // 获取右边数据列表
  void getRightList(String id) {
    setState(() {
      rightItems = [];
      isEmpty = false;
    });

    HttpRequest.queryEquipmentTypeCount(id).then((res) {
      if (res['status'] == 200) {
        List result = res['result'];
        List<EquipmentTypeCountModel> items = [];
        for (final json in result) {
          items.add(EquipmentTypeCountModel.fromJson(json));
        }
        setState(() {
          rightItems = items;
        });
        if (result.isEmpty) {
          setState(() {
            isEmpty = true;
          });
        }
      }
    }).catchError((err) {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFFEEEEEE),
        appBar: AppBar(
          titleSpacing: 0,
          automaticallyImplyLeading: false,
          title: const 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: const EdgeInsets.only(right: 5),
              ),
              onTap: () {
                final params = {
                  'title': "查询",
                  'category': RouteCategoryFrontComponentConst.query
                };
                Application.navigateToPath(context, Routes.equipWareHousing,
                    params: params);
              },
            ),
          ],
        ),
        body: leftItems.isEmpty
            ? const Center(
                child: CupertinoActivityIndicator(),
              )
            : Row(
                children: <Widget>[
                  buildLeftBar(context),
                  buildRightList(context)
                ],
              ));
  }

  Widget buildLeftBar(context) {
    return Container(
      width: 100.px,
      color: Colors.white,
      child: ListView.builder(
          padding: EdgeInsets.only(top: 8.px, bottom: 8.px),
          itemCount: leftItems.length,
          itemBuilder: (ctx, index) {
            final item = leftItems[index];
            return InkWell(
              onTap: () {
                setState(() {
                  _index = index;
                });
                getRightList(item.id);
              },
              child: Container(
                color: index == _index ? const Color(0xFFefefef) : Colors.white,
                padding: EdgeInsets.symmetric(vertical: 10.px),
                child: Row(
                  children: <Widget>[
                    index == _index
                        ? SizedBox(
                            width: 3.px,
                            height: 30.px,
                            child: DecoratedBox(
                              decoration: ShapeDecoration(
                                  color: GetConfig.getColor(theme),
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(4))),
                            ),
                          )
                        : Container(),
                    SizedBox(
                      width: 10.px,
                    ),
                    Expanded(
                        child: Text(
                      '${item.name}',
                      style: Theme.of(context).textTheme.headline3.copyWith(
                          fontWeight: FontWeight.w600,
                          color: _index == index
                              ? GetConfig.getColor(theme)
                              : const Color(0xFF666666)),
                    )),
                    SizedBox(
                      width: 12.px,
                    )
                  ],
                ),
              ),
            );
          }),
    );
  }

  Widget buildRightList(context) {
    if (isEmpty) {
      return const Expanded(
        child: Center(
          child: Text("当前数据为空"),
        ),
      );
    } else if (rightItems.isEmpty) {
      return const Expanded(
        child: Center(
          child: CupertinoActivityIndicator(),
        ),
      );
    } else {
      return Expanded(
        child: ListView.builder(
            padding: EdgeInsets.symmetric(horizontal: 5.px, vertical: 5.px),
            itemCount: rightItems.length,
            itemBuilder: (ctx, index) {
              final item = rightItems[index];
              return CommonCardItem(
                theme: theme,
                title: item.name,
                count: '${item.amount}',
                image: Image.asset(
                  'assets/images/icon_default.png',
                  package: ExternalAssetsPackageKey.BASE,
                  width: 70.px,
                ),
                onPress: () {
                  // if(item.amount==0){
                  //   FlutterToast.toastCenter('暂无该类装备');
                  //   return;
                  // }
                  final param = {'params': json.encode(item.toJson())};
                  if (item.type == 'equipment') {
                    Application.navigateToPath(context, Routes.equipmentInfo,
                        params: param);
                  } else {
                    Application.navigateToPath(context, Routes.vehicleInfo,
                        params: param);
                  }
                },
              );
            }),
      );
    }
  }
}
