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/select_vehicle_view_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/flutter_toast.dart';
import 'package:base/widgets/add_count_dialog.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/dialog/select_reason.dart';
import 'package:base/widgets/dialog/vehicle_modal_dialog.dart';
import 'package:base/widgets/pin_text_dialog.dart';
import 'package:equipment_manage/model/car_scan_model.dart';
import 'package:equipment_manage/model/equipment_scan_model.dart';
import 'package:equipment_manage/utils/equipment_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_svg_provider/flutter_svg_provider.dart';
import 'package:provider/provider.dart';
import 'package:r_scan/r_scan.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

class OfflineEquipWareHousing extends StatelessWidget {
  final RouteModel routeModel;

  OfflineEquipWareHousing({this.routeModel});

  @override
  Widget build(BuildContext context) {
    return
        // Scaffold(
        // appBar: AppBar(
        //   titleSpacing: 0,
        //   leading: LeadingButton(
        //     theme: childKey.currentState.theme,
        //     onWillScope: true,
        //     onWillPop: () {
        //       if (childKey.currentState._addItems.length > 0) {
        //         showDialog<Null>(
        //             context: context,
        //             builder: (BuildContext context) {
        //               return CommonAlertDialog(
        //                   onTap: () {
        //                     childKey.currentState._controller?.dispose();
        //                     childKey.currentState._controller = null;
        //                     Navigator.of(context).pop();
        //                   },
        //                   content: ToastMessage.forgetListAdd);
        //             });
        //       } else {
        //         childKey.currentState._controller?.dispose();
        //         childKey.currentState._controller = null;
        //         Navigator.of(context).pop();
        //       }
        //     },
        //   ),
        //   title: Text(
        //     routeModel.title,
        //     style: Theme.of(context).textTheme.headline2,
        //   ),
        //   centerTitle: true,
        //   actions: <Widget>[
        //     // 二维码扫码查询, 查询默认是没有输入编码的
        //     routeModel.category == RouteCategoryFrontComponentConst.query
        //         ? Container()
        //         :
        //         // 输入编码弹出框
        //         InkWell(
        //             splashColor: Colors.transparent,
        //             highlightColor: Colors.transparent,
        //             onTap: () => entryCode(context),
        //             child: Row(
        //               children: <Widget>[
        //                 Row(
        //                   children: <Widget>[
        //                     Padding(
        //                       padding: EdgeInsets.only(top: 3.px),
        //                       child: Image(
        //                         image: Svg("assets/images/icon_entry_code.svg",
        //                             size: Size(20, 20)),
        //                       ),
        //                     ),
        //                     SizedBox(
        //                       width: 5.px,
        //                     ),
        //                     Text(
        //                       "输入编码",
        //                       style: Theme.of(context)
        //                           .textTheme
        //                           .subtitle1
        //                           .copyWith(color:GetConfig.getColor(childKey.currentState.theme)),
        //                     ),
        //                     SizedBox(
        //                       width: 32.rpx,
        //                     )
        //                   ],
        //                   crossAxisAlignment: CrossAxisAlignment.center,
        //                 )
        //               ],
        //             ),
        //           )
        //   ],
        // ),
        // body:
        EquipWareHousingContent(routeModel);
    //);
  }

// 输入编码点击事件
// void entryCode(context) {
//   // 销毁二维码识别
//   childKey.currentState._controller?.dispose();
//   childKey.currentState._controller = null;
//
//   showDialog(
//       context: context,
//       builder: (ctx) {
//         return PinTextDialog(
//           callback: (value) {
//             if (childKey.currentState._controller == null) {
//               childKey.currentState.getRSCamera();
//             }
//             String code;
//             String category = childKey.currentState.category;
//             String item = childKey.currentState.item;
//
//             // 灭火药剂装载损耗扫码的都是车辆
//             if (category ==
//                 RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
//               if (item == RouteItemFrontComponentConst.extinguishWastage ||
//                   item == RouteItemFrontComponentConst.extinguishLoad) {
//                 code = "${QRType.fireFightingVehiclePrefix}$value";
//               }
//             }
//             // 消防车辆
//             else if (category ==
//                 RouteCategoryFrontComponentConst.fireFightingVehicle) {
//               if (item == RouteItemFrontComponentConst.carLoad ||
//                   item == RouteItemFrontComponentConst.carUnLoad) {
//                 //输入车辆二维码
//
//                 code = "${QRType.equipmentPrefix}$value";
//               } else {
//                 code = "${QRType.fireFightingVehiclePrefix}$value";
//               }
//             }
//             // 器材
//             else if (category == RouteCategoryFrontComponentConst.equipment) {
//               code = "${QRType.equipmentPrefix}$value";
//             }
//
//             childKey.currentState.checkQRScanResult(context, code);
//           },
//           cancel: () {
//             childKey.currentState.getRSCamera();
//           },
//         );
//       });
// }
}

class EquipWareHousingContent extends StatefulWidget {
  final RouteModel routeModel;

  EquipWareHousingContent(this.routeModel);

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

class _EquipWareHousingContentState extends State<EquipWareHousingContent> {
  RScanCameraController _controller;
  bool isFirst = true;
  List<RScanCameraDescription> rScanCameras;

  String category;
  String item;

  // * 是否扫码中
  // 全局重要判断字段，防止多次扫码
  bool scanning = false;

  // 查询仓库id
  String warehouseId;

  // 添加数量
  List _addItems = [];

  // 位置
  String _selectPosition;

  // 描述
  String _positionDescription = ' ';

  // 位置id
  String _warehouseStructureId;

  // 损耗
  // 选择车辆
  Map<String, dynamic> _selectVehicle;
  TreeNodeModel model = TreeNodeModel();

  // 选择原因
  List reasons = List();
  String _selectReason;
  String theme = '';

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

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

    bool isExists = false;

    for (EquipmentScanModel model in _addItems) {
      if (model.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++) {
      EquipmentScanModel element = _addItems[i];
      if (element.equipmentDetailId.toString() ==
          it.equipmentDetailId.toString()) {
        //indx=i;

        amous = double.parse(element.amount.toString()) + double.parse(value);
        element.amount = amous;
      }
    }
  }

  @override
  void initState() {
    super.initState();
    initThemeConfig();
    // 查询基本信息
    category = widget.routeModel.category;
    item = widget.routeModel.item;
    warehouseId =
        Provider.of<WarehouseInfoViewModel>(this.context, listen: false)
            .warehouseInfoModel
            ?.warehouse
            ?.id;

    getRSCamera();

    if (category == RouteCategoryFrontComponentConst.equipment) {
      if (item == "inStock") {
        getWarehousePosition(this.context);
      } else if (item == RouteItemFrontComponentConst.scraped) {
        getScrapReason(this.context);
      }
    } else if (category ==
        RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (item == "inStock") {
        getWarehousePosition(this.context);
      } else // 损耗获取车辆列表
      if (item == RouteItemFrontComponentConst.extinguishWastage ||
          item == RouteItemFrontComponentConst.extinguishLoad) {
        getWasteCarList(this.context);
      }
    } else if (category ==
        RouteCategoryFrontComponentConst.fireFightingVehicle) {
      if (item == RouteItemFrontComponentConst.carLoad) {
        getWasteCarList(this.context);
      } else if (item == RouteItemFrontComponentConst.scraped) {
        getScrapReason(this.context);
      }
    }
  }

  // 获取原因
  void getScrapReason(BuildContext context) async {
    // Future.delayed(Duration.zero, () {
    //   showDialog(
    //       context: context,
    //       builder: (ctx) {
    //         return LoadingDialog(
    //           barrierDismissible: true,
    //         );
    //       });
    //   HttpRequest.getScrapReason().then((res) {
    //     Navigator.of(context).pop();
    //     if (res["status"] == 200) {
    reasons = await getReason();
    print(reasons);
    // reasons =jsonDecode(reason.toString());

    //     }
    //   }).catchError((_) {
    //     Navigator.of(context).pop();
    //   });
    // });
  }

  // 获取损耗下车辆列表
  void getWasteCarList(BuildContext context) async {
    // Future.delayed(Duration.zero, () {
    //   showDialog(
    //       context: context,
    //       builder: (ctx) {
    //         return LoadingDialog(
    //           barrierDismissible: true,
    //         );
    //       });
    //   HttpRequest.wasteQueryCarList().then((res) {
    //     Navigator.of(context).pop();
    // if (res["status"] == 200) {
    Provider.of<SelectVehicleViewModel>(context, listen: false).vehicles =
        await getOfflineCarList();
    //     res["result"];
    //   }
    // }).catchError((_) {
    //   Navigator.of(context).pop();
    // });
    //  });
  }

  // 获取仓库位置信息
  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();
    //     }
    //   }).catchError((_) {
    //     Navigator.of(context).pop();
    //   });
    // });
  }

  @override
  Widget build(BuildContext context) {
    //判断是否有可用相机
    if (rScanCameras == null || rScanCameras.length == 0) {
      return Scaffold(
        body: Container(
          alignment: Alignment.center,
          child: Text('not have available camera'),
        ),
      );
    }
    //判断相机如果没有初始化，给它一个加载页面
    if (_controller == null || !_controller.value.isInitialized) {
      return Container();
    }
    String titleew;
    if (widget.routeModel.category ==
        RouteCategoryFrontComponentConst.equipment) {
      titleew = "装备";
    } else if (widget.routeModel.category ==
        RouteCategoryFrontComponentConst.fireFightingVehicle) {
      if (widget.routeModel.item == RouteItemFrontComponentConst.carLoad) {
        titleew = _selectVehicle == null ? "车辆" : "装备";
      } else if (widget.routeModel.item ==
          RouteItemFrontComponentConst.carUnLoad) {
        titleew = "装备";
      } else {
        titleew = "车辆";
      }
    } else if (widget.routeModel.category ==
        RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (widget.routeModel.item == RouteItemFrontComponentConst.inStock) {
        titleew = "灭火药剂";
      } else {
        titleew = "车辆";
      }
    } else {
      titleew = "装备";
    }
    // if (widget.routeModel.item == 'carUnLoad' ||
    //     widget.routeModel.item == 'inStock' ||
    //     widget.routeModel.item == 'repair' ||
    //     widget.routeModel.item == 'maintain' ||
    //     widget.routeModel.item == 'repaired' ||
    //     widget.routeModel.item == 'scraped') {
    //   titleew = "装备";
    // } else if (widget.routeModel.item == 'carmaintain' ||
    //     widget.routeModel.item == 'carrepair' ||
    //     widget.routeModel.item == 'carrepaired' ||
    //     widget.routeModel.item == 'carscraped') {
    //   titleew = "车辆";
    // } else if (widget.routeModel.item == 'carLoad') {
    //   titleew = _selectVehicle==null?"车辆":"装备";
    // } else {
    //   titleew = "装备";
    // }

    //获取到相机
    return Scaffold(
        appBar: AppBar(
          titleSpacing: 0,
          leading: LeadingButton(
            theme: theme,
            onWillScope: true,
            onWillPop: () {
              if (_addItems.length > 0) {
                showDialog<Null>(
                    context: context,
                    builder: (BuildContext context) {
                      return CommonAlertDialog(
                          theme: theme,
                          onTap: () {
                            _controller?.dispose();
                            _controller = null;
                            Navigator.of(context).pop();
                          },
                          content: ToastMessage.forgetListAdd);
                    });
              } else {
                _controller?.dispose();
                _controller = null;
                Navigator.of(context).pop();
              }
            },
          ),
          title: Text(
            widget.routeModel.title,
            style: TextStyle(color: Colors.black),
          ),
          centerTitle: true,
          actions: <Widget>[
            // 二维码扫码查询, 查询默认是没有输入编码的
            widget.routeModel.category == RouteCategoryFrontComponentConst.query
                ? Container()
                :
                // 输入编码弹出框
                InkWell(
                    splashColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    onTap: () => entryCode(context),
                    child: Row(
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Padding(
                              padding: EdgeInsets.only(top: 3.px),
                              child: Image(
                                image: Svg("assets/images/icon_entry_code.svg",
                                    size: Size(20, 20)),
                                color: GetConfig.getColor(theme),
                              ),
                            ),
                            SizedBox(
                              width: 5.px,
                            ),
                            Text(
                              item == RouteItemFrontComponentConst.carLoad
                                  ? "输入装备编码"
                                  : "输入编码",
                              style: Theme.of(context)
                                  .textTheme
                                  .subtitle1
                                  .copyWith(color: GetConfig.getColor(theme)),
                            ),
                            SizedBox(
                              width: 32.rpx,
                            )
                          ],
                          crossAxisAlignment: CrossAxisAlignment.center,
                        )
                      ],
                    ),
                  )
          ],
        ),
        body: Scaffold(
          backgroundColor: Colors.black,
          body: Stack(
            children: <Widget>[
              ScanImageView(
                theme: theme,
                child: RScanCamera(_controller),
              ),
              //闪光灯
              Align(
                  alignment: Alignment(0, -0.05),
                  child: FutureBuilder(
                    future: getFlashMode(),
                    builder: _buildFlashBtn,
                  )),
              Align(
                  alignment: Alignment(0, 0.08),
                  child: Text(
                    "请对准" + titleew + "二维码",
                    style: Theme.of(context).textTheme.headline2,
                  )),
              buildSelectItem(context),

              // 查询没有下面的底部的bar
              (widget.routeModel.category ==
                          RouteCategoryFrontComponentConst.query ||
                      widget.routeModel.item ==
                          RouteItemFrontComponentConst.extinguishLoad ||
                      widget.routeModel.item ==
                          RouteItemFrontComponentConst.extinguishWastage)
                  ? Container()
                  : buildBottomBar(context)
            ],
          ),
        ));
  }

  // 底部添加条
  // 查询、灭火药剂损耗没有底部条
  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),
              //color: GetConfig.getColor(theme),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "查看",
                    style: Theme.of(context).textTheme.headline2,
                  ),
                  Icon(
                    Icons.keyboard_arrow_right,
                    color: Colors.white,
                    size: 30.px,
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  // 查看
  void check(BuildContext context) {
    if (item == RouteItemFrontComponentConst.carLoad) {
      if (_selectVehicle == null) {
        FlutterToast.toastCenter('请选择车辆');
        return;
      }
      if (_addItems.length == 0) {
        FlutterToast.toastCenter('请添加设备');
        return;
      }
    }

    if (item == RouteItemFrontComponentConst.inStock) {
      if (_selectPosition == null) {
        FlutterToast.toastCenter('请选择位置');
        return;
      }
      if (_addItems.length == 0) {
        if (widget.routeModel.category ==
            RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
          FlutterToast.toastCenter('请添加灭火药剂');
        } else {
          FlutterToast.toastCenter('请添加设备');
        }

        return;
      }
    }
    if (item == RouteItemFrontComponentConst.scraped) {
      if (_selectReason == null) {
        FlutterToast.toastCenter('请选择原因');
        return;
      }
      if (_addItems.length == 0) {
        FlutterToast.toastCenter('请添加设备');
        return;
      }
    }

    final extension = {
      "extension": _addItems,
      "carId": _selectVehicle == null ? null : _selectVehicle["carId"],
      "reason": _selectReason == null ? null : _selectReason,
      "position": _selectPosition == null ? null : "$_selectPosition",
      "description":
          _positionDescription == null ? null : "$_positionDescription",
      "warehouseId": '0',
      "warehouseStructureId": _warehouseStructureId
    };

    var exten = json.encode(extension);
    final params = {
      "title": widget.routeModel.title,
      "category": category,
      "item": item,
      "extension": exten
    };
    // 销毁扫码
    removeScanListener();
    _controller?.dispose();
    _controller = null;
    Application.navigateToPath(context, Routes.offlineEquipmentAddList,
            params: params)
        .then((value) {
      getRSCamera();
      setState(() {
        if (value != null) {
          _addItems = value;
        } else {
          _addItems = [];
          _selectReason = null;
        }
      });
    });
  }

  // 根据不同的业务场景构建不同的视图

  // 选择位置
  Widget buildSelectItem(BuildContext context) {
    // 器材
    if (category == RouteCategoryFrontComponentConst.equipment) {
      // 入账
      if (item == "inStock") {
        return Align(
          alignment: Alignment(0, -0.6),
          child: InkWell(
            onTap: () async {
              // 请求位置信息
              // 模拟数据
//              String data = await rootBundle.loadString("assets/images/json/position.json");
//              List items = json.decode(data);
              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: this.theme,
                      data: items,
                      selectedModel: this.model,
                      noneSelect: () {
                        setState(() {
                          _selectPosition = null;
                        });
                      },
                      callback: (TreeNodeModel model) {
                        this.model = model;
                        setState(() {
                          _selectPosition = model.fullName ?? model.name;
                        });
                      },
                      confirm: (TreeNodeModel model) {
                        this.model = model;
                        // 选择位置描述
                        showEquipInStockDescription(context);
                        _warehouseStructureId = model.id;
                      },
                    );
                  });
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: buildPositionInfo(),
            ),
          ),
        );
      } else if (item == "scraped") {
        // 报废
        return Align(
          alignment: Alignment(0, -0.6),
          child: InkWell(
            onTap: () {
              showModalBottomSheet(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5.0)),
                  isScrollControlled: true,
                  context: context,
                  builder: (ctx) {
                    return SelectReasonDialog(
                      theme: theme,
                      requestReasons: reasons ?? [],
                      callback: (str) {
                        setState(() {
                          _selectReason = str;
                        });
                      },
                    );
                  });
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Image(
                  image: Svg("assets/images/icon_position.svg",
                      size: Size(20, 20)),
                ),
                SizedBox(
                  width: 5.px,
                ),
                ConstrainedBox(
                    constraints: BoxConstraints(maxWidth: 200),
                    child: Text(
                      "${_selectReason == null ? "选择原因" : _selectReason}",
                      style: TextStyle(fontSize: 14.px, color: Colors.white),
                    )),
              ],
            ),
          ),
        );
      } else {
        return Container();
      }
    } else if (category ==
        RouteCategoryFrontComponentConst.fireFightingVehicle) {
      if (item == RouteItemFrontComponentConst.carLoad) {
        return Align(
          alignment: Alignment(0, -0.6),
          child: InkWell(
            onTap: () {
              showModalBottomSheet(
                  isDismissible: false,
                  enableDrag: false,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.px)),
                  context: context,
                  builder: (BuildContext context) {
                    return VehicleModalDialog(
                      theme: this.theme,
                      vehicles:
                          Provider.of<SelectVehicleViewModel>(context).vehicles,
                      confirm: (res) => selectVehicleConfirm(context, res),
                    );
                  });
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: buildSelectedVehicle(),
            ),
          ),
        );
      } else if (item == RouteItemFrontComponentConst.scraped) {
        return Align(
          alignment: Alignment(0, -0.6),
          child: InkWell(
            onTap: () {
              showModalBottomSheet(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5.0)),
                  isScrollControlled: true,
                  context: context,
                  builder: (ctx) {
                    return SelectReasonDialog(
                      theme: theme,
                      requestReasons: reasons ?? [],
                      callback: (str) {
                        setState(() {
                          _selectReason = str;
                        });
                      },
                    );
                  });
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Image(
                  image: Svg("assets/images/icon_position.svg",
                      size: Size(20, 20)),
                ),
                SizedBox(
                  width: 5.px,
                ),
                ConstrainedBox(
                    constraints: BoxConstraints(maxWidth: 200),
                    child: Text(
                      "${_selectReason == null ? "选择原因" : _selectReason}",
                      style: TextStyle(fontSize: 14.px, color: Colors.white),
                    )),
              ],
            ),
          ),
        );
      } else {
        return Container();
      }
    } else if (category ==
        RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (item == "inStock") {
        return Align(
          alignment: Alignment(0, -0.6),
          child: InkWell(
            onTap: () async {
              // 请求位置信息
              // 模拟数据
//              String data = await rootBundle.loadString("assets/images/json/position.json");
//              List items = json.decode(data);
              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: this.theme,
                      data: items,
                      selectedModel: this.model,
                      noneSelect: () {
                        setState(() {
                          _selectPosition = null;
                        });
                      },
                      callback: (TreeNodeModel model) {
                        this.model = model;
                        setState(() {
                          _selectPosition = model.fullName ?? model.name;
                        });
                      },
                      confirm: (TreeNodeModel model) {
                        this.model = model;
                        // 选择位置描述
                        showEquipInStockDescription(context);
                        _warehouseStructureId = model.id;
                      },
                    );
                  });
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: buildPositionInfo(),
            ),
          ),
        );
      } else if (item == "extinguishWastage" || item == "extinguishLoad") {
        return Align(
          alignment: Alignment(0, -0.6),
          child: InkWell(
            onTap: () {
              showModalBottomSheet(
                  isDismissible: false,
                  enableDrag: false,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.px)),
                  context: context,
                  builder: (BuildContext context) {
                    return VehicleModalDialog(
                      theme: theme,
                      vehicles:
                          Provider.of<SelectVehicleViewModel>(context).vehicles,
                      confirm: (res) => selectVehicleConfirm(context, res),
                    );
                  });
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: buildSelectedVehicle(),
            ),
          ),
        );
      } else {
        return Container();
      }
    } else {
      return Container();
    }
  }

  // 显示位置描述
  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;
              });
            },
          );
        });
  }

  // 选择车辆
  List<Widget> buildSelectedVehicle() {
    return <Widget>[
      Image.asset(
        "assets/images/icon_scan_vehicle.png",
        width: 20.px,
        height: 20.px,
      ),
      SizedBox(
        width: 5.px,
      ),
      Text(
        _selectVehicle == null ? "选择车辆" : "${_selectVehicle["carNum"]}",
        style: TextStyle(fontSize: 14.px, color: Colors.white),
      ),
    ];
  }

  // 构建入账下选择位置信息
  List<Widget> buildPositionInfo() {
    if (_selectPosition == null) {
      return <Widget>[
        Image(
          image: Svg("assets/images/icon_position.svg", size: Size(20, 20)),
        ),
        SizedBox(
          width: 5.px,
        ),
        Text(
          "选择位置",
          style: TextStyle(fontSize: 14.px, color: Colors.white),
        ),
      ];
    } else {
      return <Widget>[
        Image(
          image: Svg("assets/images/icon_position.svg", size: Size(20, 20)),
        ),
        SizedBox(
          width: 5.px,
        ),
        ConstrainedBox(
            constraints: BoxConstraints(maxWidth: 200.px),
            child: Text(
              "$_selectPosition${_positionDescription?.trim() ?? ""}",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 14.px, color: Colors.white),
            )),
        SizedBox(
          width: 20.px,
        ),
        Icon(
          Icons.refresh,
          color: Colors.white,
        ),
        SizedBox(
          width: 2.px,
        ),
        Text(
          "重新选择",
          style: TextStyle(fontSize: 14.px, color: Colors.white),
        ),
      ];
    }
  }

  //获取闪光灯是否打开
  Future<bool> getFlashMode() async {
    bool isOpen = false;
    try {
      isOpen = await _controller.getFlashMode();
    } catch (_) {}
    return isOpen;
  }

//构建闪光灯按钮
  Widget _buildFlashBtn(BuildContext context, AsyncSnapshot<bool> snapshot) {
    return snapshot.hasData
        ? Padding(
            padding: EdgeInsets.only(
                bottom: 24 + MediaQuery.of(context).padding.bottom),
            child: SvgButton(
              src: snapshot.data
                  ? "assets/images/icon_splash_on.svg"
                  : "assets/images/icon_splash_off.svg",
              imageSize: 20.px,
              size: 50.px,
              onTap: () {
                if (snapshot.data) {
                  _controller.setFlashMode(false);
                } else {
                  _controller.setFlashMode(true);
                }
                setState(() {});
              },
            ),
          )
        : Container();
  }

  // Future<bool> canOpenCamera() async {
  //   var status = await Permission.camera.status;
  //   if (status != PermissionStatus.granted) {
  //     var future = await Permission.camera.request();
  //     return future.isGranted;
  //   } else {
  //     return true;
  //   }
  // }

  @override
  void dispose() {
    _controller?.dispose();
    _controller = null;
    super.dispose();
  }

  void getRSCamera() async {
    rScanCameras = await availableRScanCameras();
    //判断当前是否有可用相机
    if (rScanCameras != null && rScanCameras.length > 0) {
      //初始化相机控制器，一般rScanCameras[0]为后置，rScanCameras[1]为前置摄像头
      _controller = RScanCameraController(
          rScanCameras[0], RScanCameraResolutionPreset.high)
        ..initialize().then((_) {
          //初始化相机
          if (!mounted) {
            return;
          }
          // 添加扫码监听
          addScanListener();
          setState(() {});
        });
    }
  }

  // 添加扫码监听
  void addScanListener() {
    if (_controller != null) {
      _controller.addListener(() {
        if (scanning) return;
        removeScanListener();
        final result = _controller.result;
        if (result != null) {
          scanning = true;
          print("----------------------------");
          print(result.message);
          print("----------------------------");
          checkQRScanResult(context, result.message);
        }
      });
    }
  }

  // 移除扫码监听
  void removeScanListener() {
    if (_controller != null) {
      _controller.removeListener(() {});
    }
  }

  // 重新开始扫码
  void restartScanning(int seconds, {bool pop = true}) {
    // if (pop) Navigator.of(context).pop();
    Future.delayed(Duration(seconds: seconds), () {
      addScanListener();
      scanning = false;
    });
  }

  // 选择车辆后确认
  void selectVehicleConfirm(context, res) {
    setState(() {
      _selectVehicle = res;
    });

    if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      // 装载选择车之后需要选择位置页面
      // 损耗
      if (item == RouteItemFrontComponentConst.extinguishWastage) {
        final params = {
          "category": category, // 分类
          "item": item, // 子项
          "title": "${_selectVehicle["carNum"]}",
          "extension": "${json.encode(_selectVehicle)}"
        };
        _controller?.dispose();
        _controller = null;
        Application.navigateToPath(context, Routes.offlineCommonAddFireAgent,
                params: params)
            .then((value) {
          // if(value==null){
          //   setState(() {
          //     _selectVehicle = res;
          //   });
          // }
          getRSCamera();
          restartScanning(3);
        });
      }
      // 装载
      else if (item == RouteItemFrontComponentConst.extinguishLoad) {
        final params = {
          "category": category, // 分类
          "item": item, // 子项
          "title": "装载${_selectVehicle["carNum"]}",
          "extension": json.encode(_selectVehicle)
        };
        _controller?.dispose();
        _controller = null;
        Application.navigateToPath(context, Routes.offlineFireAgentInStock,
                params: params)
            .then((value) {
          // if(value==null){
          //   setState(() {
          //     _selectVehicle = null;
          //   });
          // }

          getRSCamera();
          restartScanning(3);
        });
      }
    }
  }

  // 扫码查询信息处理
  void checkQRScanResult(BuildContext context, String message) {
    // 仓库id为获取到
    // if (warehouseId == null) {
    //   FlutterToast.toastCenter(ToastMessage.notWarehouseId);
    //   restartScanning(3);
    //   return;
    // }

    // 扫码通用参数
    final params = {"qrCode": message, "warehouseId": warehouseId};

    if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
      // 装载 / 卸载
      if (item == RouteItemFrontComponentConst.carLoad) {
      } else if (item == RouteItemFrontComponentConst.carUnLoad) {
        if (!message.startsWith(QRType.equipmentPrefix)) {
          FlutterToast.toastCenter(ToastMessage.errorTypeQR);
          restartScanning(3, pop: false);
          return;
        }
      } else {
        if (!message.startsWith(QRType.fireFightingVehiclePrefix)) {
          FlutterToast.toastCenter(ToastMessage.errorVehicleTypeQR);
          restartScanning(3, pop: false);
          return;
        }
      }

      // 车辆装载
      if (item == RouteItemFrontComponentConst.carLoad) {
        if (message.startsWith(QRType.fireFightingVehiclePrefix)) {
          getOfflineCarDetal(message).then((value) {
            if (value == null) {
              FlutterToast.toastCenter(ToastMessage.errorVehicleTypeQR);
              restartScanning(3);
              return;
            }
            if (value.Status == '7') {
              FlutterToast.toastCenter("报废车辆不能装载！");
              restartScanning(3);
              return;
            }
            CarScanModel carmodel = value;
            Map<String, dynamic> data = {
              "carId": carmodel.carId,
              "carNum": carmodel.carNum
            };
            setState(() {
              _selectVehicle = data;
            });
            EquipmentToast.show(context, carModel: carmodel);
          });
        } else {
          getOfflineEquipment('21', qrCode: message).then((value) {
            if (value == null) {
              FlutterToast.toastCenter(ToastMessage.errorTypeQR);
              restartScanning(3);
              return;
            }
            if (value.equipCategoryCode[0] == '4') {
              FlutterToast.toastCenter("请扫描装备二维码");
              restartScanning(3);
              return;
            }
            if (value.status != '在位') {
              FlutterToast.toastCenter("非在位装备不能装载！");
              restartScanning(3);
              return;
            }
            EquipmentScanModel model = value;

            //EquipmentScanModel.fromJson(res["result"]["equipment"]);

            for (EquipmentScanModel item in _addItems) {
              if (item.qrCode == model.qrCode) {
                FlutterToast.toastCenter(ToastMessage.alreadyAdd);
                restartScanning(3);
                return;
              }
            }
            // 添加到列表中
            setState(() {
              _addItems.add(model);
            });
            // 展示Toast
            EquipmentToast.show(context, equipModel: model);
          });
        }
        restartScanning(3);
      }
      // 车辆卸载
      else if (item == RouteItemFrontComponentConst.carUnLoad) {
        getOfflineEquipment('22', qrCode: message).then((value) {
          if (value == null) {
            FlutterToast.toastCenter(ToastMessage.errorTypeQR);
            restartScanning(3);
            return;
          }
          if (value.equipCategoryCode[0] == '4') {
            FlutterToast.toastCenter("请扫描装备二维码");
            restartScanning(3);
            return;
          }
          if (value.status != '车载') {
            FlutterToast.toastCenter("装备不是车载状态不能卸载！");
            restartScanning(3);
            return;
          }
          EquipmentScanModel model = value;

          // EquipmentScanModel.fromJson(res["result"]["equipment"]);
          for (EquipmentScanModel item in _addItems) {
            if (item.qrCode == model.qrCode) {
              FlutterToast.toastCenter(ToastMessage.alreadyAdd);
              restartScanning(3);
              return;
            }
          }
          // 添加到列表中
          setState(() {
            _addItems.add(model);
          });
          // 展示Toast
          EquipmentToast.show(context, equipModel: model);
        });

        restartScanning(5);
        //   } else {
        //     restartScanning(3);
        //   }
        // }).catchError((e) {
        //   restartScanning(3);
        // });
      }
      // 车辆保养
      else if (item == RouteItemFrontComponentConst.maintain ||
          item == RouteItemFrontComponentConst.repair ||
          item == RouteItemFrontComponentConst.repaired ||
          item == RouteItemFrontComponentConst.scraped) {
        // showDialog(
        //     context: context,
        //     builder: (ctx) {
        //       return LoadingDialog(
        //         barrierDismissible: true,
        //       );
        //     });
        // 二维码扫码类型
        // String qrTypeParam = QueryQRType.queryQRType(category, item);
        // HttpRequest.queryQRInfo(qrTypeParam, params: params).then((res) {
        //   if (res["status"] == 200) {
        getOfflineCarDetal(message).then((value) async {
          if (value == null) {
            FlutterToast.toastCenter(ToastMessage.errorVehicleTypeQR);
            restartScanning(3);
            return;
          }
          if (item == RouteItemFrontComponentConst.maintain) {
            if (value.Status != '1') {
              FlutterToast.toastCenter("非在位状态不能保养！");
              restartScanning(3);
              return;
            }
          }
          if (item == RouteItemFrontComponentConst.repair) {
            if (value.Status != '1') {
              FlutterToast.toastCenter("非在位状态不能维修！");
              restartScanning(3);
              return;
            }
            if (value.Status != '1') {
              FlutterToast.toastCenter("非在位状态不能维修！");
              restartScanning(3);
              return;
            }
          }
          if (item == RouteItemFrontComponentConst.repaired) {
            if (value.Status != '3') {
              FlutterToast.toastCenter("非维修状态不能维修完成！");
              restartScanning(3);
              return;
            }
          }
          if (item == RouteItemFrontComponentConst.scraped) {
            if (value.Status == '3' ||
                value.Status == '1' ||
                value.Status == '6') {
            } else {
              FlutterToast.toastCenter("车辆不可报废！");
              restartScanning(3);
              return;
            }
            var sql = new StringBuffer();
            sql.write("select ");
            sql.write("* ");
            sql.write("from EquipmentOnCar where carId = ${value.carId} ");
            print(sql.toString());
            List<Map<String, dynamic>> lst =
                await dbAccess().queryData(sql.toString());
            if (lst.length > 0) {
              FlutterToast.toastCenter("车辆不可报废！");
              restartScanning(3);
              return;
            }
          }
          CarScanModel model = value;
          for (CarScanModel item in _addItems) {
            if (item.qrCode == model.qrCode) {
              FlutterToast.toastCenter(ToastMessage.alreadyAdd);
              restartScanning(3);
              return;
            }
          }
          // 添加到列表中
          setState(() {
            _addItems.add(model);
          });
          // 展示Toast
          EquipmentToast.show(context, carModel: model);
        });
        restartScanning(5);
        //   } else {
        //     restartScanning(3);
        //   }
        // }).catchError((e) {
        //   restartScanning(3);
        // });
      }
    }
    // 器材
    // 和车辆部分逻辑重叠，为了可扩展性单独分类
    else if (category == RouteCategoryFrontComponentConst.equipment) {
      // if (item == RouteItemFrontComponentConst.inStock) {
      // if (_selectPosition == null) {
      //   FlutterToast.toastCenter(ToastMessage.notSelectPosition);
      //   restartScanning(3, pop: false);
      //   return;
      // }
      //}
      // if (item == RouteItemFrontComponentConst.scraped) {
      //   if (_selectReason == null) {
      //     FlutterToast.toastCenter(ToastMessage.notSelectReason);
      //     restartScanning(3, pop: false);
      //     return;
      //   }
      // }
      if (!message.startsWith(QRType.equipmentPrefix)) {
        FlutterToast.toastCenter(ToastMessage.errorTypeQR);
        restartScanning(3);
        return;
      }

      // showDialog(
      //     context: context,
      //     builder: (ctx) {
      //       return LoadingDialog(
      //         barrierDismissible: true,
      //       );
      //     });
      getOfflineEquipment('10', qrCode: message).then((model) {
        if (model == null) {
          FlutterToast.toastCenter(ToastMessage.errorTypeQR);
          restartScanning(3);
          return;
        }
        if (model.equipCategoryCode[0] == '4') {
          FlutterToast.toastCenter("请扫描装备二维码");
          restartScanning(3);
          return;
        }
        if (item == RouteItemFrontComponentConst.inStock) {
          if (model.status != '未入库') {
            FlutterToast.toastCenter("装备已入库！");
            restartScanning(3);
            return;
          }
        } else if (item == RouteItemFrontComponentConst.maintain) {
          if (model.status != '在位') {
            FlutterToast.toastCenter("装备不是在位状态不能保养！");
            restartScanning(3);
            return;
          }
        } else if (item == RouteItemFrontComponentConst.repair) {
          if (model.status != '在位') {
            FlutterToast.toastCenter("装备不是在位状态不能维修！");
            restartScanning(3);
            return;
          }
        } else if (item == RouteItemFrontComponentConst.repaired) {
          if (model.status != '维修') {
            FlutterToast.toastCenter("装备不是维修状态不能进行该操作！");
            restartScanning(3);
            return;
          }
        } else if (item == RouteItemFrontComponentConst.scraped) {
          if (model.status == '在位' || model.status == '维修') {
          } else {
            FlutterToast.toastCenter("该装备不能进行报废！");
            restartScanning(3);
            return;
          }
        }
        for (EquipmentScanModel item in _addItems) {
          if (item.qrCode == model.qrCode) {
            FlutterToast.toastCenter(ToastMessage.alreadyAdd);

            return;
          }
        }
        if (item == RouteItemFrontComponentConst.inStock &&
            !model.singleOrDouble) {
          addInStock(context, model);
        } else {
          if (item == RouteItemFrontComponentConst.inStock) {
            model.amount = '1';
          }
          setState(() {
            _addItems.add(model);
          });
          // 展示Toast
          EquipmentToast.show(context,
              equipModel: model,
              position: "$_selectPosition${_positionDescription ?? ""}");
        }
      });
      restartScanning(3);
      // // 二维码扫码类型
      // String qrTypeParam = QueryQRType.queryQRType(category, item);
      //
      // HttpRequest.queryQRInfo(qrTypeParam, params: params).then((res) {
      //   if (res["status"] == 200) {
      //     restartScanning(5);
      //     EquipmentScanModel model =
      //     EquipmentScanModel.fromJson(res["result"]["equipment"]);

      //     // 添加到列表中
      //
      //   } else {
      //     restartScanning(3);
      //   }
      // }).catchError((e) {
      //   restartScanning(3);
      // });
    } else if (category ==
        RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (!message.startsWith(QRType.fireFightingVehiclePrefix) &&
          item != RouteItemFrontComponentConst.inStock) {
        FlutterToast.toastCenter(ToastMessage.errorVehicleTypeQR);
        restartScanning(3);
        return;
      }
      //String code = QueryQRType.queryQRType(category, item);

      // showDialog(
      //     context: context,
      //     builder: (ctx) {
      //       return LoadingDialog(
      //         barrierDismissible: true,
      //       );
      //     });
      // HttpRequest.queryQRInfo(code, params: params).then((res) {
      //   //Navigator.of(context).pop();
      //   if (res["status"] == 200) {
      if (item == RouteItemFrontComponentConst.inStock) {
        getOfflineEquipment('31', qrCode: message).then((model) {
          if (model == null) {
            FlutterToast.toastCenter(ToastMessage.errorTypeQR);
            restartScanning(3);
            return;
          }
          if (model.equipCategoryCode[0] != '4') {
            FlutterToast.toastCenter("请扫描灭火药剂二维码");
            restartScanning(3);
            return;
          }
          //model.amount=0;
          restartScanning(5, pop: false);
          addInStock(context, model);
        });
      } else {
        getOfflineCarDetal(message).then((value) {
          if (value == null) {
            FlutterToast.toastCenter(ToastMessage.errorVehicleTypeQR);
            restartScanning(3);
            return;
          }
          CarScanModel model = value;
          // 展示Toast
          EquipmentToast.show(context, carModel: model);
          restartScanning(5, pop: false);

          Map<String, dynamic> data = {
            "carId": model.carId,
            "carNum": model.carNum
          };
          selectVehicleConfirm(context, data);
        });
      }

      restartScanning(3);
      // }
      // }).catchError((e) {
      //   restartScanning(3);
      // });
    }
  }

  void addInStock(BuildContext context, EquipmentScanModel it) {
    showDialog(
        context: context,
        builder: (ctx) {
          return AddCountDialog(
            theme: theme,
            until: it.unit,
            callback: (value) {
              if (double.parse(value) == 0) {
                FlutterToast.toastCenter("数量不能为空");
                return;
              }
              it.amount = double.parse(value);
              if (isExistItems(it.equipmentDetailId) &&
                  widget.routeModel.category ==
                      RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
                add_addItemList(it, value);
              } else {
                setState(() {
                  _addItems.add(it);
                });
              }
              if (widget.routeModel.category ==
                  RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
                EquipmentToast.show(context, fireAgentModel: it);
              } else {
                EquipmentToast.show(context,
                    equipModel: it,
                    position: "$_selectPosition${_positionDescription ?? ""}");
              }
            },
          );
        });
  }

  //车辆详情查询跳转
  // getCarDel(BuildContext context, String carid) async {
  //   Future.delayed(Duration.zero, () {
  //     HttpRequest.getCarDel(carid).then((res) {
  //       // Navigator.of(context).pop();
  //       restartScanning(3);
  //       if (res["status"] == 200) {
  //         // BasicBean bean = BasicBean.fromJson(res["result"]);
  //         _controller?.dispose();
  //         _controller = null;
  //         final params = {
  //           "title": "车辆详情",
  //           "category": '3',
  //           "item": item ?? "",
  //           "extension": json.encode(res["result"])
  //         };
  //
  //         Application.navigateToPath(context, Routes.vehicleHomePage,
  //             params: params)
  //             .then((value) {
  //           getRSCamera();
  //         });
  //       } else {
  //         Navigator.of(context).pop();
  //         FlutterToast.toastCenter(res['message']);
  //       }
  //     }).catchError((_) {
  //       Navigator.of(context).pop();
  //       FlutterToast.toastCenter('请重新扫码');
  //     });
  //   });
  // }

  //装备详情查询跳转
  // getEquipmentDel(BuildContext context, String carid) async {
  //   Future.delayed(Duration.zero, () {
  //     HttpRequest.getEquipDel(carid).then((res) {
  //       restartScanning(3);
  //       if (res["status"] == 200) {
  //         _controller?.dispose();
  //         _controller = null;
  //
  //         final params = {
  //           "title": "装备详情",
  //           "category": '1',
  //           "item": item ?? "",
  //           "extension": json.encode(res["result"])
  //         };
  //
  //         Application.navigateToPath(context, Routes.vehicleHomePage,
  //             params: params)
  //             .then((value) {
  //           getRSCamera();
  //         });
  //       } else {
  //         restartScanning(3);
  //         Navigator.of(context).pop();
  //         FlutterToast.toastCenter(res['message']);
  //       }
  //     }).catchError((_) {
  //       restartScanning(3);
  //       Navigator.of(context).pop();
  //       FlutterToast.toastCenter('请重新扫码');
  //     });
  //   });
  // }
  void entryCode(context) {
    // 销毁二维码识别
    _controller?.dispose();
    _controller = null;

    showDialog(
        context: context,
        builder: (ctx) {
          return PinTextDialog(
            theme: theme,
            callback: (value) {
              if (_controller == null) {
                getRSCamera();
              }
              String code;
              String category = this.category;
              String item = this.item;

              // 灭火药剂装载损耗扫码的都是车辆
              if (category ==
                  RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
                if (item == RouteItemFrontComponentConst.extinguishWastage ||
                    item == RouteItemFrontComponentConst.extinguishLoad) {
                  code = "${QRType.fireFightingVehiclePrefix}$value";
                } else if (item == RouteItemFrontComponentConst.inStock) {
                  code = "${QRType.equipmentPrefix}$value";
                }
              }
              // 消防车辆
              else if (category ==
                  RouteCategoryFrontComponentConst.fireFightingVehicle) {
                if (item == RouteItemFrontComponentConst.carLoad ||
                    item == RouteItemFrontComponentConst.carUnLoad) {
                  //输入车辆二维码

                  code = "${QRType.equipmentPrefix}$value";
                } else {
                  code = "${QRType.fireFightingVehiclePrefix}$value";
                }
              }
              // 器材
              else if (category == RouteCategoryFrontComponentConst.equipment) {
                code = "${QRType.equipmentPrefix}$value";
              }

              checkQRScanResult(context, code);
            },
            cancel: () {
              getRSCamera();
            },
          );
        });
  }
}

class ScanImageView extends StatefulWidget {
  final Widget child;
  final String theme;

  const ScanImageView({Key key, this.child, this.theme}) : super(key: key);

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

class _ScanImageViewState extends State<ScanImageView>
    with TickerProviderStateMixin {
  AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
        vsync: this, duration: Duration(milliseconds: 1000));
    controller.repeat(reverse: true);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
        animation: controller,
        builder: (BuildContext context, Widget child) => CustomPaint(
              foregroundPainter: _ScanPainter(
                context,
                controller.value,
                GetConfig.getColor(widget.theme),
                GetConfig.getColor(widget.theme),
                theme: widget.theme,
              ),
              child: widget.child,
              willChange: true,
            ));
  }
}

class _ScanPainter extends CustomPainter {
  final double value;
  final Color borderColor;
  final Color scanColor;
  final BuildContext context;
  final String theme;

  _ScanPainter(this.context, this.value, this.borderColor, this.scanColor,
      {this.theme});

  Paint _paint;

  @override
  void paint(Canvas canvas, Size size) {
    if (_paint == null) {
      initPaint();
    }
    double width = size.width;
    double height = size.height;

    double boxWidth = size.width * 2 / 4;
    double boxHeight = height / 4;

    double left = (width - boxWidth) / 2;
    double top = boxHeight;
    double bottom = boxHeight * 2;
    double right = left + boxWidth;
    _paint.color = borderColor;
    final rect = Rect.fromLTWH(left, top, boxWidth, boxHeight);
    canvas.drawRect(rect, _paint);

    _paint.strokeWidth = 5;

    Path path1 = Path()
      ..moveTo(left, top + 12)
      ..lineTo(left, top)
      ..lineTo(left + 12, top);
    canvas.drawPath(path1, _paint);
    Path path2 = Path()
      ..moveTo(left, bottom - 12)
      ..lineTo(left, bottom)
      ..lineTo(left + 12, bottom);
    canvas.drawPath(path2, _paint);
    Path path3 = Path()
      ..moveTo(right, bottom - 12)
      ..lineTo(right, bottom)
      ..lineTo(right - 12, bottom);
    canvas.drawPath(path3, _paint);
    Path path4 = Path()
      ..moveTo(right, top + 12)
      ..lineTo(right, top)
      ..lineTo(right - 12, top);
    canvas.drawPath(path4, _paint);

    _paint.color = scanColor;

    final scanRect = Rect.fromLTWH(
        left + 10, top + 10 + (value * (boxHeight - 20)), boxWidth - 20, 1);

    _paint.shader = LinearGradient(colors: <Color>[
      GetConfig.getColor(theme).withOpacity(0.54),
      GetConfig.getColor(theme),
      GetConfig.getColor(theme).withOpacity(0.54),
    ], stops: [
      0.0,
      0.5,
      1,
    ]).createShader(scanRect);
    canvas.drawRect(scanRect, _paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }

  void initPaint() {
    _paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;
  }
}
