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/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/model/warehouse_tree_postion_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/add_count_dialog.dart';
import 'package:base/widgets/back_button.dart';
import 'package:base/widgets/dialog/choose_position.dart';
import 'package:base/widgets/fire_agent_end_drawer.dart';
import 'package:equipment_manage/model/fire_agent_category_model.dart';
import 'package:equipment_manage/model/fire_agent_classification_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

GlobalKey<_CommonAddFireAgentContentState> childKey = GlobalKey();

// 灭火药剂入库
class OfflineFireAgentInStock extends StatelessWidget {
  final RouteModel routeModel;
  OfflineFireAgentInStock({this.routeModel});

  @override
  Widget build(BuildContext context) {
    // return Scaffold(
    //   backgroundColor: AppTheme.backgroundColor,
    //   appBar: AppBar(
    //     title: Text("${routeModel.title}",style: TextStyle(color: Colors.black),),
    //     backgroundColor: Colors.white,
    //     elevation: 0,
    //     leading: LeadingButton(
    //       theme:childKey.currentState.theme,
    //       onWillScope: true,
    //       onWillPop: (){
    //         Navigator.of(context).pop();
    //       },
    //     ),
    //     centerTitle: true,
    //     actions: <Widget>[
    //       Container()
    //     ],
    //   ),
    //   endDrawerEnableOpenDragGesture: false,
    //   endDrawer: Builder(
    //     builder: (ctx) {
    //       return FireAgentEndDrawer(
    //         category: Provider.of<WarehouseInfoViewModel>(context,listen: false).warehouseInfoModel?.dictionaries,
    //         click: (FireAgentClassificationModel e) {
    //           if(e != null) {
    //             childKey.currentState.classificationCode = e.code;
    //             childKey.currentState.setClassificationName(e.name);
    //           } else {
    //             childKey.currentState.classificationCode =  Provider.of<WarehouseInfoViewModel>(context,listen: false).warehouseInfoModel?.dictionaries;
    //             childKey.currentState.setClassificationName(null);
    //           }
    //
    //           String category =  childKey.currentState.category;
    //           String item = childKey.currentState.item;
    //
    //           if(category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
    //             if(item == RouteItemFrontComponentConst.inStock) {
    //               childKey.currentState.getStockDetailCategory(context);
    //             } else if(item == RouteItemFrontComponentConst.extinguishLoad  || item == RouteItemFrontComponentConst.scraped) {
    //               childKey.currentState.getStockDetailStock(context);
    //             }
    //           }
    //         },
    //       );
    //     },
    //   ),
    //  body:
    return FireAgentInStockContent(
      key: childKey,
      routeModel: routeModel,
    );
  }
}

class FireAgentInStockContent extends StatefulWidget {
  final RouteModel routeModel;
  FireAgentInStockContent({Key key, this.routeModel}) : super(key: key);
  @override
  _CommonAddFireAgentContentState createState() =>
      _CommonAddFireAgentContentState();
}

class _CommonAddFireAgentContentState extends State<FireAgentInStockContent> {
  List _addItems = [];
  List<FireAgentCategoryModel> agents = [];
  bool hasError = false;
  bool isEmpty = false;
  String theme;
  // 位置
  String _selectPosition;
  // 位置描述
  //String _positionDescription = "";

  String warehouseId = '0';
  String warehouseStructureId;

  String category;
  String item;
  List<String> warIdList = [];
  // 分类code
  String classificationCode;
  // 分类名
  String classificationName;

  TreeNodeModel model = TreeNodeModel();

  @override
  void initState() {
    super.initState();

    warehouseId =
        Provider.of<WarehouseInfoViewModel>(this.context, listen: false)
            .warehouseInfoModel
            ?.warehouse
            ?.id;
    classificationCode =
        Provider.of<WarehouseInfoViewModel>(this.context, listen: false)
            .warehouseInfoModel
            ?.dictionaries;

    category = widget.routeModel.category;
    item = widget.routeModel.item;

    getWarehousePosition(this.context);
    initConfig();
  }

  initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        this.theme =
            preferences.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }
  // 显示位置描述
  // void showEquipInStockDescription(BuildContext context) {
  //   showModalBottomSheet(
  //       isDismissible:false,
  //       enableDrag:false,
  //       shape: RoundedRectangleBorder(
  //           borderRadius: BorderRadius.circular(10.px)
  //       ),
  //       context: context,
  //       builder: (BuildContext context){
  //         return PositionDescriptionDialog(
  //           callback: (str) {
  //             setState(() {
  //               _positionDescription = str;
  //             });
  //             if(category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
  //               if(item == RouteItemFrontComponentConst.inStock) {
  //                 getStockDetailCategory(context);
  //               } else if(item == RouteItemFrontComponentConst.extinguishLoad  || item == RouteItemFrontComponentConst.scraped) {
  //                 getStockDetailStock(context);
  //               }
  //             }
  //           },
  //           close: (){
  //             if(category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
  //               if(item == RouteItemFrontComponentConst.inStock) {
  //                 getStockDetailCategory(context);
  //               } else if(item == RouteItemFrontComponentConst.extinguishLoad  || item == RouteItemFrontComponentConst.scraped) {
  //                 getStockDetailStock(context);
  //               }
  //             }
  //           },
  //         );
  //       });
  // }

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

  // 获取仓库位置信息
  void getWarehousePosition(BuildContext context) async {
    // Future.delayed(Duration.zero, () {
    //   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) {
    Provider.of<WarehouseTreePositionViewModel>(context, listen: false)
        .positions = await getOfflineWarehouse();
    selectPosition(context);
    //     }
    //   }).catchError((_){
    //     Navigator.of(context).pop();
    //   });
    // });
  }

  @override
  Widget build(BuildContext context) {
    // if(hasError) {
    //   return Container();
    // } else if(isEmpty) {
    //   return Column(
    //     children: <Widget>[
    //       buildTopBar(context),
    //       Expanded(child: Center(child: Text("请求数据为空"),),)
    //     ],
    //   );
    // } else {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            "${widget.routeModel.title}",
            style: TextStyle(color: Colors.black),
          ),
          backgroundColor: Colors.white,
          elevation: 0,
          leading: LeadingButton(
            theme: theme,
            onWillScope: true,
            onWillPop: () {
              Navigator.of(context).pop();
            },
          ),
          centerTitle: true,
          actions: <Widget>[Container()],
        ),
        endDrawerEnableOpenDragGesture: false,
        endDrawer: Builder(
          builder: (ctx) {
            return FireAgentEndDrawer(
              theme: theme,
              category:
                  Provider.of<WarehouseInfoViewModel>(context, listen: false)
                      .warehouseInfoModel
                      ?.dictionaries,
              click: (FireAgentClassificationModel e) {
                if (e != null) {
                  classificationCode = e.code;
                  setClassificationName(e.name);
                } else {
                  classificationCode = Provider.of<WarehouseInfoViewModel>(
                          context,
                          listen: false)
                      .warehouseInfoModel
                      ?.dictionaries;
                  setClassificationName(null);
                }

                String category = this.category;
                String item = this.item;

                if (category ==
                    RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
                  if (item == RouteItemFrontComponentConst.inStock) {
                    getStockDetailCategory(context);
                  } else if (item ==
                          RouteItemFrontComponentConst.extinguishLoad ||
                      item == RouteItemFrontComponentConst.scraped) {
                    getStockDetailStock(context);
                  }
                }
              },
            );
          },
        ),
        body: hasError
            ? Container()
            : (isEmpty
                ? Column(
                    children: <Widget>[
                      buildTopBar(context),
                      Expanded(
                        child: Center(
                          child: Text("请求数据为空"),
                        ),
                      )
                    ],
                  )
                : (agents.length == 0
                    ? 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) {
              FireAgentCategoryModel item = agents[index];
              return Card(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(6.px)),
                elevation: 4,
                shadowColor: 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: Image.asset(
                          "assets/images/defule.png",
                          width: 60.px,
                          height: 60.px,
                        )),
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.symmetric(vertical: 10.px),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "${item.equipmentDetail.name}",
                              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: [
                                    WidgetSpan(
                                        child: SizedBox(
                                      width: 10,
                                    )),
                                    TextSpan(
                                      text: "${item.amount}",
                                      style:
                                          Theme.of(context).textTheme.headline4,
                                    ),
                                    WidgetSpan(
                                        child: SizedBox(
                                      width: 10,
                                    )),
                                    TextSpan(
                                        text:
                                            "${item.equipmentDetail.unitName}",
                                        style: Theme.of(context)
                                            .textTheme
                                            .headline6
                                            .copyWith(
                                                fontWeight: FontWeight.w100))
                                  ]),
                            ),
                            SizedBox(
                              height: 5.px,
                            ),
                            // widget.routeModel.item == RouteItemFrontComponentConst.extinguishLoad? Text("批次: ${item.batchNum}", style: Theme.of(context).textTheme.headline6,):Container(),
                            // SizedBox(height: 8.px,),
                          ],
                        ),
                      ),
                    ),
                    SvgButton(
                      onTap: () => addInStock(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: Column(
        children: <Widget>[
          // Center(child:
          //   TopBarButton(
          //     name: "${classificationName==null?"全部":classificationName}",
          //     onPressed: (){
          //        Scaffold.of(context).openEndDrawer();
          //   },)),
          Container(
            padding: EdgeInsets.only(top: 8.px),
            color: AppTheme.backgroundColor,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    width: double.infinity,
                    height: 1,
                    color: Color(0xFFe0e1e5),
                  ),
                ),
                InkWell(
                  onTap: () => selectPosition(context),
                  child: Container(
                    width: 150.px,
                    child: Center(
                      child: Text(
                        "${_selectPosition != null ? "$_selectPosition" : "选择位置"}",
                        style: TextStyle(color: GetConfig.getColor(theme)),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    width: double.infinity,
                    height: 1,
                    color: Color(0xFFe0e1e5),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  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 selectPosition(context) {
    List items =
        Provider.of<WarehouseTreePositionViewModel>(context, listen: false)
            .positions;
    showModalBottomSheet(
        isDismissible: false,
        enableDrag: false,
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.px)),
        context: context,
        builder: (BuildContext context) {
          return ChoosePositionDialog(
            theme: theme,
            data: items,
            selectedModel: this.model,
            close: () {
              if (warehouseStructureId == null) {
                Navigator.of(context).pop();
              }
            },
            callback: (TreeNodeModel model) {
              this.model = model;
              setState(() {
                _selectPosition = model.fullName ?? model.name;
              });
            },
            confirm: (TreeNodeModel model) {
              this.model = model;
              warehouseStructureId = model.id;
              // showEquipInStockDescription(context);
              if (category ==
                  RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
                if (item == RouteItemFrontComponentConst.inStock) {
                  getStockDetailCategory(context);
                } else if (item ==
                        RouteItemFrontComponentConst.extinguishLoad ||
                    item == RouteItemFrontComponentConst.scraped) {
                  getStockDetailStock(context);
                }
              }
            },
          );
        });
  }

  // 获取灭火药剂入库的列表数据
  void getStockDetailCategory(BuildContext context) async {
    setState(() {
      agents = [];
      isEmpty = false;
    });

    // final params = {
    //   "warehouseStructureId":warehouseStructureId,
    //   "pageNum":0
    // };
    // HttpRequest.getStockDetailCategory(params: params,category:classificationCode).then((res) {
    //     if(res["status"] == 200) {
    // List lists = await getOfflineAgentList(warehouseStructureId);
    agents = await getOfflineAgentList(warehouseStructureId);
    // for (var json in lists) {
    //   items.add(FireAgentCategoryModel.fromJson(json));
    // }
    hasError = false;
    // agents = items;
    setState(() {});
    if (agents.length == 0) {
      setState(() {
        isEmpty = true;
      });
    }
    //     }
    // }).catchError((err){
    //   print(err);
    //   setState(() {
    //     hasError = true;
    //   });
    // });
  }

  getmogString(TreeNodeModel model) {
    model.children.forEach((element) {
      warIdList.add(element.id);
      if (element.children != null) {
        getmogString(element);
      }
    });
  }

  // 获取灭火药剂装载列表
  void getStockDetailStock(BuildContext context) async {
    setState(() {
      agents = [];
      isEmpty = false;
    });
    warIdList.clear();
    warIdList.add(this.model.id);
    if (model.children != null) {
      getmogString(this.model);
    }
    String result;
    warIdList.forEach((element) {
      if (result == null) {
        result = "\"$element\"";
      } else {
        result = "$result,\"$element\"";
      }
    });
    String type = '';
    if (item == RouteItemFrontComponentConst.scraped) {
      type = '34';
    }

    agents = await getOfflineAgentList(result, type: type);
    // final params = {
    //   "warehouseStructureId":warehouseStructureId,
    //   "pageNum":0,
    // };
    // HttpRequest.getStockDetailStock(params: params).then((res) {
    //   if(res["status"] == 200) {
    //     List lists = await getOfflineAgentList(warehouseStructureId);
    //     List<FireAgentCategoryModel> items = [];
    //     for (var json in lists) {
    //       items.add(FireAgentCategoryModel.fromJson(json));
    //     }
    setState(() {
      hasError = false;
      //agents = items;
    });
    if (agents.length == 0) {
      setState(() {
        isEmpty = true;
      });
    }
    //   }
    // }).catchError((err){
    //   print(err);
    //   setState(() {
    //     hasError = true;
    //   });
    // });
  }

  // 查看
  void check(BuildContext context) {
    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.inStock) {
      for (var item in _addItems) {
        item["warehouseId"] = warehouseId;
        item["warehouseStructureId"] = warehouseStructureId;
      }

      final params = {
        "title": widget.routeModel.title,
        "category": category,
        "item": item,
        "extension": json.encode({
          "extension": _addItems,
          "description": "",
          "position": _selectPosition
        })
      };

      Application.navigateToPath(context, Routes.offlineAddFireAgentConfirm,
              params: params)
          .then((value) {
        setState(() {
          if (value != null) {
            _addItems = value;
          } else {
            _addItems = [];
          }
        });
      });
    } else if (category ==
            RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.extinguishLoad) {
      for (var item in _addItems) {
        item["car_id"] = widget.routeModel.extension["carId"] ?? "";
      }

      final params = {
        "title": widget.routeModel.title,
        "category": category,
        "item": item,
        "extension": json.encode({"extension": _addItems})
      };

      Application.navigateToPath(context, Routes.offlineAddFireAgentConfirm,
              params: params)
          .then((value) {
        setState(() {
          if (value != null) {
            _addItems = value;
          } else {
            _addItems = [];
          }
        });
      });
    } else if (category ==
            RouteCategoryFrontComponentConst.fireExtinguishingAgent &&
        item == RouteItemFrontComponentConst.scraped) {
      final params = {
        "title": widget.routeModel.title,
        "category": category,
        "item": item,
        "extension": json.encode({"extension": _addItems})
      };

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

  // 入账
  void addInStock(BuildContext context, FireAgentCategoryModel it) {
    showDialog(
        context: context,
        builder: (ctx) {
          return AddCountDialog(
            until: it.equipmentDetail.unitName,
            theme: theme,
            callback: (value) {
              if (double.parse(value) == 0) {
                FlutterToast.toastCenter("数量不能为空");
                return;
              }

              if (item == RouteItemFrontComponentConst.extinguishLoad) {
                if (!isExistItems(it.id)) {
                  // 判断装载数量和库存数量关系

                  double count = double.parse(value);

                  if (count > double.parse(it.amount)) {
                    FlutterToast.toastCenter("装载数量不能大于库存数量!");
                    return;
                  } else if (count < 0) {
                    FlutterToast.toastCenter(ToastMessage.notLowZero);
                    return;
                  }

                  final addItem = {
                    "amount": value,
                    "stockDetailId": it.id,
                    "model": it.toJson()
                  };
                  _addItems.add(addItem);

                  setState(() {});
                } else {
                  _addItems.forEach((element) {
                    if (it.id == element['stockDetailId']) {
                      double count =
                          double.parse(value) + double.parse(element['amount']);
                      if (count > double.parse(it.amount)) {
                        FlutterToast.toastCenter("装载数量不能大于库存数量!");
                        return;
                      } else if (count < 0) {
                        FlutterToast.toastCenter(ToastMessage.notLowZero);
                        return;
                      }
                      element['amount'] = count.toString();
                    }
                  });
                  setState(() {});
                  // FlutterToast.toastCenter(ToastMessage.alreadyAdd);
                }
              } else if (item == RouteItemFrontComponentConst.inStock) {
                if (!isExistItems(it.id)) {
                  final addItem = {
                    "amount": value,
                    "stockDetailId": it.id,
                    "model": it.toJson()
                  };
                  _addItems.add(addItem);
                  setState(() {});
                } else {
                  add_addItemList(it, value);
                  setState(() {});
                  //FlutterToast.toastCenter(ToastMessage.alreadyAdd);
                }
              } else if (item == RouteItemFrontComponentConst.scraped) {
                if (!isExistItems(it.id)) {
                  double count = double.parse(value);

                  if (count > double.parse(it.amount.toString())) {
                    FlutterToast.toastCenter(ToastMessage.countNotMoreStock);
                    return;
                  } else if (count < 0) {
                    FlutterToast.toastCenter(ToastMessage.notLowZero);
                    return;
                  }
                  it.batchNum = DateTime.now().toString().substring(0, 10);
                  final addItem = {
                    "amount": value,
                    "stockDetailId": it.id,
                    "model": it.toJson()
                  };
                  _addItems.add(addItem);
                  setState(() {});
                } else {
                  _addItems.forEach((element) {
                    if (it.id == element['stockDetailId']) {
                      double count =
                          double.parse(value) + double.parse(element['amount']);
                      if (count > double.parse(it.amount.toString())) {
                        FlutterToast.toastCenter(
                            ToastMessage.countNotMoreStock);
                        return;
                      } else if (count < 0) {
                        FlutterToast.toastCenter(ToastMessage.notLowZero);
                        return;
                      }
                      element['amount'] = count.toString();
                    }
                  });
                  setState(() {});
                  // FlutterToast.toastCenter("已存在添加列表中!");
                }
              }
            },
          );
        });
  }

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

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

//添加同类型灭火药剂只增加数量
  void add_addItemList(it, value) {
    double amous;
    int indx;
    for (int i = 0; i < _addItems.length; i++) {
      dynamic element = _addItems[i];
      if (element['stockDetailId'].toString() == it.id) {
        indx = i;
        amous = double.parse(element["amount"]) + double.parse(value);
      }
    }
    // _addItems.forEach((element) {
    //   if(element["equipmentDetailId"] == it.equipmentDetail.id) {
    //     equipment=element;
    //     amous= double.parse(element["amount"])+double.parse(value);
    //   }
    // });
    final addItem = {
      "amount": amous.toString(),
      "stockDetailId": it.id,
      "model": it.toJson()
    };
    _addItems.removeAt(indx);
    _addItems.add(addItem);
  }
}
