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/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/utils/request.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:base/widgets/loading_dialog.dart';
import 'package:base/widgets/tabbar_button.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:amos_iot_login_tpl/const/global_config.dart';

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

GlobalKey<_CommonAddFireAgentContentState> childKey = GlobalKey();

// 灭火药剂入库
class FireAgentInStock extends StatelessWidget {
  final RouteModel routeModel;

  const FireAgentInStock({this.routeModel});

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

class FireAgentInStockContent extends StatefulWidget {
  final RouteModel routeModel;

  const 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 warehouseId;
  String warehouseStructureId;
  String category;
  String item;

  // 分类code
  String classificationCode;

  // 分类名
  String classificationName;
  TreeNodeModel model = TreeNodeModel();

  String imageUrl = '';

  @override
  void initState() {
    super.initState();
    warehouseId = Provider.of<WarehouseInfoViewModel>(context, listen: false).warehouseInfoModel?.warehouse?.id;
    classificationCode = Provider.of<WarehouseInfoViewModel>(context, listen: false).warehouseInfoModel?.dictionaries;
    category = widget.routeModel.category;
    item = widget.routeModel.item;
    getWarehousePosition(context);
    initConfig();

    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
  }

  Future<void> initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  void setClassificationName(String name) {
    setState(() {
      classificationName = name;
    });
  }

  // 获取仓库位置信息
  Future<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 = res['result'];
          selectPosition(context);
        }
      }).catchError((_) {
        Navigator.of(context).pop();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: AppBar(
          title: Text(
            '${widget.routeModel.title}',
          ),
          elevation: 0,
          centerTitle: true,
          actions: <Widget>[Container()],
        ),
        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),
                      const Expanded(
                        child: Center(
                          child: Text('请求数据为空'),
                        ),
                      )
                    ],
                  )
                : (agents.isEmpty
                    ? const Center(
                        child: CircularProgressIndicator(),
                      )
                    : Stack(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.only(bottom: 48.px),
                            child: Column(
                              children: <Widget>[buildTopBar(context), buildListContext(context)],
                            ),
                          ),
                          buildBottomBar(context)
                        ],
                      ))));
  }

  // 列表内容
  Widget buildListContext(context) {
    return Expanded(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 8.px, vertical: 10.px),
        child: ListView.separated(
            itemBuilder: (ctx, index) {
              FireAgentCategoryModel item = agents[index];
              return Card(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.px)),
                elevation: 4,
                shadowColor: const Color.fromRGBO(69, 91, 99, 0.08),
                margin: EdgeInsets.zero,
                child: Row(
                  children: <Widget>[
                    Padding(
                        padding: EdgeInsets.fromLTRB(20.px, 20.px, 28.px, 10.px),
                        child: item.img == null
                            ? Image.asset(
                                'assets/images/icon_default.png',
                          // ExternalAssetsPackageKey.BASE,
                                width: 60.px,
                                height: 60.px,
                              )
                            : Image.network(
                                imageUrl+item.img,
                                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.headline6.copyWith(fontSize: 20.px),
                            ),
                            SizedBox(
                              height: 10.px,
                            ),
                            RichText(
                              text: TextSpan(
                                  text: "库存",
                                  style: Theme.of(context).textTheme.headline6.copyWith(fontSize: 16.px,fontWeight: FontWeight.w100),
                                  children: [
                                    const WidgetSpan(
                                        child: SizedBox(
                                      width: 10,
                                    )),
                                    TextSpan(text: '${item.amount}', style: Theme.of(context).textTheme.headline6.copyWith(fontSize: 16.px)),
                                    const WidgetSpan(
                                        child: SizedBox(
                                      width: 10,
                                    )),
                                    TextSpan(
                                        text: item.equipmentDetail.unitName ?? '吨',
                                        style:
                                            Theme.of(context).textTheme.headline6.copyWith(fontSize: 16.px,fontWeight: FontWeight.w100))
                                  ]),
                            ),
                            SizedBox(
                              height: 5.px,
                            ),
                            widget.routeModel.item == RouteItemFrontComponentConst.extinguishLoad
                                ? Text(
                                    '批次: ${item.batchNum}',
                                    style: Theme.of(context).textTheme.headline6.copyWith(fontSize: 16.px)
                                  )
                                : Container(),
                            SizedBox(
                              height: 8.px,
                            ),
                          ],
                        ),
                      ),
                    ),
                    IconButton(
                      icon: Icon(Icons.add),
                      color:Color.fromRGBO(50, 89, 206, 1),
                      onPressed: () => addInStock(context, item),
                    )
                    // 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 ?? "全部"}",
            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: const 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: const 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.headline6,
                  ),
                  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) {
    setState(() {
      agents = [];
      isEmpty = false;
    });

    final params = {"warehouseStructureId": warehouseStructureId, "pageNum": 0};
    HttpRequest.getStockDetailCategory(params: params, category: classificationCode).then((res) {
      if (res["status"] == 200) {
        List lists = res["result"]["records"];
        List<FireAgentCategoryModel> items = [];
        for (var json in lists) {
          items.add(FireAgentCategoryModel.fromJson(json));
        }
        setState(() {
          hasError = false;
          agents = items;
        });

        if (lists.length == 0) {
          setState(() {
            isEmpty = true;
          });
        }
      }
    }).catchError((err) {
      print(err);
      setState(() {
        hasError = true;
      });
    });
  }

  // 获取灭火药剂装载列表
  void getStockDetailStock(BuildContext context) {
    setState(() {
      agents = [];
      isEmpty = false;
    });

    final params = {
      "warehouseStructureId": warehouseStructureId,
      "pageNum": 0,
    };
    HttpRequest.getStockDetailStock(params: params).then((res) {
      if (res["status"] == 200) {
        List lists = res["result"]["records"];
        List<FireAgentCategoryModel> items = [];
        for (var json in lists) {
          items.add(FireAgentCategoryModel.fromJson(json));
        }
        setState(() {
          hasError = false;
          agents = items;
        });
        if (lists.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.addFireAgentConfirm, 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.addFireAgentConfirm, 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.addFireAgentConfirm, 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(
            theme: theme,
            callback: (value) {
              if (double.parse(value) == 0) {
                FlutterToast.toastCenter("数量不能为空");
                return;
              }
              List<String> pag = value.split('.');
              if (pag.length > 2) {
                FlutterToast.toastCenter("输入正确数字");
                return;
              }
              if (pag.length == 1) {
                var lis1 = pag[0];
                if (lis1.length > 10) {
                  FlutterToast.toastCenter("输入数字不正确");
                  return;
                }
              }
              if (pag.length == 2) {
                var lis1 = pag[0];
                var lis2 = pag[1];
                if (lis1.length > 10) {
                  FlutterToast.toastCenter("输入数字不正确");
                  return;
                }
                if (lis2.length > 2) {
                  FlutterToast.toastCenter("输入数字不正确");
                  return;
                }
              }
              if (item == RouteItemFrontComponentConst.extinguishLoad) {
                if (!isExistItems(it.id)) {
                  // 判断装载数量和库存数量关系

                  double count = double.parse(value);

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

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

                  setState(() {});
                } else {
                  _addItems.forEach((element) {
                    if (it.id == element['equipmentDetailId']) {
                      double count = double.parse(value) + double.parse(element['amount']);
                      if (count > 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.equipmentDetail.id)) {
                  final addItem = {"amount": value, "equipmentDetailId": it.equipmentDetail.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 > it.amount) {
                    FlutterToast.toastCenter(ToastMessage.countNotMoreStock);
                    return;
                  } else if (count < 0) {
                    FlutterToast.toastCenter(ToastMessage.notLowZero);
                    return;
                  }
                  final addItem = {"amount": value, "equipmentDetailId": it.id, "model": it.toJson()};
                  _addItems.add(addItem);
                  setState(() {});
                } else {
                  _addItems.forEach((element) {
                    if (it.id == element['equipmentDetailId']) {
                      double count = double.parse(value) + double.parse(element['amount']);
                      if (count > it.amount) {
                        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["equipmentDetailId"].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["equipmentDetailId"].toString() == it.equipmentDetail.id.toString()) {
        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(), "equipmentDetailId": it.equipmentDetail.id, "model": it.toJson()};
    _addItems.removeAt(indx);
    _addItems.add(addItem);
  }
}
