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/external_assets_package_key.dart';
import 'package:base/consts/route_category_front_component_const.dart';
import 'package:base/consts/toast_message.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/utils/request.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/dialog/select_reason.dart';
import 'package:base/widgets/loading_dialog.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../routes/routes.dart';

GlobalKey<_EquipmentAddListContentState> childKey = GlobalKey();

class AddFireAgentConfirm extends StatelessWidget {
  final RouteModel routeModel;

  AddFireAgentConfirm({this.routeModel});

  @override
  Widget build(BuildContext context) {
    // return Scaffold(
    //   backgroundColor: AppTheme.backgroundColor,
    //   appBar: AppBar(
    //     title: Text("${routeModel.title}",style: TextStyle(color: Colors.black),),
    //     leading: LeadingButton(
    //       theme:childKey.currentState.theme,
    //       onWillScope: true,
    //       onWillPop: (){
    //          Navigator.of(context).pop(childKey.currentState.getAddItems());
    //       },
    //     ),
    //     centerTitle: true,
    //   ),
    //   body:
    return AddFireAgentConfirmContent(
      key: childKey,
      routeModel: routeModel,
    );
  }
}

class AddFireAgentConfirmContent extends StatefulWidget {
  final RouteModel routeModel;

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

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

class _EquipmentAddListContentState extends State<AddFireAgentConfirmContent> {
  List _addItems = [];
  String category;
  String item;

  String position;
  String theme = '';

  List getAddItems() {
    return _addItems;
  }

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

    position = widget.routeModel.extension["position"];
    _addItems.addAll(widget.routeModel.extension["extension"]);
    initThemeConfig();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            "${widget.routeModel.title}",
            style: TextStyle(color: Colors.white),
          ),
          leading: LeadingButton(
            theme: theme,
            onWillScope: true,
            onWillPop: () {
              Navigator.of(context).pop(childKey.currentState.getAddItems());
            },
          ),
          centerTitle: true,
        ),
        body: Stack(
          children: <Widget>[buildEquipList(context), buildBottom(context)],
        ));
  }

  // 顶部导航条
  Widget buildTopBar(context) {
    return Align(
      alignment: Alignment.topCenter,
      child: Container(
        height: 40.px,
        color: Colors.white,
        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: () => continueAdd(context),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "继续添加",
                    style: Theme.of(context).textTheme.headline6,
                  ),
                  Icon(
                    Icons.keyboard_arrow_right,
                    color: GetConfig.getColor(theme),
                    size: 30.px,
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  // 底部按钮
  Widget buildBottom(context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 48.px,
        width: double.infinity,
        child: RaisedButton(
          color: GetConfig.getColor(theme),
          child: Text(
            "提交",
            style: Theme.of(context).textTheme.headline6.copyWith(
                color: Colors.white),
          ),
          onPressed: () => submit(context),
        ),
      ),
    );
  }

  // 装备列表
  Widget buildEquipList(context) {
    return Column(
      children: <Widget>[
        buildTopBar(context),
        Expanded(
          child: ListView.builder(
              padding: EdgeInsets.only(bottom: 48.px, left: 5.px, right: 5.px, top: 5.px),
              itemCount: _addItems.length,
              itemBuilder: (ctx, index) {
                final it = _addItems[index];
                return buildContentCard(it);
              }),
        ),
      ],
    );
  }

  // 选择不同的展示列表Card
  Widget buildContentCard(it) {
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.inStock) {
      return FireAgentAddCard(
        item: it,
        position: position,
        deleteConfirm: (item) {
          print(item);
          int index = _addItems.indexOf(item);
          _addItems.removeAt(index);
          setState(() {});
        },
      );
    } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.extinguishWastage) {
      return WasteFireAgentCard(
          item: it,
          deleteConfirm: (item) {
            print(item);
            int index = _addItems.indexOf(item);
            _addItems.removeAt(index);
            setState(() {});
          });
    } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.extinguishLoad) {
      return LoadCard(
          item: it,
          deleteConfirm: (item) {
            print(item);
            int index = _addItems.indexOf(item);
            _addItems.removeAt(index);
            setState(() {});
          });
    } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.scraped) {
      return ScrapCard(
        theme: theme,
        item: it,
        deleteConfirm: (item) {
          print(item);
          int index = _addItems.indexOf(item);
          _addItems.removeAt(index);
          setState(() {});
        },
        selectReasonCallBack: () {
          setState(() {});
        },
      );
    } else {
      return Container();
    }
  }

  // 继续添加
  void continueAdd(context) {
    Navigator.of(context).pop(_addItems);
  }

  // 提交
  void submit(context) {
    if (_addItems.length == 0) {
      FlutterToast.toastCenter(ToastMessage.listEmpty);
      return;
    }

    String _description = widget.routeModel.extension["description"];

    // 灭火药剂入账
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (item == RouteItemFrontComponentConst.inStock) {
        List params = [];
        for (var item in _addItems) {
          params.add({
            "amount": item["amount"],
            "equipmentDetailId": item["equipmentDetailId"],
            "warehouseId": item["warehouseId"],
            "warehouseStructureId": item["warehouseStructureId"],
            "description": _description
          });
        }
        showDialog(
            context: context,
            builder: (ctx) {
              return LoadingDialog(
                barrierDismissible: true,
              );
            });
        HttpRequest.fireAgentInStock(params: params).then((res) {
          Navigator.of(context).pop();
          if (res["status"] == 200) {
            final result = res["result"];
            final param = {"title": "入账", "category": category, "item": item, "extension": json.encode(result)};
            Application.navigateToPath(context, Routes.submitSuccess, params: param);
          }
        }).catchError((err) {
          Navigator.of(context).pop();
        });
      } else if (item == RouteItemFrontComponentConst.extinguishWastage) {
        List params = [];
        for (var item in _addItems) {
          params.add({
            "amount": double.parse(item["amount"]),
            "equipmentDetailId": item["equipmentDetailId"],
            "total": item["model"]["amount"]
          });
        }
        showDialog(
            context: context,
            builder: (ctx) {
              return LoadingDialog(
                barrierDismissible: true,
              );
            });
        String carId = _addItems[0]["model"]["car_id"];
        print(_addItems);
        HttpRequest.lossExtinguishantsSubmit(carId, params: params).then((res) {
          Navigator.of(context).pop();
          if (res["status"] == 200) {
            final result = res["result"];
            final param = {"title": "损耗", "category": category, "item": item, "extension": json.encode(result)};
            Application.navigateToPath(context, Routes.submitSuccess, params: param);
          }
        }).catchError((err) {
          Navigator.of(context).pop();
        });
      } else if (item == RouteItemFrontComponentConst.extinguishLoad) {
        List params = [];
        for (var item in _addItems) {
          params.add({"amount": double.parse(item["amount"]), "stockDetailId": item["equipmentDetailId"]});
        }
        showDialog(
            context: context,
            builder: (ctx) {
              return LoadingDialog(
                barrierDismissible: true,
              );
            });
        String carId = _addItems[0]["car_id"];
        print(_addItems);
        HttpRequest.loadingExtinguishantSubmit(carId, params: params).then((res) {
          Navigator.of(context).pop();
          if (res["status"] == 200) {
            final result = res["result"];
            final param = {"title": "装载", "category": category, "item": item, "extension": json.encode(result)};
            Application.navigateToPath(context, Routes.submitSuccess, params: param);
          }
        }).catchError((err) {
          Navigator.of(context).pop();
        });
      } else if (item == RouteItemFrontComponentConst.scraped) {
        // 报废
        List params = [];
        bool hasReason = true;
        for (var item in _addItems) {
          if (item["reason"] == null) {
            hasReason = false;
            break;
          }
          params.add({
            "amount": double.parse(item["amount"]),
            "stockDetailId": item["equipmentDetailId"],
            "reason": item["reason"]
          });
        }

        if (!hasReason) {
          FlutterToast.toastCenter("请选择原因!");
          return;
        }

        showDialog(
            context: context,
            builder: (ctx) {
              return LoadingDialog(
                barrierDismissible: true,
              );
            });
        HttpRequest.createScrapSubmit(params: params).then((res) {
          Navigator.of(context).pop();
          if (res["status"] == 200) {
            final result = res["result"];
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              "extension": json.encode(result)
            };
            Application.navigateToPath(context, Routes.scrapPostBill, params: param);
          }
        }).catchError((err) {
          Navigator.of(context).pop();
        });
      }
    }
  }
}

// 灭火药剂入账展示
class FireAgentAddCard extends StatelessWidget {
  final item;
  final ValueChanged<Map> deleteConfirm;
  final String position;

  FireAgentAddCard({this.item, this.deleteConfirm, this.position});

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: const Color(0xFF455b63).withOpacity(0.08),
      child: Stack(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: item['model']['img'] == null
                    ? Image.asset(
                        'assets/images/equip_cap.png',
                        package: ExternalAssetsPackageKey.BASE,
                        width: 70.px,
                      )
                    : Image.network(
                        item['model']['img'],
                        width: 70.px,
                      ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text("${item["model"]["equipmentDetail"]["name"]}",
                        style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 17.px)),
                    SizedBox(
                      height: 5.px,
                    ),
                    Text(
                      "入库数量: ${item["amount"]}" + item["model"]['equipmentDetail']["unitName"] ?? '吨',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    Text(
                      "库存:   ${item["model"]["amount"]}" + item["model"]['equipmentDetail']["unitName"] ?? '吨',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                    ),
                    //Text("批次:   ${item["model"]["batchNum"]}",style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),),
                    SizedBox(
                      height: 5.px,
                    ),
                    position != null
                        ? Text(
                            "位置:   $position",
                            style: Theme.of(context).textTheme.headline3.copyWith(fontSize: 13.px),
                          )
                        : Container(),
                    SizedBox(
                      height: 10.px,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child: IconButton(
                icon: Icon(Icons.delete),
                color: Colors.redAccent,
                onPressed:(){
                  if (deleteConfirm != null) {
                    deleteConfirm(item);
                  }
                }
            )
          )
        ],
      ),
    );
  }
}

// 损耗展示列表
class WasteFireAgentCard extends StatelessWidget {
  final item;
  final ValueChanged<Map> deleteConfirm;

  WasteFireAgentCard({this.item, this.deleteConfirm});

  @override
  Widget build(BuildContext context) {
    print(item);
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: Color(0xFF455b63).withOpacity(0.08),
      child: Stack(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: item['model']['img'] == null
                    ? Image.asset(
                        'assets/images/equip_cap.png',
                        package: ExternalAssetsPackageKey.BASE,
                        width: 70.px,
                      )
                    : Image.network(
                        item['model']['img'],
                        width: 70.px,
                      ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text("${item["model"]["equipmentName"]}",
                        style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 17.px)),
                    SizedBox(
                      height: 5.px,
                    ),
                    // Row(
                    //   children: <Widget>[
                    Text(
                      "原有存量: ${item["model"]["amount"]}" + item["model"]["unitName"] ?? '吨',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    Text(
                      "现有存量: ${item["amount"]}" + item["model"]["unitName"] ?? '吨',
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                    ),
                    //   ],
                    // ),
                    Text(
                      "损耗量:  ${(item["model"]["amount"] - double.parse(item["amount"]) as double).toStringAsFixed(1)}${item["model"]["unitName"]}",
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                    ),
                    SizedBox(
                      height: 10.px,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child: IconButton(
              icon: Icon(Icons.delete),
              color: Colors.redAccent,
              onPressed:(){
                if (deleteConfirm != null) {
                deleteConfirm(item);
                }
              }
            ),
          )
        ],
      ),
    );
  }
}

// 报废
class ScrapCard extends StatelessWidget {
  final item;
  final ValueChanged<Map> deleteConfirm;
  final Function selectReasonCallBack;
  final String theme;

  ScrapCard({this.item, this.deleteConfirm, this.selectReasonCallBack, this.theme});

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: Color(0xFF455b63).withOpacity(0.08),
      child: Stack(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: item['model']['img'] == null
                    ? Image.asset(
                        "assets/images/equip_cap.png",
                        package: ExternalAssetsPackageKey.BASE,
                        width: 70.px,
                      )
                    : Image.network(
                        item['model']['img'],
                        width: 70.px,
                      ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text("${item["model"]["equipmentDetail"]["name"]}",
                        style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 16.px)),
                    SizedBox(
                      height: 5.px,
                    ),
                    // Row(
                    //   children: <Widget>[
                    Text(
                      "报废数量: ${item["amount"]}" + (item["model"]["equipmentDetail"]["unitName"] ?? '吨'),
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    Text(
                      "库存:   ${item["model"]["amount"]}" + (item["model"]["equipmentDetail"]["unitName"] ?? '吨'),
                      style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
                    ),
                    //   ],
                    // ),
                    //Text("批次:"+ item["model"]["batchNum"]==null?" ":item["model"]["batchNum"],style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),),
                    SizedBox(
                      height: 10.px,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "报废原因:",
                          style: Theme.of(context).textTheme.headline6.copyWith(fontSize: 13.px),
                        ),
                        InkWell(
                          onTap: () => selectReason(context, item, theme),
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: 140.px,
                                child: Text(
                                  "${item["reason"] ?? ""}",
                                  textAlign: TextAlign.end,
                                  style: Theme.of(context).textTheme.headline6,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              const Icon(
                                Icons.keyboard_arrow_right,
                                size: 30,
                                color: Color(0xFF999999),
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 12.px,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child: IconButton(
                icon: Icon(Icons.delete),
                color: Colors.redAccent,
                onPressed:(){
                  if (deleteConfirm != null) {
                    deleteConfirm(item);
                  }
                }
            ),
          )
        ],
      ),
    );
  }

  void selectReason(BuildContext context, Map it, String theme) {
    showModalBottomSheet(
        enableDrag: false,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.px)),
        context: context,
        builder: (BuildContext context) {
          return SelectReasonDialog(
            theme: theme,
            callback: (str) {
              it["reason"] = str;
              selectReasonCallBack();
            },
          );
        });
  }
}

// 装载
class LoadCard extends StatelessWidget {
  final item;
  final ValueChanged<Map> deleteConfirm;

  LoadCard({this.item, this.deleteConfirm});

  @override
  Widget build(BuildContext context) {
    print(item);
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: Color(0xFF455b63).withOpacity(0.08),
      child: Stack(
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: item['model']['img'] == null
                    ? Image.asset(
                        "assets/images/equip_cap.png",
                        package: ExternalAssetsPackageKey.BASE,
                        width: 70.px,
                      )
                    : Image.network(
                        item['model']['img'],
                        width: 70.px,
                      ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text("${item["model"]["equipmentDetail"]["name"]}",
                        style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 16.px)),
                    SizedBox(
                      height: 5.px,
                    ),
                    Row(
                      children: <Widget>[
                        Text(
                          // "库存: ${item["model"]["amount"]}" + (item["model"]['equipmentDetail']["unitName"]??'0') ?? '吨',
                          "库存: ${item["model"]["amount"]} 吨",
                          style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                        ),
                        Text(
                          // "  装载数量:   ${item["amount"]}" + (item["model"]['equipmentDetail']["unitName"]??'0') ?? '吨',
                          "  装载数量:   ${item["amount"]} 吨" ,
                          style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),
                        ),
                      ],
                    ),
                    //Text("批次:"+   item["model"]["batchNum"]==null?" ":item["model"]["batchNum"],style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 14.px),),
                    SizedBox(
                      height: 10.px,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child:
            IconButton(
              icon: Icon(Icons.delete),
              color: Colors.redAccent,
              onPressed: () {
                if (deleteConfirm != null) {
                      deleteConfirm(item);
                    }
              },
            )
          )
        ],
      ),
    );
  }
}
