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/consts/route_category_front_component_const.dart';
import 'package:base/model/route_model.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/app_theme.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:base/utils/request.dart';
import 'package:base/widgets/add_count_dialog.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/fire_agent_end_drawer.dart';
import 'package:base/widgets/tabbar_button.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/extinguish_agent_model.dart';
import '../../model/fire_agent_classification_model.dart';
import '../../routes/routes.dart';

// 灭火药剂添加列表页面
// 灭火药剂损耗页面

GlobalKey<_CommonAddFireAgentContentState> childKey = GlobalKey();

class CommonAddFireAgent extends StatelessWidget {
  final RouteModel routeModel;

  const CommonAddFireAgent({this.routeModel});

  @override
  Widget build(BuildContext context) {
    return CommonAddFireAgentContent(
      key: childKey,
      routeModel: routeModel,
    );
  }
}

class CommonAddFireAgentContent extends StatefulWidget {
  final RouteModel routeModel;

  const CommonAddFireAgentContent({Key key, this.routeModel}) : super(key: key);

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

class _CommonAddFireAgentContentState extends State<CommonAddFireAgentContent> {
  List _addItems = [];
  List agents = [];
  bool hasError = false;
  bool isEmpty = false;
  String category;
  String item;
  // 分类code
  String classificationCode;
  // 分类名
  String classificationName;
  String theme = '';

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

  @override
  void initState() {
    super.initState();
    initThemeConfig();
    category = widget.routeModel.category;
    item = widget.routeModel.item;

    // 损耗
    if (item == RouteItemFrontComponentConst.extinguishWastage) {
      final params = {
        'pageNum': 0,
        'carId': "${widget.routeModel.extension["carId"]}"
      };
      // 获取列表
      getExtinguishAgent(params, '');
    } else if (item == RouteItemFrontComponentConst.scraped) {}
  }

  // 设置条件名称
  void setClassificationName(String name) {
    setState(() {
      classificationName = name;
    });
  }

  // 获取灭火药剂列表
  void getExtinguishAgent(Map<String, dynamic> params, String code) {
    setState(() {
      agents = [];
      isEmpty = false;
    });

    HttpRequest.getExtinguishAgent(params: params, code: code).then((res) {
      if (res['status'] == 200) {
        List list = res['result']['records'];
        List<ExtinguishAgentModel> data = [];
        for (final item in list) {
          item['amount'] = double.parse(item['amount']);
          data.add(ExtinguishAgentModel.fromJson(item));
        }
        hasError = false;
        agents = list;
        if (list.isEmpty) {
          isEmpty = true;
        }
        setState(() {});
      } else {
        setState(() {
          hasError = true;
        });
      }
    }).catchError((e) {
      setState(() {
        hasError = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            '${widget.routeModel.title}',
            style: const TextStyle(color: Colors.white),
          ),
          elevation: 0,
          leading: LeadingButton(
            theme: theme,
            onWillScope: true,
            onWillPop: () {
              Navigator.of(context).pop();
            },
          ),
          actions: <Widget>[Container()],
          centerTitle: true,
        ),
        endDrawerEnableOpenDragGesture: false,
        endDrawer: Builder(
          builder: (ctx) {
            return FireAgentEndDrawer(
              theme: theme,
              category:
                  Provider.of<WarehouseInfoViewModel>(context, listen: false)
                      .warehouseInfoModel
                      ?.dictionaries,
              click: (FireAgentClassificationModel e) {
                childKey.currentState.setClassificationName(e.name);
                Navigator.of(ctx).pop();
                final params = {
                  'pageNum': 0,
                  'carId': "${widget.routeModel.extension["carId"]}"
                };
                childKey.currentState.getExtinguishAgent(params, e.code);
              },
            );
          },
        ),
        body:
        agents.isEmpty
            ? const Center(
                child: CircularProgressIndicator(),
              )
            :
            Stack(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(bottom: 48.px),
                    child: Column(
                      children: <Widget>[
                        buildTopBar(context),
                        buildListContext(context)
                      ],
                    ),
                  ),
                  buildBottomBar(context)
                ],
              ));
  }

  // 列表内容
  Widget buildListContext(context) {
    return Expanded(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 8.px, vertical: 10.px),
        child: ListView.separated(
            itemBuilder: (ctx, index) {
              ExtinguishAgentModel item = ExtinguishAgentModel.fromJson(agents[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: Row(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.fromLTRB(20.px, 20.px, 28.px, 10.px),
                      child: FadeInImage.assetNetwork(
                        placeholder: 'assets/images/equip_cap.png',
                        width: 60.px,
                        height: 60.px,
                        image: '${item.img}',
                        placeholderErrorBuilder: (ctx, error, stack) {
                          return Container();
                        },
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.symmetric(vertical: 10.px),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              '${item.equipmentName}',
                              style: Theme.of(context)
                                  .textTheme
                                  .headline6
                                  .copyWith(fontSize: 20.px),
                            ),
                            SizedBox(
                              height: 10.px,
                            ),
                            RichText(
                              text: TextSpan(
                                  text: '上次统计车载量',
                                  style: Theme.of(context)
                                      .textTheme
                                      .headline6
                                      .copyWith(fontSize: 16.px,fontWeight: FontWeight.w100),
                                  children: [
                                    const WidgetSpan(
                                        child: SizedBox(
                                      width: 10,
                                    )),
                                    TextSpan(
                                        text: '${item.amount}',
                                        style: Theme.of(context)
                                            .textTheme
                                            .headline6
                                            .copyWith(fontSize: 16.px)),
                                    const WidgetSpan(
                                        child: SizedBox(
                                      width: 10,
                                    )),
                                    TextSpan(
                                        text: '${item.unitName}',
                                        style: Theme.of(context)
                                            .textTheme
                                            .headline6
                                            .copyWith(
                                            fontSize: 16.px,fontWeight: FontWeight.w100))
                                  ]),
                            ),
                            SizedBox(
                              height: 8.px,
                            ),
                          ],
                        ),
                      ),
                    ),
                    IconButton(
                      icon: Icon(Icons.add),
                      color:Color.fromRGBO(50, 89, 206, 1),
                      onPressed:() => addWaste(context, item)
                    )
                    // SvgButton(
                    //   onTap: () => addWaste(context, item),
                    //   src: 'assets/images/icon_add_count.svg',
                    //   imageSize: 20,
                    //   size: 70,
                    // )
                  ],
                ),
              );
            },
            separatorBuilder: (ctx, index) {
              return SizedBox(
                height: 10.px,
              );
            },
            itemCount: agents.length),
      ),
    );
  }

  Widget buildTopBar(context) {
    return Container(
      color: Colors.white,
      child: Center(
          child: TopBarButton(
        name: "${classificationName ?? "全部"}",
        onPressed: () {
          Scaffold.of(context).openEndDrawer();
        },
      )),
    );
  }

  Widget buildBottomBar(context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 48.px,
        color: GetConfig.getColor(theme),
        padding: EdgeInsets.only(left: 16.px, right: 5.px),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              '已添加:  ${_addItems.length}',
              style: Theme.of(context).textTheme.headline6.copyWith(
                  color: Colors.white),
            ),
            FlatButton(
              padding: EdgeInsets.zero,
              onPressed: () => check(context),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "查看",
                    style: Theme.of(context).textTheme.headline6.copyWith(
                        color: Colors.white)
                  ),
                  Icon(
                    Icons.keyboard_arrow_right,
                    color: Colors.white,
                    size: 30.px,
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  // 查看
  void check(BuildContext context) {
    final params = {
      "title": "损耗",
      "category": RouteCategoryFrontComponentConst.fireExtinguishingAgent,
      "item": "extinguishWastage",
      "extension": json.encode({"extension": _addItems})
    };

    Application.navigateToPath(context, Routes.addFireAgentConfirm,
            params: params)
        .then((value) {
      setState(() {
        if (value != null) {
          _addItems = value;
        } else {
          _addItems = [];
        }
      });
    });
  }

  // 添加损耗
  void addWaste(BuildContext context, ExtinguishAgentModel item) {
    showDialog(
        context: context,
        builder: (ctx) {
          return AddCountDialog(
            theme: theme,
            title: '输入现车载量',
            callback: (value) {
              if (double.parse(value) > item.amount) {
                FlutterToast.toastCenter('损耗量不能大于车载量!');
                return;
              }

              if (!isExistItems(item.equipmentDetailId)) {
                FlutterToast.toastCenter(
                    '损耗${(item.amount - double.parse(value)).toStringAsFixed(1)}吨');
                final addItem = {
                  'amount': value,
                  'equipmentDetailId': item.equipmentDetailId,
                  'model': item.toJson()
                };
                _addItems.add(addItem);
                setState(() {});
              } else {
                FlutterToast.toastCenter('已存在添加列表中!');
              }
            },
          );
        });
  }

  // 判断是否存在列表中
  bool isExistItems(id) {
    if (_addItems.isEmpty) return false;

    bool isExists = false;
    _addItems.forEach((element) {
      if (element['equipmentDetailId'] == id) {
        isExists = true;
      }
    });
    return isExists;
  }
}
