import 'dart:convert';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/entity/platform_menu.dart';
import 'package:base/routes/routes.dart' as base_routes;
import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/consts/qr_type_consts.dart';
import 'package:base/consts/route_category_front_component_const.dart';
import 'package:base/consts/share_prefers_key_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_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/utils/query_qr_type.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/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/loading_dialog.dart';
import 'package:base/widgets/pin_text_dialog.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:get/get.dart';
import 'package:provider/provider.dart';
import 'package:r_scan/r_scan.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../model/car_scan_model.dart';
import '../model/equipment_scan_model.dart';
import 'package:base/model/select_vehicle_view_model.dart';
import '../routes/routes.dart';
import '../utils/equipment_toast.dart';

///装备页面入口
class EquipWareHousing extends StatelessWidget {
  RouteModel routeModel;

  ///修改时间：2021年10月13日14:23:14
  ///将RouteModel参数转化成GexX的arguments
  EquipWareHousing({this.routeModel}) {
    PlatformMenu platformMenu = Get.arguments;
    routeModel ??= RouteModel(
        category: platformMenu.parentFrontComponent ?? '',
        title: platformMenu.permissionName ?? '',
        item: platformMenu.frontComponent ?? '');
  }

  @override
  Widget build(BuildContext context) {
    return EquipWareHousingContent(routeModel);
  }
}

class EquipWareHousingContent extends StatefulWidget {
  final RouteModel routeModel;

  const 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;
  String _selectReason;
  String theme = '';

  @override
  void initState() {
    super.initState();
    initThemeConfig();
    getData();
    category = widget.routeModel.category;
    item = widget.routeModel.item;
    warehouseId = Provider.of<WarehouseInfoViewModel>(context, listen: false).warehouseInfoModel?.warehouse?.id;
    getRSCamera();
  }

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

  /// 获取选择的部门
  Future<void> getData() async {
    HttpRequest.getSelectCompany().then((result) {
      if (result['status'] == 200) {
        var _result = result['result'];
        List companys = _result['companys'];
        Map companyDepartments = _result['companyDepartments'];
        Map orgRoles = _result['orgRoles'];
        if (companys.length == 1 &&
            companyDepartments.values.toList().length == 1 &&
            orgRoles.values.toList().length == 1) {
          var _company = companys[0];
          var _department = companyDepartments.values.toList()[0].toList().length == 1
              ? companyDepartments.values.toList()[0][0]
              : {};
          var _role = orgRoles.values.toList()[0][0];
          confirm(context, _company, _department, _role);
        } else {
          Application.navigateToPath(context, base_routes.Routes.selectCompanyRole,
              params: {'extension': json.encode(_result)}).then((companyModel) {
            getCompanyInfo(companyModel['orgCode'].toString());
          });
        }
      }
    }).catchError((_) {});
  }

  void confirm(context, _company, _department, _role) {
    if (_company == null || _role == null) {
      FlutterToast.toastCenter('角色异常请联系管理员!');
      return;
    }
    showDialog(
        context: context,
        builder: (ctx) {
          return LoadingDialog(
            barrierDismissible: true,
          );
        });
    // 处理数据
    // 后台解析数据有问题，需前端处理
    _company['children'] = [];
    if (_department != null) {
      _department['children'] = [];
    }
    _role['children'] = [];
    final params = {'companyModel': _company, 'departmentModel': _department, 'roleModel': _role};
    HttpRequest.saveCurCompany(params: params).then((res) async {
      Navigator.of(context).pop();
      if (res['status'] == 200) {
        final result = res['result'];
        final companyModel = result['companyModel'];
        final departmentModel = result['departmentModel'];
        final roleModel = result['roleModel'];
        SharedPreferences prefer = await SharedPreferences.getInstance();
        prefer.setString(SharePrefersKey.companyModelKey, json.encode(companyModel));
        prefer.setString('sel_dept', json.encode(departmentModel));
        prefer.setString('sel_role', json.encode(roleModel));
        getCompanyInfo(companyModel['orgCode'].toString());
      } else {
        shortMessage('接口请求失败!');
      }
    });
  }

  ///获取公司信息
  void getCompanyInfo(String companyOrgCode) {
    Future.delayed(Duration.zero, () async {
      HttpRequest.getWarehouseInfo(companyOrgCode).then((value) {
        if (value['result'] == null) {
          AmosToast.show('仓库信息返回为空！', context);
          return;
        }
        if (value['status'] == 200) {
          try {
            final model = WarehouseInfoModel.fromJson(value['result']);
            Provider.of<WarehouseInfoViewModel>(context, listen: false).warehouseInfoModel = model;
            if (category == RouteCategoryFrontComponentConst.equipment) {
              if (item == 'inStock') {
                getWarehousePosition(context);
              } else if (item == RouteItemFrontComponentConst.scraped) {
                getScrapReason();
              }
            } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
              if (item == 'inStock') {
                getWarehousePosition(context);
              } else if (item == RouteItemFrontComponentConst.extinguishWastage ||
                  item == RouteItemFrontComponentConst.extinguishLoad) {
                // 损耗获取车辆列表
                getWasteCarList(context);
              }
            } else if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
              if (item == RouteItemFrontComponentConst.carLoad) {
                getWasteCarList(context);
              } else if (item == RouteItemFrontComponentConst.scraped) {
                getScrapReason();
              }
            }
          } catch (e) {
            print(e);
          }
        } else {
          ToastUtils.showToast('响应码异常');
        }
      }).catchError((e) {
        print(e);
      });
    });
  }

  /// 判断是否存在列表中
  bool isExistItems(id) {
    if (_addItems.isEmpty) return false;
    bool isExists = false;
    for (final EquipmentScanModel model in _addItems) {
      if (model.equipmentDetailId.toString() == id.toString()) {
        isExists = true;
      }
    }
    return isExists;
  }

  ///添加同类型灭火药剂只增加数量
  void addAddItemList(it, value) {
    double amous;
    for (int i = 0; i < _addItems.length; i++) {
      EquipmentScanModel element = _addItems[i];
      if (element.equipmentDetailId.toString() == it.equipmentDetailId.toString()) {
        amous = double.parse(element.amount.toString()) + double.parse(value);
        element.amount = amous;
      }
    }
  }

  /// 获取原因
  Future<void> getScrapReason() 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 = res['result'];
        }
      }).catchError((_) {
        Navigator.of(context).pop();
      });
    });
  }

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

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

  @override
  Widget build(BuildContext context) {
    //判断是否有可用相机
    if (rScanCameras == null || rScanCameras.isEmpty) {
      return Scaffold(
        body: Container(
          alignment: Alignment.center,
          child: const 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 = '装备';
    }
    return Scaffold(
        appBar: AppBar(
          titleSpacing: 0,
          leading: LeadingButton(
            onWillScope: true,
            onWillPop: () {
              if (_addItems.isNotEmpty) {
                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: const TextStyle(color: Colors.white),
          ),
          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: const Svg('assets/images/icon_entry_code.svg', size: Size(16, 16)),
                                color: GetConfig.getColor(theme),
                              ),
                            ),
                            SizedBox(
                              width: 3.px,
                            ),
                            Text(
                              item == RouteItemFrontComponentConst.carLoad ? '输入装备编码' : '输入编码',
                              style: const TextStyle(color: Colors.white),
                            ),
                            SizedBox(
                              width: 10.rpx,
                            )
                          ],
                          crossAxisAlignment: CrossAxisAlignment.center,
                        )
                      ],
                    ),
                  )
          ],
        ),
        body: Scaffold(
          backgroundColor: Colors.black,
          body: Stack(
            children: <Widget>[
              ScanImageView(
                theme: theme,
                child: RScanCamera(_controller),
              ),
              //闪光灯
              Align(
                  alignment: const Alignment(0, -0.05),
                  child: FutureBuilder(
                    future: getFlashMode(),
                    builder: _buildFlashBtn,
                  )),
              Align(
                  alignment: const Alignment(0, 0.08),
                  child: Text(
                    '请对准' + titleew + '二维码',
                    style: const TextStyle(color: Colors.white),
                  )),
              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: Theme.of(context).primaryColor,
        padding: EdgeInsets.only(left: 16.px, right: 5.px),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              '已添加:  ${_addItems.length}',
              style: const TextStyle(color: Colors.white),
            ),
            FlatButton(
              padding: EdgeInsets.zero,
              onPressed: () => check(context),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  const Text(
                    '查看',
                    style: TextStyle(color: Colors.white),
                  ),
                  Icon(
                    Icons.keyboard_arrow_right,
                    color: Colors.white,
                    size: 30.px,
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

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

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

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

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

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

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

  /// 选择位置
  Widget buildSelectItem(BuildContext context) {
    // 器材
    if (category == RouteCategoryFrontComponentConst.equipment) {
      // 入账
      if (item == 'inStock') {
        return Align(
          alignment: const Alignment(0, -0.6),
          child: InkWell(
            onTap: () async {
              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: 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: const 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>[
                const Image(
                  image: Svg('assets/images/icon_position.svg', size: Size(20, 20)),
                ),
                SizedBox(
                  width: 5.px,
                ),
                ConstrainedBox(
                    constraints: const BoxConstraints(maxWidth: 200),
                    child: Text(
                      '${_selectReason ?? '选择原因'}',
                      style: TextStyle(fontSize: 14.px, color: Colors.white),
                    )),
              ],
            ),
          ),
        );
      } else {
        return Container();
      }
    } else if (category == RouteCategoryFrontComponentConst.fireFightingVehicle) {
      if (item == RouteItemFrontComponentConst.carLoad) {
        return Align(
          alignment: const 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 if (item == RouteItemFrontComponentConst.scraped) {
        return Align(
          alignment: const 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>[
                const Image(
                  image: Svg('assets/images/icon_position.svg', size: Size(20, 20)),
                ),
                SizedBox(
                  width: 5.px,
                ),
                ConstrainedBox(
                    constraints: const BoxConstraints(maxWidth: 200),
                    child: Text(
                      '${_selectReason ?? '选择原因'}',
                      style: TextStyle(fontSize: 14.px, color: Colors.white),
                    )),
              ],
            ),
          ),
        );
      } else {
        return Container();
      }
    } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (item == 'inStock') {
        return Align(
          alignment: const Alignment(0, -0.6),
          child: InkWell(
            onTap: () async {
              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: 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: const 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: theme,
            callback: (str) {
              setState(() {
                //str.graphemeClusters.removeLast();
                _positionDescription = str;
              });
            },
          );
        });
  }

  /// 选择车辆
  List<Widget> buildSelectedVehicle() {
    return <Widget>[
      Image.asset(
        'assets/images/icon_scan_vehicle.png',
        package: ExternalAssetsPackageKey.BASE,
        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>[
        const 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>[
        const 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,
        ),
        const 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();
  }

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

  Future<void> getRSCamera() async {
    rScanCameras = await availableRScanCameras();
    //判断当前是否有可用相机
    if (rScanCameras != null && rScanCameras.isNotEmpty) {
      //初始化相机控制器，一般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.commonAddFireAgent, 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.fireAgentInStock, 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, pop: false);
      return;
    }
    // 扫码通用参数
    final params = {'qrCode': message, 'warehouseId': warehouseId};
    // 全局扫码
    if (category == RouteCategoryFrontComponentConst.query) {
      // 查询仓库id
      final params = {'qrCode': message, 'warehouseId': warehouseId};
      showDialog(
          context: context,
          builder: (ctx) {
            return LoadingDialog(
              barrierDismissible: true,
            );
          });
      if (message.startsWith('01#')) {
        getEquipmentDel(context, message.substring(3));
      } else {
        HttpRequest.queryQRInfo(QRType.qrGlobal, params: params).then((res) {
          restartScanning(5);
          if (res['status'] == 200) {
            final result = res['result'];
            String type = result['type'];
            // 车辆详情
            if (type == 'car') {
              getCarDel(context, result['car']['carId']);
            }
          } else {
            // restartScanning(5);
            //FlutterToast.toastCenter(res['message']);
          }
        }).catchError((e) {
          restartScanning(5);
          FlutterToast.toastCenter('请重新扫码');
        });
      }
    }
    // 车辆
    else 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) {
        showDialog(
            context: context,
            builder: (ctx) {
              return LoadingDialog(
                barrierDismissible: true,
              );
            });
        HttpRequest.queryQRInfo(QRType.car_load, params: params).then((res) {
          restartScanning(3);
          if (res['status'] == 200) {
            if (message.startsWith(QRType.fireFightingVehiclePrefix)) {
              CarScanModel carmodel = CarScanModel.fromJson(res['result']['car']);
              Map<String, dynamic> data = {'carId': carmodel.carId, 'carNum': carmodel.carNum};
              setState(() {
                _selectVehicle = data;
              });
              EquipmentToast.show(context, carModel: carmodel);
            } else {
              EquipmentScanModel model = EquipmentScanModel.fromJson(res['result']['equipment']);

              for (final EquipmentScanModel item in _addItems) {
                if (item.qrCode == model.qrCode) {
                  FlutterToast.toastCenter(ToastMessage.alreadyAdd);
                  return;
                }
              }
              // 添加到列表中
              setState(() {
                _addItems.add(model);
              });
              // 展示Toast
              EquipmentToast.show(context, equipModel: model);
            }
          } else {
            //FlutterToast.toastCenter(res['message']);
          }
        }).catchError((e) {
          restartScanning(5);
          FlutterToast.toastCenter('请重新扫码');
        });
      }
      // 车辆卸载
      else if (item == RouteItemFrontComponentConst.carUnLoad) {
        showDialog(
            context: context,
            builder: (ctx) {
              return LoadingDialog(
                barrierDismissible: true,
              );
            });
        HttpRequest.queryQRInfo(QRType.car_uninstall, params: params).then((res) {
          restartScanning(3);
          if (res['status'] == 200) {
            EquipmentScanModel model = EquipmentScanModel.fromJson(res['result']['equipment']);
            for (final EquipmentScanModel item in _addItems) {
              if (item.qrCode == model.qrCode) {
                FlutterToast.toastCenter(ToastMessage.alreadyAdd);

                return;
              }
            }
            // 添加到列表中
            setState(() {
              _addItems.add(model);
            });
            // 展示Toast
            EquipmentToast.show(context, equipModel: model);
          } else {
            // FlutterToast.toastCenter(res['message']);
          }
        }).catchError((e) {
          restartScanning(5);
          FlutterToast.toastCenter('请重新扫码');
        });
      }
      // 车辆保养
      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) {
          restartScanning(3);
          if (res['status'] == 200) {
            CarScanModel model = CarScanModel.fromJson(res['result']['car']);
            for (final CarScanModel item in _addItems) {
              if (item.qrCode == model.qrCode) {
                FlutterToast.toastCenter(ToastMessage.alreadyAdd);
                return;
              }
            }
            // 添加到列表中
            setState(() {
              _addItems.add(model);
            });
            // 展示Toast
            EquipmentToast.show(context, carModel: model);
          } else {
            //FlutterToast.toastCenter(res['message']);
          }
        }).catchError((e) {
          restartScanning(5);
          FlutterToast.toastCenter('请重新扫码');
        });
      }
    }
    // 器材
    // 和车辆部分逻辑重叠，为了可扩展性单独分类
    else if (category == RouteCategoryFrontComponentConst.equipment) {
      if (!message.startsWith(QRType.equipmentPrefix)) {
        FlutterToast.toastCenter(ToastMessage.errorTypeQR);
        restartScanning(3, pop: false);
        return;
      }
      showDialog(
          context: context,
          builder: (ctx) {
            return LoadingDialog(
              barrierDismissible: true,
            );
          });
      // 二维码扫码类型
      String qrTypeParam = QueryQRType.queryQRType(category, item);
      HttpRequest.queryQRInfo(qrTypeParam, params: params).then((res) {
        restartScanning(5);
        if (res['status'] == 200) {
          EquipmentScanModel model = EquipmentScanModel.fromJson(res['result']['equipment']);
          if (item != RouteItemFrontComponentConst.inStock && model.status == null) {
            FlutterToast.toastCenter('装备未入库');
            return;
          } else if (item == RouteItemFrontComponentConst.maintain && model.status != '库存') {
            FlutterToast.toastCenter('装备未在位');
            return;
          } else if (item == RouteItemFrontComponentConst.repair && model.status != '库存') {
            FlutterToast.toastCenter('装备未在位');
            return;
          } else if (item == RouteItemFrontComponentConst.repaired && model.status != '维修') {
            FlutterToast.toastCenter('装备未在维修,不能维修完成');
            return;
          } else if (item == RouteItemFrontComponentConst.scraped) {
            if (model.status != '维修' && model.status != '库存') {
              FlutterToast.toastCenter('该装备不能报废');
              return;
            }
          }
          for (final EquipmentScanModel item in _addItems) {
            if (item.qrCode == model.qrCode) {
              FlutterToast.toastCenter(ToastMessage.alreadyAdd);
              return;
            }
          }
          if (item == RouteItemFrontComponentConst.inStock && !model.singleOrDouble) {
            addInStock(context, model);
          } else {
            setState(() {
              _addItems.add(model);
            });
            // 展示Toast
            EquipmentToast.show(context, equipModel: model, position: '$_selectPosition${_positionDescription ?? ''}');
          }
          // 添加到列表中
        } else {
          //FlutterToast.toastCenter(res['message']);
        }
      }).catchError((e) {
        restartScanning(5);
        FlutterToast.toastCenter('请重新扫码');
      });
    } else if (category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
      if (!message.startsWith(QRType.fireFightingVehiclePrefix) && item != RouteItemFrontComponentConst.inStock) {
        FlutterToast.toastCenter(ToastMessage.errorVehicleTypeQR);
        restartScanning(3, pop: false);
        return;
      }
      String code = QueryQRType.queryQRType(category, item);
      showDialog(
          context: context,
          builder: (ctx) {
            return LoadingDialog(
              barrierDismissible: true,
            );
          });
      HttpRequest.queryQRInfo(code, params: params).then((res) {
        restartScanning(5);
        if (res['status'] == 200) {
          if (item == RouteItemFrontComponentConst.inStock) {
            EquipmentScanModel model = EquipmentScanModel.fromJson(res['result']['equipment']);
            model.status = '未入库';
            addInStock(context, model);
          } else {
            CarScanModel carmodel = CarScanModel.fromJson(res['result']['car']);
            // 展示Toast
            EquipmentToast.show(context, carModel: carmodel);
            //restartScanning(5, pop: false);
            Map<String, dynamic> data = {'carId': carmodel.carId, 'carNum': carmodel.carNum};
            selectVehicleConfirm(context, data);
          }
        } else {
          //FlutterToast.toastCenter(res['message']);
        }
      }).catchError((e) {
        restartScanning(3);
        FlutterToast.toastCenter('请重新扫码');
      });
    }
  }

  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;
              }
              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('输入数字不得大于10位');
                  return;
                }
              }
              if (pag.length == 2) {
                var lis1 = pag[0];
                var lis2 = pag[1];
                if (lis1.length > 10) {
                  FlutterToast.toastCenter('输入数字不得大于10位');
                  return;
                }
                if (lis2.length > 2) {
                  FlutterToast.toastCenter('输入小数只能输入小数点后两位');
                  return;
                }
              }
              if (widget.routeModel.category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
                it.amount = double.parse(value);
              } else {
                it.amount = int.parse(value);
              }

              if (isExistItems(it.equipmentDetailId) &&
                  widget.routeModel.category == RouteCategoryFrontComponentConst.fireExtinguishingAgent) {
                addAddItemList(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 ?? ''}');
              }
            },
          );
        });
  }

  ///车辆详情查询跳转
  Future<void> getCarDel(BuildContext context, String carid) async {
    Future.delayed(Duration.zero, () {
      HttpRequest.getCarDel(carid).then((res) {
        restartScanning(3);
        if (res['status'] == 200) {
          _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 {
          // restartScanning(3,pop: false);
          // Navigator.of(context).pop();
          //FlutterToast.toastCenter(res['message']);
        }
      }).catchError((_) {
        restartScanning(3);
        FlutterToast.toastCenter('请重新扫码');
      });
    });
  }

  ///装备详情查询跳转
  Future<void> 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 {
          //FlutterToast.toastCenter(res['message']);
        }
      }).catchError((_) {
        restartScanning(3);
        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;
  }
}
