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/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/widgets/add_count_dialog.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/tabbar_button.dart';
import 'package:equipment_manage/model/extinguish_agent_model.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../routes/routes.dart';
import '../services/offline_plan_inspection_services.dart';

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

GlobalKey<_CommonAddFireAgentContentState> childKey = GlobalKey();

class OfflineCommonAddFireAgent extends StatelessWidget {
  final RouteModel routeModel;
  const OfflineCommonAddFireAgent({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 = true;
  bool isEmpty = false;
  String category;
  String item;
  // 分类code
  String classificationCode;
  // 分类名
  String classificationName;
  String theme = '';

  Future<void> 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;
    });
  }

  // 获取灭火药剂列表
  Future<void> getExtinguishAgent(Map<String, dynamic> params, String code) async {
    setState(() {
      agents = [];
      isEmpty = false;
    });
    await getOfflineAgentshList(params['carId']).then((value) {
      setState(() {
        hasError = false;
        agents = value;
      });
      if (value.isEmpty) {
        setState(() {
          isEmpty = true;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            '${widget.routeModel.title}',
            style: const TextStyle(color: Colors.black),
          ),
          elevation: 0,
          leading: LeadingButton(
            theme: theme,
            onWillScope: true,
            onWillPop: () {
              Navigator.of(context).pop();
            },
          ),
          actions: <Widget>[Container()],
          centerTitle: true,
        ),
        body: agents.isEmpty
            ? Container()
            : 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 = 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/defule.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.headline4.copyWith(fontSize: 16.px),
                            ),
                            SizedBox(
                              height: 10.px,
                            ),
                            RichText(
                              text: TextSpan(
                                  text: '上次统计车载量',
                                  style: Theme.of(context).textTheme.headline6.copyWith(fontWeight: FontWeight.w100),
                                  children: [
                                    const WidgetSpan(
                                        child: SizedBox(
                                      width: 10,
                                    )),
                                    TextSpan(text: '${item.amount}', style: Theme.of(context).textTheme.headline4),
                                    const WidgetSpan(
                                        child: SizedBox(
                                      width: 10,
                                    )),
                                    TextSpan(
                                        text: '${item.unitName}',
                                        style:
                                            Theme.of(context).textTheme.headline6.copyWith(fontWeight: FontWeight.w100))
                                  ]),
                            ),
                            SizedBox(
                              height: 8.px,
                            ),
                          ],
                        ),
                      ),
                    ),
                    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,
            ),
            FlatButton(
              padding: EdgeInsets.zero,
              onPressed: () => check(context),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '查看',
                    style: Theme.of(context).textTheme.headline2,
                  ),
                  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.offlineAddFireAgentConfirm, 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;
  }
}
