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/qr_type_consts.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/model/tree_node_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/widgets/back_button.dart';
import 'package:base/widgets/common_alert_dialog.dart';
import 'package:base/widgets/dialog/choose_position.dart';
import 'package:base/widgets/dialog/position_description_dialog.dart';
import 'package:base/widgets/quote_chip.dart';
import 'package:equipment_manage/model/car_scan_model.dart';
import 'package:equipment_manage/model/equipment_scan_model.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 '../routes/routes.dart';
import '../services/dbAccess.dart';
import '../services/offline_plan_inspection_services.dart';

class OfflineEquipmentAddList extends StatefulWidget {
  RouteModel routeModel;

  OfflineEquipmentAddList({this.routeModel});

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

// class _EquipmentAddListState extends State<OfflineEquipmentAddList> {
//   @override
//   Widget build(BuildContext context) {
//       return EquipmentAddListContent(routeModel: widget.routeModel,);
//
//   }
// }
//
//
// class EquipmentAddListContent extends StatefulWidget {
//
//   RouteModel routeModel;
//   EquipmentAddListContent({Key key,this.routeModel}):super(key:key);
//   @override
//   _EquipmentAddListContentState createState() => _EquipmentAddListContentState();
//}

class _EquipmentAddListContentState extends State<OfflineEquipmentAddList> {
  // 是否详细列表
  // 是展示合并列表
  // 否展示详细列表
  bool isDetailList = false;
  String category;
  String item;
  String reason;
  String _positionDescription = '';

  // 提交列表
  List<CarScanModel> list = [];

  List<EquipmentScanModel> list1 = [];
  List<EquipmentScanModel> list2 = [];
  List<EquipmentScanModel> list3 = [];
  TreeNodeModel model = TreeNodeModel();
  bool carLoad = false;

  // 仓库 id
  String warehouseId = '0';

  // 货位 code
  String shelfCellCode;
  String theme = '';

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

  @override
  void initState() {
    super.initState();
    initThemeConfig();
    category = widget.routeModel.category;
    item = widget.routeModel.item;
    reason = widget.routeModel.extension["reason"];

    warehouseId =
        Provider.of<WarehouseInfoViewModel>(this.context, listen: false)
            .warehouseInfoModel
            ?.warehouse
            ?.id;
    if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
      // 扫码的是装备
      if (item == RouteItemFrontComponentConst.carLoad ||
          item == RouteItemFrontComponentConst.carUnLoad) {
        carLoad = true;
        List lists = widget.routeModel.extension["extension"];
        for (var json in lists) {
          bool res = true;
          EquipmentScanModel mode = EquipmentScanModel.fromJson(json);
          EquipmentScanModel mode1 = EquipmentScanModel.fromJson(json);
// mode.amount=int.parse(mode.amount.toString());
//           mode1.amount=int.parse(mode1.amount.toString());
          list2.add(mode1);
          if (list3.length == 0) {
            list3.add(mode);
          } else {
            for (EquipmentScanModel bean in list3) {
              if (bean.equipmentId == mode.equipmentId) {
                res = false;
                bean.amount = (int.parse(bean.amount) + int.parse(mode.amount))
                    .toString();
              }
            }
            if (res) {
              list3.add(mode);
            }
          }
        }
        list1 = list3;
      } else if (item == RouteItemFrontComponentConst.maintain ||
          item == RouteItemFrontComponentConst.repair ||
          item == RouteItemFrontComponentConst.repaired ||
          item == RouteItemFrontComponentConst.scraped) {
        List lists = widget.routeModel.extension["extension"];
        for (var json in lists) {
          list.add(CarScanModel.fromJson(json));
        }
      }
    }
    // 装备
    else if (category == RouteCategoryFrontComponentConst.equipment) {
      carLoad = true;
      List lists = widget.routeModel.extension["extension"];
      for (var json in lists) {
        bool res = true;
        EquipmentScanModel mode = EquipmentScanModel.fromJson(json);
        EquipmentScanModel mode1 = EquipmentScanModel.fromJson(json);
        // if(category == RouteCategoryFrontComponentConst.equipment) {
        //   mode.amount=int.parse(mode.amount.toString());
        //   mode1.amount=int.parse(mode1.amount.toString());
        // }
        //list1.add(mode);
        list2.add(mode1);
        if (list3.length == 0) {
          list3.add(mode);
        } else {
          for (EquipmentScanModel bean in list3) {
            if (bean.equipmentId == mode.equipmentId) {
              res = false;
              bean.amount =
                  (int.parse(bean.amount) + int.parse(mode.amount)).toString();
            }
          }
          if (res) {
            list3.add(mode);
          }
        }
      }
      list1 = list3;
    } else if (category ==
        RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      carLoad = true;
      List lists = widget.routeModel.extension["extension"];
      for (var json in lists) {
        bool res = true;
        EquipmentScanModel mode = EquipmentScanModel.fromJson(json);
        EquipmentScanModel mode1 = EquipmentScanModel.fromJson(json);
        // if(category == RouteCategoryFrontComponentConst.equipment) {
        //   mode.amount=int.parse(mode.amount.toString());
        //   mode1.amount=int.parse(mode1.amount.toString());
        // }
        //list1.add(mode);
        list2.add(mode1);
        if (list3.length == 0) {
          list3.add(mode);
        } else {
          for (EquipmentScanModel bean in list3) {
            if (bean.equipmentId == mode.equipmentId) {
              res = false;
              bean.amount =
                  (double.parse(bean.amount) + double.parse(mode.amount))
                      .toString();
            }
          }
          if (res) {
            list3.add(mode);
          }
        }
      }
      list1 = list3;
    }
//     if(category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
//       // 扫码的是装备
//       if(item == RouteItemFrontComponentConst.carLoad || item == RouteItemFrontComponentConst.carUnLoad) {
//         carLoad = true;
//         List lists =  widget.routeModel.extension["extension"];
//         for(var json in lists) {
//           bool res=true;
//           EquipmentScanModel mode=EquipmentScanModel.fromJson(json);
//           EquipmentScanModel mode1=EquipmentScanModel.fromJson(json);
//           //list1.add(mode);
//           list2.add(mode1);
//           if (list3.length==0){
//             list3.add(mode);
//
//           }else {
//
//             for (EquipmentScanModel bean in list3) {
//               if(bean.equipmentId==mode.equipmentId){
//                 res=false;
//                 bean.amount=bean.amount+1;
//               }
//             }
//             if(res){
//               list3.add(mode);
//             }
//           }
//
//         }
//         list1=list3;
//
//       } else if(item == RouteItemFrontComponentConst.maintain || item == RouteItemFrontComponentConst.repair ||
//           item == RouteItemFrontComponentConst.repaired || item == RouteItemFrontComponentConst.scraped) {
//         List lists =  widget.routeModel.extension["extension"];
//         for(var json in lists) {
//           list.add(CarScanModel.fromJson(json));
//         }
//       }
//     }
//     // 装备
//     else if(category == RouteCategoryFrontComponentConst.equipment||category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
//       carLoad = true;
//       List lists =  widget.routeModel.extension["extension"];
//       for(var json in lists) {
//         bool res=true;
//         EquipmentScanModel mode=EquipmentScanModel.fromJson(json);
//         EquipmentScanModel mode1=EquipmentScanModel.fromJson(json);
//
//         list2.add(mode1);
//         if (list3.length==0){
//           list3.add(mode);
//
//         }else {
//
//           for (EquipmentScanModel bean in list3) {
// if(bean.equipmentId==mode.equipmentId){
//   res=false;
//   bean.amount=bean.amount+mode.amount;
// }
//           }
//           if(res){
//             list3.add(mode);
//           }
//         }
//
//       }
//       list1=list3;
//     }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            "${widget.routeModel?.title ?? ""}",
            style: TextStyle(color: Colors.black),
          ),
          leading: LeadingButton(
            theme: this.theme,
            onWillScope: true,
            onWillPop: () {
              bool carLoad = this.carLoad;
              if (carLoad) {
                Navigator.of(context).pop(this.list2);
              } else {
                Navigator.of(context).pop(this.list);
              }
            },
          ),
          centerTitle: true,
        ),
        body: new WillPopScope(
          child: Stack(
            children: <Widget>[buildEquipList(context), buildBottom(context)],
          ),
          onWillPop: () async {
            // return false;
            bool carLoad = this.carLoad;
            if (carLoad) {
              Navigator.of(context).pop(this.list2);
            } else {
              Navigator.of(context).pop(this.list);
            }
          },
        ));
  }

  // 顶部导航条
  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(
              "已添加: ${carLoad ? list2.length : list.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: (category ==
                  RouteCategoryFrontComponentConst.fireFightingVehicle &&
              (item == RouteItemFrontComponentConst.scraped ||
                  item == RouteItemFrontComponentConst.maintain ||
                  item == RouteItemFrontComponentConst.repair ||
                  item == RouteItemFrontComponentConst.repaired))
          ? //(item==RouteItemFrontComponentConst.carLoad||item==RouteItemFrontComponentConst.carUnLoad)?
          Container(
              height: 50.px,
              width: MediaQuery.of(context).size.width,
              child: RaisedButton(
                color: GetConfig.getColor(theme),
                child: Text(
                  "提交",
                  style: Theme.of(context).textTheme.headline2,
                ),
                onPressed: () => submit(context),
              ),
            )
          : Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    height: 50.px,
                    child: RaisedButton(
                      color: Colors.white,
                      child: !carLoad
                          ? Text(
                              "详细列表",
                              style: Theme.of(context)
                                  .textTheme
                                  .headline2
                                  .copyWith(color: Color(0xFF333333)),
                            )
                          : Text(
                              isDetailList ? "合并列表" : "详细列表",
                              style: Theme.of(context)
                                  .textTheme
                                  .headline2
                                  .copyWith(color: Color(0xFF333333)),
                            ),
                      onPressed: () => checkDetailListType(context),
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    height: 50.px,
                    child: RaisedButton(
                      color: GetConfig.getColor(theme),
                      child: Text(
                        "提交",
                        style: Theme.of(context).textTheme.headline2,
                      ),
                      onPressed: () => submit(context),
                    ),
                  ),
                )
              ],
            ),
    );
  }

  // 装备列表
  Widget buildEquipList(context) {
    if (!carLoad) {
      return Column(
        children: <Widget>[
          buildTopBar(context),
          Expanded(
            child: ListView.builder(
                padding: EdgeInsets.only(
                    bottom: 50.px, left: 10.px, right: 10.px, top: 5.px),
                itemCount: list.length,
                itemBuilder: (ctx, index) {
                  CarScanModel model = list[index];
                  return
                      //!isDetailList?
                      // AddNoDetailCard(
                      //   model: model,
                      //   index: index,
                      //   callBack: (i){
                      //     list.removeAt(i);
                      //     setState(() {
                      //
                      //     });
                      //   } ,
                      // ):
                      AddDetailCard(
                    theme: theme,
                    position: widget.routeModel.extension["position"] != null
                        ? "${widget.routeModel.extension["position"]}${widget.routeModel.extension["description"] ?? ""}"
                        : "",
                    category: category,
                    item: item,
                    model: model,
                    index: index,
                    callBack: (i) {
                      if (list1.length == 0) {
                        setState(() {
                          list.removeAt(i);
                        });
                      } else {
                        EquipmentScanModel model = list1[i];
                        list3.forEach((element) {
                          if (element.equipmentId == model.equipmentId) {
                            // if(category == RouteCategoryFrontComponentConst.fireExtinguishingAgent){
                            //   element.amount=element.amount-model.amount;
                            // }else{
                            if (category ==
                                RouteCategoryFrontComponentConst
                                    .fireExtinguishingAgent) {
                              element.amount = (double.parse(element.amount) -
                                      double.parse(model.amount))
                                  .toString();
                            } else {
                              element.amount = (int.parse(element.amount) -
                                      int.parse(model.amount))
                                  .toString();
                            }
                            //}

                          }
                        });

                        //list2.removeAt(i);
                        setState(() {
                          list2.removeAt(i);
                          list1 = list2;
                        });
                        //
                        //  list.removeAt(i);
                        //  list2.removeAt(i);
                        //
                        // // int e=0;
                        //  //list3.firstWhere((element) => false)
                        //  for( EquipmentScanModel mod in list3){
                        //    //EquipmentScanModel mod=list3[s];
                        //    if(mod.equipmentId==model.equipmentId){
                        //      mod.amount=mod.amount-1;
                        //    }
                        //    if(mod.amount==0){
                        //      list3.remove(mod);
                        //    }
                        //  }
                        //
                        //  setState(() {
                        //
                        //  });
                      }
                    },
                  );
                }),
          ),
        ],
      );
    } else {
      return Column(
        children: <Widget>[
          buildTopBar(context),
          Expanded(
            child: ListView.builder(
                padding: EdgeInsets.only(
                    bottom: 50.px, left: 10.px, right: 10.px, top: 5.px),
                itemCount: list1.length,
                itemBuilder: (ctx, index) {
                  EquipmentScanModel model = list1[index];
                  return !isDetailList
                      ? AddNoDetailCard(
                          equipModel: model,
                          index: index,
                          callBack: (i) {
                            list1.removeAt(i);
                            setState(() {});
                          },
                        )
                      : AddDetailCard(
                          theme: theme,
                          position: widget.routeModel.extension["position"] !=
                                  null
                              ? "${widget.routeModel.extension["position"]}${widget.routeModel.extension["description"] ?? ""}"
                              : "",
                          category: category,
                          item: item,
                          equipModel: model,
                          index: index,
                          callBack: (i) {
                            list1.removeAt(i);
                            list3.removeAt(i);
                            setState(() {});
                          },
                        );
                }),
          ),
        ],
      );
    }
  }

  // 显示位置描述
  void showEquipInStockDescription(BuildContext context) {
    showModalBottomSheet(
        isDismissible: false,
        enableDrag: false,
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.px)),
        context: context,
        builder: (BuildContext context) {
          return PositionDescriptionDialog(
            theme: this.theme,
            callback: (str) {
              //setState(() {
              //str.graphemeClusters.removeLast();
              _positionDescription = str;
              carUnloadSubmit(context);
              //});
            },
          );
        });
  }

  // 继续添加
  void continueAdd(context) {
    Navigator.of(context).pop(carLoad ? list2 : list);
  }

  // 提交
  void submit(context) {
    // carLoad 装备
    if (carLoad) {
      if (list2.length == 0) {
        FlutterToast.toastCenter("当前列表为空!");
        return;
      }
    } else {
      if (list.length == 0) {
        FlutterToast.toastCenter("当前列表为空!");
        return;
      }
    }

    // 车辆
    if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
      if (item == RouteItemFrontComponentConst.carLoad) {
        List equipments = [];
        for (EquipmentScanModel model in list1) {
          equipments.add({
            "qrCode": model.qrCode,
            "amount": model.amount,
            "carId": widget.routeModel.extension["carId"],
            "equipmentDetailId": model.equipmentDetailId,
            "warehouseId": warehouseId,
            "glcarId": widget.routeModel.extension["carId"],
          });
        }
        final params = {
          "warehouseId": warehouseId,
          "type": QRType.car_load,
          "equipments": equipments,
          "carId": widget.routeModel.extension["carId"],
        };
        getInStockCar(params, '21').then((value) {
          if (value) {
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              // "extension":json.encode(result)
            };
            Application.navigateToPath(context, Routes.offlineSubmitSuccess,
                params: param);
          }
        });
// getInStockEquipment(equipments, '21').then((value) {
//   if(value){
//     final param = {
//       "title":widget.routeModel.title,
//       "category":category,
//       "item": item,
//       // "extension":json.encode(result)
//     };
//     Application.navigateToPath(context, Routes.offlineSubmitSuccess,params: param);
//   }
//
// });
        // showDialog(context: context,builder: (ctx){
        //   return LoadingDialog(
        //     barrierDismissible: true,
        //   );
        // });
        // HttpRequest.loadingOrUnloadEquip(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.submitSuccess,params: param);
        //    }
        // }).catchError((err){
        //   Navigator.of(context).pop();
        // });
      } else if (item == RouteItemFrontComponentConst.carUnLoad) {
        showDialog<Null>(
            context: context, //BuildContext对象
            builder: (BuildContext ctx) {
              return CommonAlertDialog(
                theme: theme,
                onTap: () {
                  warehouseId = null;
                  shelfCellCode = null;
                  carUnloadSubmit(context);
                },
                onCancelTap: () {
                  getWarehousePosition(context);
                },
                content: "是否放回原位？",
                subtitle: "选择否的话需要重新入账",
              );
            });
      } else if (item == RouteItemFrontComponentConst.maintain) {
        List cars = [];
        for (CarScanModel model in list) {
          cars.add({"carId": model.carId});
        }
        getInStockEquipment(cars, '23').then((value) {
          if (value) {
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              // "extension":json.encode(result)
            };
            Application.navigateToPath(context, Routes.offlineSubmitSuccess,
                params: param);
          }
        });
        // showDialog(context: context,builder: (ctx){
        //   return LoadingDialog(
        //     barrierDismissible: true,
        //   );
        // });
        // HttpRequest.carMaintain(params: cars).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.submitSuccess,params: param);
        //   }
        // }).catchError((err){
        //   Navigator.of(context).pop();
        // });
      }
      // 维修
      else if (item == RouteItemFrontComponentConst.repair) {
        List cars = [];
        for (CarScanModel model in list) {
          cars.add({"carId": model.carId});
        }
        getInStockEquipment(cars, '24').then((value) {
          if (value) {
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              // "extension":json.encode(result)
            };
            Application.navigateToPath(context, Routes.offlineSubmitSuccess,
                params: param);
          }
        });
        // showDialog(context: context,builder: (ctx){
        //   return LoadingDialog(
        //     barrierDismissible: true,
        //   );
        // });
        // HttpRequest.carRepair(params: cars).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.submitSuccess,params: param);
        //   }
        // }).catchError((err){
        //   Navigator.of(context).pop();
        // });
      }
      // 维修完成
      else if (item == RouteItemFrontComponentConst.repaired) {
        List cars = [];
        for (CarScanModel model in list) {
          cars.add({"carId": model.carId});
        }
        getInStockEquipment(cars, '25').then((value) {
          if (value) {
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              // "extension":json.encode(result)
            };
            Application.navigateToPath(context, Routes.offlineSubmitSuccess,
                params: param);
          }
        });
        // showDialog(context: context,builder: (ctx){
        //   return LoadingDialog(
        //     barrierDismissible: true,
        //   );
        // });
        // HttpRequest.carRepairComplete(params: cars).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.submitSuccess,params: param);
        //   }
        // }).catchError((err){
        //   Navigator.of(context).pop();
        // });
      }
      // 报废
      else if (item == RouteItemFrontComponentConst.scraped) {
        List cars = [];
        for (CarScanModel model in list) {
          cars.add({"carId": model.carId, "reason": reason});
        }
        getInStockEquipment(cars, '26').then((value) {
          if (value) {
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              "extension":
                  json.encode({"list": json.encode(list), "reason": reason})
              // "extension":json.encode(result)
            };
            Application.navigateToPath(context, Routes.offlineScrapPostBill,
                params: param);
          }
        });
        // showDialog(context: context,builder: (ctx){
        //   return LoadingDialog(
        //     barrierDismissible: true,
        //   );
        // });
        // HttpRequest.carCreateScrap(params: cars).then((res) {
        //   Navigator.of(context).pop();
        //   if(res["status"] == 200) {
        //     final result = res["result"];
        //
        //     final extension = {
        //       "billCode":result["billCode"],
        //       "id":result["id"]
        //     };
        //
        //     final params = {
        //       "title":widget.routeModel.title,
        //       "category":category,
        //       "item": item,
        //       "extension":json.encode(extension)
        //     };
        //     Application.navigateToPath(context, Routes.scrapPostBill,params: params);
        //   }
        // }).catchError((err){
        //   Navigator.of(context).pop();
        // });
      }
    }
    // 器材
    else if (category == RouteCategoryFrontComponentConst.equipment) {
      if (item == RouteItemFrontComponentConst.inStock) {
        Map extension = widget.routeModel.extension;
        String warehouseId = extension["warehouseId"];
        String warehouseStructureId = extension["warehouseStructureId"];
        String description = extension["description"];

        List equips = [];
        for (EquipmentScanModel model in list2) {
          equips.add({
            "amount": model.amount == 0 ? 1 : model.amount,
            "equipmentDetailId": model.equipmentDetailId,
            "qrCode": model.qrCode,
            "warehouseId": warehouseId,
            "warehouseStructureId": warehouseStructureId,
            "description": description,
          });
        }
        getInStockEquipment(equips, '11').then((value) {
          if (value) {
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              // "extension":json.encode(result)
            };
            Application.navigateToPath(context, Routes.offlineSubmitSuccess,
                params: param);
          }
        });
        // showDialog(context: context,builder: (ctx){
        //   return LoadingDialog(
        //     barrierDismissible: true,
        //   );
        // });
        // HttpRequest.equipStockIn(params: equips).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.submitSuccess,params: param);
        //   }
        // }).catchError((err){
        //   Navigator.of(context).pop();
        // });
      }
      // 其他类型传参相同
      else {
        List equips = [];
        String type = '';
        if (item == RouteItemFrontComponentConst.scraped) {
          type = '15';
          for (EquipmentScanModel model in list1) {
            equips.add({
              "stockDetailId": model.stockDetailId,
              "equipmentDetailId": model.equipmentDetailId,
              "reason": widget.routeModel.extension["reason"],
              "amount": model.amount,
            });
          }
        } else {
          if (item == RouteItemFrontComponentConst.maintain) type = '12';
          if (item == RouteItemFrontComponentConst.repair) type = '13';
          if (item == RouteItemFrontComponentConst.repaired) type = '14';

          // type='12';
          for (EquipmentScanModel model in list1) {
            equips.add({
              "stockDetailId": model.stockDetailId,
              "equipmentDetailId": model.equipmentDetailId,
              "qrCode": model.qrCode,
              "amount": model.amount,
            });
          }
        }
        getInStockEquipment(equips, type).then((value) {
          if (value) {
            //final result = res["result"];
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              "extension": json.encode({
                "list": json.encode(list1),
                "reason": widget.routeModel.extension["reason"]
              })
              //"extension":json.encode(result)
            };
            // 报废跳转上传凭据页面
            if (item == RouteItemFrontComponentConst.scraped) {
              Application.navigateToPath(context, Routes.offlineScrapPostBill,
                  params: param);
            } else {
              Application.navigateToPath(context, Routes.offlineSubmitSuccess,
                  params: param);
            }
          }
        });
        // showDialog(context: context,builder: (ctx){
        //   return LoadingDialog(
        //     barrierDismissible: true,
        //   );
        // });
        //HttpRequest.equipHandle(item,params: equips).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)
        //     };
        //     // 报废跳转上传凭据页面
        //     if(item == RouteItemFrontComponentConst.scraped) {
        //        Application.navigateToPath(context, Routes.scrapPostBill,params: param);
        //     } else {
        //       Application.navigateToPath(context, Routes.submitSuccess,params: param);
        //     }
        //   }
        // }).catchError((err){
        //   Navigator.of(context).pop();
        // });

      }
    } else {
      if (item == RouteItemFrontComponentConst.inStock) {
        Map extension = widget.routeModel.extension;
        String warehouseId = extension["warehouseId"];
        String warehouseStructureId = extension["warehouseStructureId"];
        String description = extension["description"];
        List params = [];
        for (EquipmentScanModel item in list2) {
          params.add({
            "amount": item.amount,
            "equipmentDetailId": item.equipmentDetailId,
            "item": item,
            "warehouseId": warehouseId,
            "warehouseStructureId": warehouseStructureId,
            "description": description,
            "qrCode": item.qrCode
          });
        }
        getInStockEquipment(params, '31').then((value) {
          if (value) {
            final param = {
              "title": widget.routeModel.title,
              "category": category,
              "item": item,
              // "extension":json.encode(result)
            };
            Application.navigateToPath(context, Routes.offlineSubmitSuccess,
                params: param);
          }
        });
        // 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();
        // });
      }
    }
  }

  // 车辆卸载提交
  void carUnloadSubmit(context) async {
    List equipments = [];
    for (EquipmentScanModel model in list1) {
      equipments.add({
        "qrCode": model.qrCode,
        "amount": model.amount,
        //String carid=await getEquipmentOnCar(model.equipmentDetailId);
        "carId": await getEquipmentOnCar(model.equipmentDetailId),
        "equipmentDetailId": model.equipmentDetailId,
        "warehouseId": warehouseId,
        "glcarId": await getEquipmentOnCar(model.equipmentDetailId),
        "shelfCellCode": shelfCellCode,
        "area": _positionDescription
      });
    }
    final params = {
      "warehouseId": warehouseId,
      "type": QRType.car_uninstall,
      "equipments": equipments,
      "shelfCellCode": shelfCellCode,
      "carId": equipments[0]['carId'],
      "area": _positionDescription
    };
    getInStockCar(params, '22').then((value) {
      if (value) {
        final param = {
          "title": widget.routeModel.title,
          "category": category,
          "item": item,
          // "extension":json.encode(result)
        };
        Application.navigateToPath(context, Routes.offlineSubmitSuccess,
            params: param);
      }
    });
    // getInStockEquipment(equipments,'22').then((value) {
    //   if(value){
    // final param = {
    //         "title":widget.routeModel.title,
    //         "category":category,
    //         "item": item,
    //        // "extension":json.encode(result)
    //       };
    //       Application.navigateToPath(context, Routes.offlineSubmitSuccess,params: param);
    //     }
    // });
    // showDialog(context: context,builder: (ctx){
    //   return LoadingDialog(
    //     barrierDismissible: true,
    //   );
    // });
//     HttpRequest.loadingOrUnloadEquip(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.submitSuccess,params: param);
    //   }
    // }).catchError((err){
    //   Navigator.of(context).pop();
    // });
  }

  void getWarehousePosition(BuildContext context) async {
    // if(warehouseId == null) return;
    // showDialog(context: context,builder: (ctx){
    //   return LoadingDialog(
    //     barrierDismissible: true,
    //   );
    // });
    // HttpRequest.getWarehousePositionStructureTree(warehouseId).then((res) {
    //   Navigator.of(context).pop();
    // if(res["status"] == 200) {
    // List items = res["result"];
    List items = await getOfflineWarehouse();
    showModalBottomSheet(
        isDismissible: false,
        enableDrag: false,
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.px)),
        context: context,
        builder: (BuildContext ctx) {
          return ChoosePositionDialog(
            theme: this.theme,
            data: items,
            selectedModel: this.model,
            noneSelect: () {
              FlutterToast.toastCenter(ToastMessage.placePosition);
              warehouseId = null;
              carUnloadSubmit(context);
            },
            confirm: (TreeNodeModel model) {
              this.model = model;
              shelfCellCode = model.code;
              showEquipInStockDescription(context);
            },
          );
        });
    //   }
    // }).catchError((_){
    //   Navigator.of(context).pop();
    // });
  }

  void checkDetailListType(context) {
    setState(() {
      isDetailList = !isDetailList;
      if (isDetailList) {
        list1 = list2;
      } else {
        list1 = list3;
      }
    });
  }
}

class AddDetailCard extends StatelessWidget {
  String theme;
  String category;
  String item;
  String position;
  CarScanModel model;
  EquipmentScanModel equipModel;
  int index;
  ValueChanged<int> callBack;

  AddDetailCard(
      {this.model,
      this.equipModel,
      this.callBack,
      this.index,
      this.category,
      this.item,
      this.position,
      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: Image.asset(
                  'assets/images/defule.png',
                  width: 70.px,
                  height: 80,
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text("${model?.equipName ?? equipModel.equipName}",
                        style: Theme.of(context)
                            .textTheme
                            .headline4
                            .copyWith(fontSize: 17.px)),
                    SizedBox(
                      height: 8.px,
                    ),
                    Row(
                      children: <Widget>[
                        Image(
                          image: Svg("assets/images/icon_stock_qrcode.svg",
                              size: Size(12, 12)),
                        ),
                        SizedBox(
                          width: 5.px,
                        ),
                        Text(
                          "${model?.qrCode ?? equipModel.qrCode}",
                          style: Theme.of(context)
                              .textTheme
                              .subtitle2
                              .copyWith(fontSize: 14.px),
                        )
                      ],
                    ),
                    getShowContent(context)
                  ],
                ),
              ),
            ],
          ),
          Positioned(
            right: 0.px,
            child: SvgButton(
              size: 40.px,
              src: "assets/images/icon_clear.svg",
              onTap: () {
                callBack(index);
              },
            ),
          )
        ],
      ),
    );
  }

  // 获取展示内容
  Widget getShowContent(BuildContext context) {
    if (category == RouteCategoryFrontComponentConst.fireFightingVehicle &&
        (item == RouteItemFrontComponentConst.scraped ||
            item == RouteItemFrontComponentConst.maintain ||
            item == RouteItemFrontComponentConst.repair ||
            item == RouteItemFrontComponentConst.repaired)) {
      return Column(
        children: <Widget>[
          Wrap(
            spacing: 2,
            runSpacing: 2,
            children: model.equProperties.map((e) {
              return e.textLine != null
                  ? QuoteChip(quote: e.textLine, theme: this.theme)
                  : Container();
            }).toList(),
          ),
          // Text("库存:   ${model?.amount??equipModel.total}${model?.unit??equipModel.unit}",style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),),
          model.carNum != null
              ? Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.only(top: 5.rpx),
                  child: Text(
                    "车辆编码：" + model.carNum,
                    style: Theme.of(context)
                        .textTheme
                        .subtitle2
                        .copyWith(fontSize: 13.px),
                    textAlign: TextAlign.left,
                  ),
                )
              : Container(),
        ],
      );
    } else {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          // RichText(
          //     text: TextSpan(
          //         text: "数量",
          //         style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
          //         children: [
          //           WidgetSpan(child: SizedBox(width: 15.px,)),
          //           TextSpan(text: "1", style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 13.px)),
          //           WidgetSpan(child: SizedBox(width: 15.px,)),
          //           TextSpan(text: "${equipModel.unit}", style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px)),
          //         ]
          //     ),
          //   ),
          //SizedBox(height: 10.px,),
          equipModel.carNum != null
              ? Padding(
                  padding: EdgeInsets.only(top: 5.rpx),
                  child: Text(
                    "车辆编码：" + equipModel.carNum,
                    style: Theme.of(context)
                        .textTheme
                        .subtitle2
                        .copyWith(fontSize: 13.px),
                  ),
                )
              : Container(),
          //性能指标查询报错
          Wrap(
            spacing: 2,
            runSpacing: 2,
            children: equipModel.equProperties.map((e) {
              return e.textLine != null
                  ? QuoteChip(quote: e.textLine, theme: this.theme)
                  : Container();
            }).toList(),
          ),
          // SizedBox(height: 8.px,),

          Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(top: 5.rpx, bottom: 24.rpx, right: 10),
            child: Text(
                (equipModel.carNum != null ? "原位置：" : "位置：") +
                    ((equipModel.description != null &&
                            equipModel.description != "null")
                        ? equipModel.description
                        : position),
                style: Theme.of(context)
                    .textTheme
                    .subtitle2
                    .copyWith(fontSize: 13.px),
                softWrap: true,
                overflow: TextOverflow.ellipsis,
                maxLines: 2),
          )
        ],
      );
    }
  }
}

class AddNoDetailCard extends StatelessWidget {
  CarScanModel model;
  EquipmentScanModel equipModel;
  int index;
  ValueChanged<int> callBack;

  AddNoDetailCard({this.model, this.equipModel, this.index, this.callBack});

  @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(20.px, 15.px, 10.px, 15.px),
                child: Image.asset(
                  "assets/images/defule.png",
                  width: 70.px,
                  height: 80,
                ),
              ),
              SizedBox(
                width: 10.px,
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "${model?.equipName ?? equipModel.equipName}",
                      style: Theme.of(context)
                          .textTheme
                          .headline2
                          .copyWith(color: Color(0xFF333333)),
                    ),
                    SizedBox(
                      height: 7.px,
                    ),
                    RichText(
                      text: TextSpan(
                          text: "数量：",
                          style: Theme.of(context).textTheme.headline3,
                          children: [
                            // WidgetSpan(child: SizedBox(width: 10.px,),),
                            TextSpan(
                                text: "${model?.amount ?? equipModel.amount}",
                                style: Theme.of(context).textTheme.headline4),
                            WidgetSpan(
                              child: SizedBox(
                                width: 10.px,
                              ),
                            ),
                            TextSpan(
                                text: "${model?.unit ?? equipModel.unit}",
                                style: Theme.of(context).textTheme.headline3),
                          ]),
                    ),
                    SizedBox(
                      height: 7.px,
                    ),
                    equipModel == null
                        ? Container()
                        : Text(
                            "状态：${equipModel?.status ?? '未入账'}",
                            style: Theme.of(context).textTheme.headline3,
                          ),
                  ],
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

Future<String> getEquipmentOnCar(String id) async {
  var sql = new StringBuffer();
  sql.write("select ");
  sql.write("* ");
  sql.write("from EquipmentOnCar where equipmentDetailId=$id;");
  List<Map<String, dynamic>> lstRd = await dbAccess().queryData(sql.toString());
  String carid = lstRd[0]['carId'];
  return carid;
}
