Merge branch 'release' of https://gitee.com/starlock-cn/app-starlock into release

# Conflicts:
#	lib/main/lockMian/lockList/lockList_page.dart
#	lib/network/api.dart
#	lib/network/api_provider.dart
#	lib/network/api_repository.dart
This commit is contained in:
魏少阳 2024-05-23 10:51:32 +08:00
commit a8c57cc5b0
152 changed files with 5013 additions and 3907 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@ -1,29 +1,287 @@
# This file configures the analyzer, which statically analyzes Dart code to # For a list of lints, see: http://dart-lang.github.io/linter/lints/
# check for errors, warnings, and lints. # See the configuration guide for more
# https://github.com/dart-lang/sdk/tree/master/pkg/analyzer#configuring-the-analyzer
# #
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled # There are other similar analysis options files in the flutter repos,
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be # which should be kept in sync with this file:
# invoked from the command line by running `flutter analyze`. #
# - analysis_options.yaml (this file)
# - packages/flutter/lib/analysis_options_user.yaml
# - https://github.com/flutter/plugins/blob/master/analysis_options.yaml
# - https://github.com/flutter/engine/blob/master/analysis_options.yaml
#
# This file contains the analysis options used by Flutter tools, such as IntelliJ,
# Android Studio, and the `flutter analyze` command.
# The following line activates a set of recommended lints for Flutter apps, analyzer:
# packages, and plugins designed to encourage good coding practices. strong-mode:
include: package:flutter_lints/flutter.yaml implicit-casts: true
implicit-dynamic: true
errors:
# treat missing required parameters as a warning (not a hint)
missing_required_param: warning
# treat missing returns as a warning (not a hint)
missing_return: warning
# allow having TODOs in the code
todo: ignore
# allow self-reference to deprecated members (we do this because otherwise we have
# to annotate every member in every test, assert, etc, when we deprecate something)
# deprecated_member_use_from_same_package: ignore
# Ignore analyzer hints for updating pub specs when using Future or
# Stream and not importing dart:async
# Please see https://github.com/flutter/flutter/pull/24528 for details.
sdk_version_async_exported_from_core: ignore
exclude:
# - "**"
# the following two are relative to the stocks example and the flutter package respectively
# see https://github.com/dart-lang/sdk/issues/28463
- "ios/*"
- "android/*"
- "analysis_options.yaml"
linter: linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at
# https://dart-lang.github.io/linter/lints/index.html.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules: rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule # these rules are documented on and in the same order as
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule # the Dart Lint rules page to make maintenance easier
# https://github.com/dart-lang/linter/blob/master/example/all.yaml
# Additional information about this file can be found at - always_declare_return_types
# https://dart.dev/guides/language/analysis-options - avoid_bool_literals_in_conditional_expressions
- avoid_field_initializers_in_const_classes
- avoid_return_types_on_setters
- avoid_slow_async_io
- avoid_unused_constructor_parameters
- avoid_void_async
- cast_nullable_to_non_nullable
- flutter_style_todos
- iterable_contains_unrelated_type
- leading_newlines_in_multiline_strings
- library_prefixes
- no_adjacent_strings_in_list
- null_check_on_nullable_type_parameter
- package_api_docs
- package_prefixed_library_names
- prefer_final_in_for_each
- prefer_for_elements_to_map_fromIterable
- prefer_foreach
- prefer_generic_function_type_aliases
- prefer_if_elements_to_conditional_expressions
- prefer_iterable_whereType
- prefer_single_quotes
- prefer_spread_collections
- throw_in_finally
- tighten_type_of_initializing_formals
- type_init_formals
- unnecessary_nullable_for_final_variable_declarations
- use_is_even_rather_than_modulo
- use_late_for_private_fields_and_variables
- use_raw_strings
# ======================= 自定义规则
# -------------------------命名
# - 类型定义采用大写驼峰
- camel_case_types
# - 函数拓展采用大写驼峰
- camel_case_extensions
# - 库和文件名采用小写+下划线的方式命名
- library_names
- file_names
# - 普通变量使用驼峰命名
- non_constant_identifier_names
# - 静态变量推荐使用驼峰命名
- constant_identifier_names
# -------------------------排
# - 包引用排序:
# - dart开头的包排在最前面
# - package开头的包排在相对引用包前面
# - exports列在单独模块
# - 每个模块内引用按字母顺序排序
- directives_ordering
# -------------------------格式化
# - 控制流中尽量使用大括号
- curly_braces_in_flow_control_structures
# -------------------------评论
# - 评论使用三斜杠标识
- slash_for_doc_comments
# - 评论中使用可引用范围内的变量
- comment_references
# -------------------------库使用
# - 避免引用包内的具体实现文件
- implementation_imports
# - 避免对lib/目录下的文件采用相对引用
- avoid_relative_lib_imports
#-------------------------NULL
# - 避免初始化变量为null
- avoid_init_to_null
# -------------------------字符串
# - 避免不需要的大括号
- unnecessary_brace_in_string_interps
# - 使用相邻字符串的方式连接字符串
- prefer_adjacent_string_concatenation
# -------------------------集合
# - 尽量使用显式类型的方式初始化集合
- prefer_collection_literals
# - 使用isEmpty和isNotE叩ty来判断是否为空而不是通过length是否为0的方式
- prefer_is_empty
- prefer_is_not_empty
# -------------------------函数
# - 去除不必要的lambdas表达式
- unnecessary_lambdas
# - 函数默认值尽量使用=来赋值
- prefer_equal_for_default_values
# - 使用函数声明的方式将函数和变量做绑定
- prefer_function_declarations_over_variables
# -------------------------成员变量
# - 如无特殊作用,不用专门定义设置和获取方法
- unnecessary_getters_setters
# - 避免使用this方式调用变量
- unnecessary_this
# - 私有变量推荐定义成final
- prefer_final_fields
# - 可以考虑使用..这样方式而不是返回this指针的方式来实现流式调用
- avoid_returning_this
# - 避免返回null
- avoid_returning_null
# -------------------------构造函数
# - 避免构造函数使用{}做空实现可以直接使用;
- empty_constructor_bodies
# - 推荐在构造函数中直接对成员变量进行赋值
- prefer_initializing_formals
# - 去掉new关键字
- unnecessary_new
# - 在const环境中避免使用const关键字
- unnecessary_const
# -------------------------异常处理
# - 对捕获异常不处理的情况话建议使用rethrow方式重新抛出而不是直接throw
- use_rethrow_when_possible
#-------------------------Mixin
# - 建议尽可能使用mixin机制
- prefer_mixin
# -------------------------类型
# - 未初始化变量,尽量提供类型
- prefer_typing_uninitialized_variables
# - 尽可能显式声明变量类型
- always_specify_types
# -------------------------参数
# - 避免使用True或者 false作为参数。应该换成更有语义的表达
- avoid_positional_boolean_parameters
# -------------------------质量
# - 如果重写了==同时也需要重写hashcode
- hash_and_equals
# - 非immutable1e类不要重写hashCode和=否则在集合中会出现bug
- avoid_equals_and_hash_code_on_mutable_classes
# - 在自定义==时,不要做null检查
- avoid_null_checks_in_equality_operators
# -------------------------Core集合融合部分
# - 避免空的else语句
- avoid_empty_else
# - 避免使用隐形类型传递
- avoid_shadowing_type_parameters
# - 避免类型做参数
- avoid_types_as_parameter_names
# - 避免await非future对象
- await_only_futures
# - 避免catch空实现
- empty_catches
# - 集合的 remove需要传递符合集合的类型的参数
- list_remove_unrelated_type
# - case中避免重复
- no_duplicate_case_values
# - deprecated函数或者变量需要注明相关信息
- provide_deprecation_message
# - 去掉不需要的重写注解
- unnecessary_overrides
# - 两个变量比较时,避免类型不一致
- unrelated_type_equality_checks
# - 避免赋值给void类型变量
- void_checks
# - 正则表达式合法性校验
- valid_regexps
# -------------------------Recommended 集合融合部分
# - 非空变量使用 require 关键字
- always_require_non_null_named_parameters
# - 对重写的方法和变量加 override注解
- annotate_overrides
# - 重写方法的参数不要改变参数名称
- avoid_renaming_method_parameters
# - 不要在void函数中返回null
- avoid_returning_null_for_void
# - 避免在单个函数调用中使用传递调用语法
- avoid_single_cascade_in_expression_statements
# - 避免在finally语句块中使用控制流语句
- control_flow_in_finally
# - 避免空语句
- empty_statements
# - 避免传递null给闭包参数
- null_closures
# - 避免重写类的field
- overridden_fields
# - 建议判空逻辑中建议使用??=语法
- prefer_conditional_assignment
# - 判断集合或者字符串的包含的逻辑使用contains而不是indexOf
- prefer_contains
# - 空判断尽量使用??操作符
- prefer_if_null_operators
# - 允许情况下,1ist使用内联的方式声明
- prefer_inlined_adds
# - 推荐使用is!操作符
- prefer_is_not_operator
# - 推荐使用?.操作符
- prefer_null_aware_operators
# - 类型定义尽可能使用void而不是null
- prefer_void_to_null
# - 避免递归调用 getter
- recursive_getters
# - 避免在空判断中使用null
- unnecessary_null_in_if_null_operators
# - 去掉不必要的反斜线
- unnecessary_string_escapes
# - 避免不必要的字符串引用逻辑
- unnecessary_string_interpolations
# -------------------------Flutter 集合融合部分
# - 避免生产环境使用print
- avoid_print
# - 去掉无用的container节点
- avoid_unnecessary_containers
# - 避免在flutter代码中引入web相关的库
- avoid_web_libraries_in_flutter
# - 在state create函数中不加入额外逻辑
- no_logic_in_create_state
# - 优先使用 const构造函数
- prefer_const_constructors
# - 在immutable类定义中使用 const构造函数
- prefer_const_constructors_in_immutables
# - 尽可能定义成const变量
- prefer_const_declarations
# - 在immutable类创建中尽量使用 const变量
- prefer_const_literals_to_create_immutables
# - 优先使用SizedBox而不是 Container
- sized_box_for_whitespace
# - 使用8位16进制整数标识颜色值
- use_full_hex_values_for_flutter_colors
# - 在构造函数中加入key参数
- use_key_in_widget_constructors
# -------------------------其他规则融合部分
# - 无用代码清理
- unnecessary_statements
# - 控制流语句分散到不同层
- always_put_control_body_on_new_line
# - required修饰变量排到变量列表前面
- always_put_required_named_parameters_first
#dart.async.StreamSubscription需要在恰当时机调用 cancel方法
- cancel_subscriptions
# - 倾向在初始化列表中增加 assert
- prefer_asserts_in_initializer_lists
# - 符合标准情况下加上final关键字
- prefer_final_locals
# - 构造函数排在变量之前
- sort_constructors_first
- sort_unnamed_constructors_first
# - 在比较之前先测试类型是否符合要求
- test_types_in_equals
# - 避免不必要的null判断
- unnecessary_null_aware_assignments
# - 去掉不必要的圆括号
- unnecessary_parenthesis
# - 避免不安全HTML的API
- unsafe_html
# - 避免魔鬼数值
- avoid_hard_coded_literals

View File

@ -22,7 +22,8 @@
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<!--允许写设备缓存,用于问题排查--> <!--允许写设备缓存,用于问题排查-->
<uses-permission android:name="android.permission.WRITE_SETTINGS"/> <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<!--允许写入扩展存储,用于写入缓存定位数据--> <!--允许读设备日志,用于问题排查-->
<uses-permission android:name="android.permission.READ_LOGS" />
<!--相机--> <!--相机-->
<uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.CAMERA"/>

View File

@ -608,7 +608,7 @@
"卡详情": "Card details", "卡详情": "Card details",
"请输入": "Please enter", "请输入": "Please enter",
"关闭后,智能锁将设置为全天常开模式,直到手动关闭": "After closing, the smart lock will be set to all-day open mode until manually closed", "关闭后,智能锁将设置为全天常开模式,直到手动关闭": "After closing, the smart lock will be set to all-day open mode until manually closed",
"请输入小于1000的数字": "Please enter a number less than 1000", "请输入小于或等于60的数字": "Please enter a number less than 60",
"操作成功": "Operation success", "操作成功": "Operation success",
"管理员密码相同,无需修改": "The administrator password is the same and does not need to be modified", "管理员密码相同,无需修改": "The administrator password is the same and does not need to be modified",
"修改密码": "Modify password", "修改密码": "Modify password",
@ -816,6 +816,7 @@
"身份证号":"ID number", "身份证号":"ID number",
"请输入真实姓名":"Please enter your real name", "请输入真实姓名":"Please enter your real name",
"请输入身份证号":"Please enter your ID number", "请输入身份证号":"Please enter your ID number",
"请输入身份证号和真实姓名":"Please enter your ID number and real name",
"点击返回设备配对":"Tap Back to device pairing", "点击返回设备配对":"Tap Back to device pairing",
"无法连接?尝试升级":"Can't connect?Upgrade attempted", "无法连接?尝试升级":"Can't connect?Upgrade attempted",
"固件升级提示":"Firmware upgrade prompt", "固件升级提示":"Firmware upgrade prompt",
@ -854,5 +855,6 @@
"门铃事件":"Doorbell event", "门铃事件":"Doorbell event",
"视频事件":"Video event", "视频事件":"Video event",
"请开启蓝牙":"Please turn on Bluetooth", "请开启蓝牙":"Please turn on Bluetooth",
"请选择有效日":"Please select the effective day" "请选择有效日":"Please select the effective day",
"公司名字长度不能小于 6 ": "The length of the company name cannot be less than 6"
} }

View File

@ -633,7 +633,7 @@
"卡详情": "卡详情", "卡详情": "卡详情",
"请输入": "请输入", "请输入": "请输入",
"关闭后,智能锁将设置为全天常开模式,直到手动关闭": "关闭后,智能锁将设置为全天常开模式,直到手动关闭", "关闭后,智能锁将设置为全天常开模式,直到手动关闭": "关闭后,智能锁将设置为全天常开模式,直到手动关闭",
"请输入小于1000的数字": "请输入小于1000的数字", "请输入小于或等于60的数字": "请输入小于或等于60的数字",
"操作成功": "操作成功", "操作成功": "操作成功",
"管理员密码相同,无需修改": "管理员密码相同,无需修改", "管理员密码相同,无需修改": "管理员密码相同,无需修改",
"修改密码": "修改密码", "修改密码": "修改密码",
@ -844,6 +844,7 @@
"身份证号":"身份证号", "身份证号":"身份证号",
"请输入真实姓名":"请输入真实姓名", "请输入真实姓名":"请输入真实姓名",
"请输入身份证号":"请输入身份证号", "请输入身份证号":"请输入身份证号",
"请输入身份证号和真实姓名":"请输入身份证号和真实姓名",
"点击返回设备配对":"点击返回设备配对", "点击返回设备配对":"点击返回设备配对",
"无法连接?尝试升级":"无法连接?尝试升级", "无法连接?尝试升级":"无法连接?尝试升级",
@ -883,5 +884,6 @@
"门铃事件":"门铃事件", "门铃事件":"门铃事件",
"视频事件":"视频事件", "视频事件":"视频事件",
"请开启蓝牙":"请开启蓝牙", "请开启蓝牙":"请开启蓝牙",
"请选择有效日":"请选择有效日" "请选择有效日":"请选择有效日",
"公司名字长度不能小于 6 ": "公司名字长度不能小于 6 "
} }

View File

@ -608,7 +608,7 @@
"卡详情": "卡详情", "卡详情": "卡详情",
"请输入": "请输入", "请输入": "请输入",
"关闭后,智能锁将设置为全天常开模式,直到手动关闭": "关闭后,智能锁将设置为全天常开模式,直到手动关闭", "关闭后,智能锁将设置为全天常开模式,直到手动关闭": "关闭后,智能锁将设置为全天常开模式,直到手动关闭",
"请输入小于1000的数字": "请输入小于1000的数字", "请输入小于或等于60的数字": "请输入小于或等于60的数字",
"操作成功": "操作成功", "操作成功": "操作成功",
"管理员密码相同,无需修改": "管理员密码相同,无需修改", "管理员密码相同,无需修改": "管理员密码相同,无需修改",
"修改密码": "修改密码", "修改密码": "修改密码",
@ -753,7 +753,7 @@
"当被胁迫要求强行开锁时,使用胁迫指纹会触发报警,报警消息会推送给管理员,该功能需要锁联网": "当被胁迫要求强行开锁时,使用胁迫指纹会触发报警,报警消息会推送给管理员,该功能需要锁联网", "当被胁迫要求强行开锁时,使用胁迫指纹会触发报警,报警消息会推送给管理员,该功能需要锁联网": "当被胁迫要求强行开锁时,使用胁迫指纹会触发报警,报警消息会推送给管理员,该功能需要锁联网",
"胁迫指纹": "胁迫指纹", "胁迫指纹": "胁迫指纹",
"指纹列表": "指纹列表", "指纹列表": "指纹列表",
"经过以上设定的时间,锁没有被开启,系统会给指定对象发送提醒消息,该功能需要锁联网": "经过以上设定的时间,锁没有被开启,系统会给指定对象发送提醒消息,该功能需要锁联网", "经过以上设定的时间,锁没有被开启,系统会给指定对象发送提醒消息,该功能需要锁联网": "经过以上设定的时间,锁没有被开启,系统会给指定对象发送提醒消息,该功能需要锁联网",
"打开提醒后当锁电量低于20%、10%和5%系统会给指定对象发送提醒消息。电量读取方式网关读取或APP读取。": "打开提醒后当锁电量低于20%、10%和5%系统会给指定对象发送提醒消息。电量读取方式网关读取或APP读取。", "打开提醒后当锁电量低于20%、10%和5%系统会给指定对象发送提醒消息。电量读取方式网关读取或APP读取。": "打开提醒后当锁电量低于20%、10%和5%系统会给指定对象发送提醒消息。电量读取方式网关读取或APP读取。",
"门未开时间": "门未开时间", "门未开时间": "门未开时间",
"添加和使用面容开锁时:": "添加和使用面容开锁时:", "添加和使用面容开锁时:": "添加和使用面容开锁时:",
@ -815,6 +815,7 @@
"身份证号": "身份证号", "身份证号": "身份证号",
"请输入真实姓名": "请输入真实姓名", "请输入真实姓名": "请输入真实姓名",
"请输入身份证号": "请输入身份证号", "请输入身份证号": "请输入身份证号",
"请输入身份证号和真实姓名": "请输入身份证号和真实姓名",
"点击返回设备配对": "点击返回设备配对", "点击返回设备配对": "点击返回设备配对",
"无法连接?尝试升级": "无法连接?尝试升级", "无法连接?尝试升级": "无法连接?尝试升级",
"固件升级提示": "固件升级提示", "固件升级提示": "固件升级提示",
@ -844,14 +845,15 @@
"操作失败,请确认锁是否在附近,或重启手机蓝牙后再试。": "操作失败,请确认锁是否在附近,或重启手机蓝牙后再试。", "操作失败,请确认锁是否在附近,或重启手机蓝牙后再试。": "操作失败,请确认锁是否在附近,或重启手机蓝牙后再试。",
"如果是全自动锁,请使屏幕变亮": "如果是全自动锁,请使屏幕变亮", "如果是全自动锁,请使屏幕变亮": "如果是全自动锁,请使屏幕变亮",
"正在尝试闭锁……": "正在尝试闭锁……", "正在尝试闭锁……": "正在尝试闭锁……",
"清空记录":"清空记录", "清空记录": "清空记录",
"是否要删除操作记录?":"是否要删除操作记录?", "是否要删除操作记录?": "是否要删除操作记录?",
"被删除的记录不能恢复":"被删除的记录不能恢复", "被删除的记录不能恢复": "被删除的记录不能恢复",
"全部事件":"全部事件", "全部事件": "全部事件",
"开锁事件":"开锁事件", "开锁事件": "开锁事件",
"异常事件":"异常事件", "异常事件": "异常事件",
"门铃事件":"门铃事件", "门铃事件": "门铃事件",
"视频事件":"视频事件", "视频事件": "视频事件",
"请开启蓝牙":"请开启蓝牙", "请开启蓝牙": "请开启蓝牙",
"请选择有效日":"请选择有效日" "请选择有效日": "请选择有效日",
"公司名字长度不能小于 6 ": "公司名字长度不能小于 6 "
} }

View File

@ -36,6 +36,7 @@ PODS:
- Flutter - Flutter
- auto_orientation (0.0.1): - auto_orientation (0.0.1):
- Flutter - Flutter
- Bugly (2.6.1)
- camera_avfoundation (0.0.1): - camera_avfoundation (0.0.1):
- Flutter - Flutter
- connectivity_plus (0.0.1): - connectivity_plus (0.0.1):
@ -81,6 +82,9 @@ PODS:
- Flutter (1.0.0) - Flutter (1.0.0)
- flutter_blue_plus (0.0.1): - flutter_blue_plus (0.0.1):
- Flutter - Flutter
- flutter_bugly_plugin (0.0.1):
- Bugly
- Flutter
- flutter_local_notifications (0.0.1): - flutter_local_notifications (0.0.1):
- Flutter - Flutter
- flutter_native_contact_picker (0.0.1): - flutter_native_contact_picker (0.0.1):
@ -170,6 +174,7 @@ DEPENDENCIES:
- file_picker (from `.symlinks/plugins/file_picker/ios`) - file_picker (from `.symlinks/plugins/file_picker/ios`)
- Flutter (from `Flutter`) - Flutter (from `Flutter`)
- flutter_blue_plus (from `.symlinks/plugins/flutter_blue_plus/ios`) - flutter_blue_plus (from `.symlinks/plugins/flutter_blue_plus/ios`)
- flutter_bugly_plugin (from `.symlinks/plugins/flutter_bugly_plugin/ios`)
- flutter_local_notifications (from `.symlinks/plugins/flutter_local_notifications/ios`) - flutter_local_notifications (from `.symlinks/plugins/flutter_local_notifications/ios`)
- flutter_native_contact_picker (from `.symlinks/plugins/flutter_native_contact_picker/ios`) - flutter_native_contact_picker (from `.symlinks/plugins/flutter_native_contact_picker/ios`)
- flutter_pcm_sound (from `.symlinks/plugins/flutter_pcm_sound/ios`) - flutter_pcm_sound (from `.symlinks/plugins/flutter_pcm_sound/ios`)
@ -205,6 +210,7 @@ SPEC REPOS:
- AMap3DMap - AMap3DMap
- AMapFoundation - AMapFoundation
- AMapLocation - AMapLocation
- Bugly
- DKImagePickerController - DKImagePickerController
- DKPhotoGallery - DKPhotoGallery
- GoogleMaps - GoogleMaps
@ -248,6 +254,8 @@ EXTERNAL SOURCES:
:path: Flutter :path: Flutter
flutter_blue_plus: flutter_blue_plus:
:path: ".symlinks/plugins/flutter_blue_plus/ios" :path: ".symlinks/plugins/flutter_blue_plus/ios"
flutter_bugly_plugin:
:path: ".symlinks/plugins/flutter_bugly_plugin/ios"
flutter_local_notifications: flutter_local_notifications:
:path: ".symlinks/plugins/flutter_local_notifications/ios" :path: ".symlinks/plugins/flutter_local_notifications/ios"
flutter_native_contact_picker: flutter_native_contact_picker:
@ -309,6 +317,7 @@ SPEC CHECKSUMS:
audio_session: 088d2483ebd1dc43f51d253d4a1c517d9a2e7207 audio_session: 088d2483ebd1dc43f51d253d4a1c517d9a2e7207
audioplayers_darwin: 877d9a4d06331c5c374595e46e16453ac7eafa40 audioplayers_darwin: 877d9a4d06331c5c374595e46e16453ac7eafa40
auto_orientation: 102ed811a5938d52c86520ddd7ecd3a126b5d39d auto_orientation: 102ed811a5938d52c86520ddd7ecd3a126b5d39d
Bugly: 217ac2ce5f0f2626d43dbaa4f70764c953a26a31
camera_avfoundation: 759172d1a77ae7be0de08fc104cfb79738b8a59e camera_avfoundation: 759172d1a77ae7be0de08fc104cfb79738b8a59e
connectivity_plus: bf0076dd84a130856aa636df1c71ccaff908fa1d connectivity_plus: bf0076dd84a130856aa636df1c71ccaff908fa1d
device_info_plus: e5c5da33f982a436e103237c0c85f9031142abed device_info_plus: e5c5da33f982a436e103237c0c85f9031142abed
@ -318,12 +327,13 @@ SPEC CHECKSUMS:
file_picker: ce3938a0df3cc1ef404671531facef740d03f920 file_picker: ce3938a0df3cc1ef404671531facef740d03f920
Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
flutter_blue_plus: 4837da7d00cf5d441fdd6635b3a57f936778ea96 flutter_blue_plus: 4837da7d00cf5d441fdd6635b3a57f936778ea96
flutter_bugly_plugin: d2db6d6641938269fa538575126e8ff530ee02c7
flutter_local_notifications: 4cde75091f6327eb8517fa068a0a5950212d2086 flutter_local_notifications: 4cde75091f6327eb8517fa068a0a5950212d2086
flutter_native_contact_picker: bd430ba0fbf82768bb50c2c52a69a65759a8f907 flutter_native_contact_picker: bd430ba0fbf82768bb50c2c52a69a65759a8f907
flutter_pcm_sound: de0572ca4f99091cc2abfcc31601b8a4ddd33c0e flutter_pcm_sound: de0572ca4f99091cc2abfcc31601b8a4ddd33c0e
flutter_voice_processor: 2b89b93d69b02227ae3fd58589ee0bcfa3ca2a82 flutter_voice_processor: 2b89b93d69b02227ae3fd58589ee0bcfa3ca2a82
fluttertoast: 9f2f8e81bb5ce18facb9748d7855bf5a756fe3db fluttertoast: 9f2f8e81bb5ce18facb9748d7855bf5a756fe3db
fluwx: daa284756ce53442b3d0417ceeda66e981906811 fluwx: c18fd6c16b03a2187cd07d6e48e32a7801962849
google_maps_flutter_ios: f135b968a67c05679e0a53538e900b5c174b0d99 google_maps_flutter_ios: f135b968a67c05679e0a53538e900b5c174b0d99
GoogleMaps: 20d7b12be49a14287f797e88e0e31bc4156aaeb4 GoogleMaps: 20d7b12be49a14287f797e88e0e31bc4156aaeb4
image_gallery_saver: cb43cc43141711190510e92c460eb1655cd343cb image_gallery_saver: cb43cc43141711190510e92c460eb1655cd343cb

View File

@ -22,14 +22,59 @@
<string>$(FLUTTER_BUILD_NAME)</string> <string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key> <key>CFBundleSignature</key>
<string>????</string> <string>????</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>None</string>
<key>CFBundleURLIconFile</key>
<string/>
<key>CFBundleURLName</key>
<string>com.sky.skysmartlock</string>
<key>CFBundleURLSchemes</key>
<array>
<string>skysmartlock</string>
<string/>
<string/>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>weixin</string>
<key>CFBundleURLSchemes</key>
<array>
<string>123456</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>weixin</string>
<key>CFBundleURLSchemes</key>
<array>
<string>wxbe340095d2b8fd51</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string> <string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
<string>weixinULAPI</string>
<string>weixinURLParamsAPI</string>
</array>
<key>LSRequiresIPhoneOS</key> <key>LSRequiresIPhoneOS</key>
<true/> <true/>
<key>NSAppTransportSecurity</key> <key>NSAppTransportSecurity</key>
<dict> <dict>
<key>NSAllowsArbitraryLoads</key> <key>NSAllowsArbitraryLoads</key>
<true/> <true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
<key>NSExceptionDomains</key> <key>NSExceptionDomains</key>
<dict> <dict>
<key>jpush.cn</key> <key>jpush.cn</key>
@ -86,23 +131,6 @@
</array> </array>
<key>UIViewControllerBasedStatusBarAppearance</key> <key>UIViewControllerBasedStatusBarAppearance</key>
<false/> <false/>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.sky.skysmartlock</string>
<key>CFBundleURLSchemes</key>
<array>
<string>skysmartlock</string>
<string></string>
<string></string>
</array>
<key>CFBundleURLIconFile</key>
<string></string>
<key>CFBundleTypeRole</key>
<string>None</string>
</dict>
</array>
<key>io.flutter.embedded_views_preview</key> <key>io.flutter.embedded_views_preview</key>
<true/> <true/>
</dict> </dict>

View File

@ -11,7 +11,6 @@ import 'package:star_lock/main/lockMian/lockMain/lockMain_logic.dart';
import 'package:star_lock/tools/app_manager.dart'; import 'package:star_lock/tools/app_manager.dart';
import 'package:star_lock/tools/bindings/app_binding.dart'; import 'package:star_lock/tools/bindings/app_binding.dart';
import 'package:star_lock/tools/storage.dart'; import 'package:star_lock/tools/storage.dart';
import 'package:star_lock/tools/xs_jPhush.dart';
import 'package:star_lock/translations/app_dept.dart'; import 'package:star_lock/translations/app_dept.dart';
import 'package:star_lock/translations/trans_lib.dart'; import 'package:star_lock/translations/trans_lib.dart';
@ -19,7 +18,6 @@ import 'package:star_lock/translations/trans_lib.dart';
import 'appRouters.dart'; import 'appRouters.dart';
import 'baseWidget.dart'; import 'baseWidget.dart';
import 'tools/appRouteObserver.dart'; import 'tools/appRouteObserver.dart';
import 'dart:io';
import 'tools/store_service.dart'; import 'tools/store_service.dart';
@ -38,24 +36,25 @@ class _MyAppState extends State<MyApp> with WidgetsBindingObserver, BaseWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ScreenUtilInit( return ScreenUtilInit(
designSize: const Size(585, 1265), designSize: const Size(585, 1265),
builder: (w, a) => _initMaterialApp()); builder: (BuildContext w, Widget? a) => _initMaterialApp());
} }
GetMaterialApp _initMaterialApp() => GetMaterialApp( GetMaterialApp _initMaterialApp() => GetMaterialApp(
// enableLog: false, // enableLog: false,
title: F.navTitle, title: F.navTitle,
navigatorObservers: [AppRouteObserver().routeObserver], navigatorObservers: <NavigatorObserver>[AppRouteObserver().routeObserver],
translations: TranslationMessage(), translations: TranslationMessage(),
supportedLocales: appDept.deptSupportedLocales, supportedLocales: appDept.deptSupportedLocales,
localizationsDelegates: const [ localizationsDelegates: const <LocalizationsDelegate<dynamic>>[
GlobalMaterialLocalizations.delegate, GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate, GlobalWidgetsLocalizations.delegate,
], ],
localeResolutionCallback: (locale, supportedLocales) { localeResolutionCallback:
(Locale? locale, Iterable<Locale> supportedLocales) {
if (!supportedLocales.contains(locale)) { if (!supportedLocales.contains(locale)) {
int idx = appSupportedLocales.indexWhere( final int idx = appSupportedLocales.indexWhere(
(element) => element.languageCode == locale!.languageCode); (Locale element) => element.languageCode == locale!.languageCode);
if (idx != -1) { if (idx != -1) {
locale = appSupportedLocales[idx]; locale = appSupportedLocales[idx];
} else { } else {
@ -68,7 +67,7 @@ class _MyAppState extends State<MyApp> with WidgetsBindingObserver, BaseWidget {
}, },
locale: StoreService.to.getLanguageCode()!.isNotEmpty locale: StoreService.to.getLanguageCode()!.isNotEmpty
? appDept.deptSupportedLocales ? appDept.deptSupportedLocales
.where((element) => .where((Locale element) =>
element.languageCode == StoreService.to.getLanguageCode()) element.languageCode == StoreService.to.getLanguageCode())
.first .first
: Get.deviceLocale, : Get.deviceLocale,
@ -148,7 +147,7 @@ class _MyAppState extends State<MyApp> with WidgetsBindingObserver, BaseWidget {
} }
Future<bool> getLoginStatus() async { Future<bool> getLoginStatus() async {
final data = await Storage.getString(saveUserLoginData); final String? data = await Storage.getString(saveUserLoginData);
if (data != null && data.isNotEmpty) { if (data != null && data.isNotEmpty) {
return true; return true;
} }

View File

@ -42,7 +42,8 @@ import 'package:star_lock/mine/about/webviewShow_page.dart';
import 'package:star_lock/mine/mine/safeVerify/safeVerify_page.dart'; import 'package:star_lock/mine/mine/safeVerify/safeVerify_page.dart';
import 'package:star_lock/mine/minePersonInfo/minePersonInfoEmail/mineBindPhoneOrEmail_page.dart'; import 'package:star_lock/mine/minePersonInfo/minePersonInfoEmail/mineBindPhoneOrEmail_page.dart';
import 'package:star_lock/mine/minePersonInfo/minePersonInfoViewSafetyProblem/minePersonInfoViewSafetyProblem_page.dart'; import 'package:star_lock/mine/minePersonInfo/minePersonInfoViewSafetyProblem/minePersonInfoViewSafetyProblem_page.dart';
import 'package:star_lock/mine/mineSet/authorizedAdministrator/administratorDetails/adminDetailChangeDate_page.dart'; import 'package:star_lock/mine/mineSet/authorizedAdministrator/administratorAssociationLock/administratorAssociationLock_page.dart';
import 'package:star_lock/mine/mineSet/authorizedAdministrator/administratorChangeDate/adminDetailChangeDate_page.dart';
import 'package:star_lock/mine/mineSet/authorizedAdministrator/administratorDetails/administratorDetails_page.dart'; import 'package:star_lock/mine/mineSet/authorizedAdministrator/administratorDetails/administratorDetails_page.dart';
import 'package:star_lock/mine/mineSet/lockGroup/lockGroupList/lockGroupList_page.dart'; import 'package:star_lock/mine/mineSet/lockGroup/lockGroupList/lockGroupList_page.dart';
import 'package:star_lock/mine/mineSet/lockUserManage/expireLockList/expireLockManage_page.dart'; import 'package:star_lock/mine/mineSet/lockUserManage/expireLockList/expireLockManage_page.dart';
@ -373,7 +374,8 @@ abstract class Routers {
static const getDeviceListPage = '/getDeviceListPage'; // static const getDeviceListPage = '/getDeviceListPage'; //
static const getNameListPage = '/getNameListPage'; // static const getNameListPage = '/getNameListPage'; //
static const authorityManagementPage = '/authorityManagementPage'; // static const authorityManagementPage = '/authorityManagementPage'; //
static const massSendLockGroupListPage = '/massSendLockGroupListPage'; // static const massSendLockGroupListPage =
'/massSendLockGroupListPage'; //
static const massSendReceiverPage = '/massSendReceiverPage'; // static const massSendReceiverPage = '/massSendReceiverPage'; //
static const lockUserListPage = '/lockUserListPage'; // static const lockUserListPage = '/lockUserListPage'; //
static const administratorDetailsPage = '/administratorDetailsPage'; // static const administratorDetailsPage = '/administratorDetailsPage'; //
@ -447,6 +449,8 @@ abstract class Routers {
static const advancedFeaturesWebPage = '/advancedFeaturesWebPage'; // static const advancedFeaturesWebPage = '/advancedFeaturesWebPage'; //
static const advancedFunctionRecordPage = static const advancedFunctionRecordPage =
'/advancedFunctionRecordPage'; // '/advancedFunctionRecordPage'; //
static const String administratorAssociationLockPage =
'/administratorAssociationLockPage'; //--
} }
abstract class AppRouters { abstract class AppRouters {
@ -1069,5 +1073,8 @@ abstract class AppRouters {
GetPage( GetPage(
name: Routers.advancedFunctionRecordPage, name: Routers.advancedFunctionRecordPage,
page: (() => const AdvancedFunctionRecordPage())), page: (() => const AdvancedFunctionRecordPage())),
GetPage(
name: Routers.administratorAssociationLockPage,
page: () => const AdministratorAssociationLockPage()),
]; ];
} }

View File

@ -4,38 +4,42 @@ import 'dart:io';
import 'package:star_lock/mine/about/debug/debug_console.dart'; import 'package:star_lock/mine/about/debug/debug_console.dart';
class AppLog { class AppLog {
static bool _printLog = false; static bool _printLog = false;
static bool _onlyError = false; static bool _onlyError = false;
static showLog({required bool printLog, bool? onlyError}){ static void showLog({required bool printLog, bool? onlyError}) {
_printLog = printLog; _printLog = printLog;
_onlyError = onlyError ?? false; _onlyError = onlyError ?? false;
} }
static log(String msg,{bool? error}){
static void log(String msg, {StackTrace? stackTrace, bool? error}) {
msg = '${DateTime.now().toIso8601String()} : $msg'; msg = '${DateTime.now().toIso8601String()} : $msg';
DebugConsole.info(msg); DebugConsole.info(msg, stackTrace: stackTrace, isErr: error ?? false);
if(!kDebugMode)return; if (!kDebugMode) {
return;
}
error = error ?? false; error = error ?? false;
// if(!_printLog)return; // if(!_printLog)return;
// if(_onlyError && !error) return; // if(_onlyError && !error) return;
if(error){ if (error) {
msg = '----->>> $msg'; final bool stackTraceIsNull = stackTrace != null;
msg = '----->>> $msg ${stackTraceIsNull ? '\n$stackTrace' : ''}';
} }
Get.log(msg); Get.log(msg);
} }
} }
class AppPlatform { class AppPlatform {
static bool isIOS = Platform.isIOS; static bool isIOS = Platform.isIOS;
static bool isAndroid = Platform.isAndroid; static bool isAndroid = Platform.isAndroid;
static String platformString(){
static String platformString() {
String name = 'unknown'; String name = 'unknown';
if(isIOS){ if (isIOS) {
name = 'iOS'; name = 'iOS';
} }
if(isAndroid){ if (isAndroid) {
name = 'Android'; name = 'Android';
} }
return name; return name;
@ -44,50 +48,59 @@ class AppPlatform {
static String _brand = 'unknown'; static String _brand = 'unknown';
static int _sdkInt = 23; static int _sdkInt = 23;
static void setBrandString(String brand){ static void setBrandString(String brand) {
_brand = brand; _brand = brand;
} }
static String getBrandString()=>_brand;
static void setSDKInt(int sdkInt){ static String getBrandString() => _brand;
static void setSDKInt(int sdkInt) {
_sdkInt = sdkInt; _sdkInt = sdkInt;
} }
static bool isSamsung()=>_brand.toLowerCase().contains('samsung');
static int getSdkIntValue()=>_sdkInt;
static bool onlyCanNetUpgrade()=>isSamsung() && (getSdkIntValue() >= 29);
static bool isSamsung() => _brand.toLowerCase().contains('samsung');
static int getSdkIntValue() => _sdkInt;
static bool onlyCanNetUpgrade() => isSamsung() && (getSdkIntValue() >= 29);
} }
class AppMowerCodes { class AppMowerCodes {
static int idCodeLength(){ static int idCodeLength() {
int len = 19; int len = 19;
return len; return len;
} }
static int fenceNameLength = 8; static int fenceNameLength = 8;
static int registerCodeLength = 4; static int registerCodeLength = 4;
} }
class AppDate { class AppDate {
static String dateString() { static String dateString() {
return '${year()}-${month().toString().padLeft(2,'0')}-${day().toString() return '${year()}-${month().toString().padLeft(2, '0')}-${day().toString().padLeft(2, '0')}';
.padLeft(2,'0')}';
} }
static String calendarString() { static String calendarString() {
String temp = '${year()}${month().toString().padLeft(2,'0')}${day().toString() String temp =
.padLeft(2,'0')}${hour().toString().padLeft(2,'0')}${second() '${year()}${month().toString().padLeft(2, '0')}${day().toString().padLeft(2, '0')}${hour().toString().padLeft(2, '0')}${second().toString().padLeft(2, '0')}';
.toString().padLeft(2,'0')}';
return temp; return temp;
} }
static int year()=>DateTime.now().year; static int year() => DateTime.now().year;
static int month()=>DateTime.now().month;
static int day()=>DateTime.now().day;
static int hour()=>DateTime.now().hour;
static int minute()=>DateTime.now().minute;
static int second()=>DateTime.now().second;
static int weekDay()=>DateTime.now().weekday;
static int timeZeroOffset()=>DateTime.now().timeZoneOffset.inHours;
static int month() => DateTime.now().month;
static int day() => DateTime.now().day;
static int hour() => DateTime.now().hour;
static int minute() => DateTime.now().minute;
static int second() => DateTime.now().second;
static int weekDay() => DateTime.now().weekday;
static int timeZeroOffset() => DateTime.now().timeZoneOffset.inHours;
} }
//TODO: //TODO:
@ -99,9 +112,9 @@ enum ErrorType {
} }
class AppErrorCode { class AppErrorCode {
static int errorCode(ErrorType type){ static int errorCode(ErrorType type) {
int code = 0; int code = 0;
switch(type){ switch (type) {
case ErrorType.modeNotMatch: case ErrorType.modeNotMatch:
code = 1; code = 1;
break; break;
@ -118,8 +131,3 @@ class AppErrorCode {
return code; return code;
} }
} }

View File

@ -1,13 +1,9 @@
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'package:app_settings/app_settings.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/app_settings/app_settings.dart'; import 'package:star_lock/app_settings/app_settings.dart';
import 'package:star_lock/tools/showTipView.dart';
import 'package:star_lock/widget/permission/permission_dialog.dart';
import 'package:url_launcher/url_launcher.dart';
import 'io_tool/io_model.dart'; import 'io_tool/io_model.dart';
import 'io_tool/io_tool.dart'; import 'io_tool/io_tool.dart';
@ -21,39 +17,39 @@ typedef ConnectStateCallBack = Function(
typedef ScanDevicesCallBack = Function(List<ScanResult>); typedef ScanDevicesCallBack = Function(List<ScanResult>);
class BlueManage { class BlueManage {
final List<ScanResult> scanDevices = [];
factory BlueManage() => shareManager()!;
BlueManage._init() {
_initBlue();
}
final List<ScanResult> scanDevices = <ScanResult>[];
// id // id
final Guid _serviceIdConnect = Guid("fff0"); final Guid _serviceIdConnect = Guid('fff0');
// id // id
final Guid _serviceIdWrite = Guid('0000FFF0-0000-1000-8000-00805F9B34FB'); final Guid _serviceIdWrite = Guid('0000FFF0-0000-1000-8000-00805F9B34FB');
// id // id
final Guid _characteristicIdSubscription = Guid("fff1"); final Guid _characteristicIdSubscription = Guid('fff1');
// id // id
final Guid _characteristicIdWrite = Guid("fff2"); final Guid _characteristicIdWrite = Guid('fff2');
// //
StreamSubscription<EventSendModel>? _sendStreamSubscription; StreamSubscription<EventSendModel>? _sendStreamSubscription;
//
// StreamSubscription? _scanSubscription;
//
// StreamSubscription<dynamic>? _currentConnectionStream;
// StreamSubscription<List<ScanResult>>? _scanResultsSubscription;
StreamSubscription<BluetoothConnectionState>? _connectionStateSubscription; StreamSubscription<BluetoothConnectionState>? _connectionStateSubscription;
StreamSubscription<int>? _mtuSubscription; StreamSubscription<int>? _mtuSubscription;
int? _mtuSize = 20; int? _mtuSize = 20;
// //
String connectDeviceName = ""; String connectDeviceName = '';
// mac地址 // mac地址
String connectDeviceMacAddress = ""; String connectDeviceMacAddress = '';
// //
BluetoothDevice? bluetoothConnectDevice; BluetoothDevice? bluetoothConnectDevice;
@ -68,11 +64,14 @@ class BlueManage {
BluetoothAdapterState? _adapterState = BluetoothAdapterState.unknown; BluetoothAdapterState? _adapterState = BluetoothAdapterState.unknown;
StreamSubscription<BluetoothAdapterState>? _adapterStateStateSubscription; StreamSubscription<BluetoothAdapterState>? _adapterStateStateSubscription;
static BlueManage? _manager; // ,
List<int> allData = <int>[];
BlueManage._init() { //
_initBlue(); List<int> lastTimeData = <int>[];
} int? dataLen;
static BlueManage? _manager;
static BlueManage? shareManager() { static BlueManage? shareManager() {
_manager ??= BlueManage._init(); _manager ??= BlueManage._init();
@ -80,20 +79,16 @@ class BlueManage {
return _manager; return _manager;
} }
factory BlueManage() => shareManager()!;
BlueManage? get manager => shareManager(); BlueManage? get manager => shareManager();
void _initBlue() { void _initBlue() {
FlutterBluePlus.setLogLevel(LogLevel.error, color: true); FlutterBluePlus.setLogLevel(LogLevel.error, color: true);
_initSendStreamSubscription(); _initSendStreamSubscription();
_initAdapterStateStateSubscription(); _initAdapterStateStateSubscription();
// _initListenscanResults();
// _initListenConnectionState();
} }
void _initGetMtuSubscription() { void _initGetMtuSubscription() {
_mtuSubscription ??= bluetoothConnectDevice!.mtu.listen((value) { _mtuSubscription ??= bluetoothConnectDevice!.mtu.listen((int value) {
_mtuSize = value - 3; _mtuSize = value - 3;
AppLog.log('_mtuSizeValue:$value mtuSize:$_mtuSize'); AppLog.log('_mtuSizeValue:$value mtuSize:$_mtuSize');
}); });
@ -101,56 +96,17 @@ class BlueManage {
void _initAdapterStateStateSubscription() { void _initAdapterStateStateSubscription() {
_adapterStateStateSubscription ??= _adapterStateStateSubscription ??=
FlutterBluePlus.adapterState.listen((state) { FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) {
_adapterState = state; _adapterState = state;
}); });
} }
// void _initListenscanResults() {
// var subscription = FlutterBluePlus.scanResults.listen((results) {
// scanDevices.clear();
// for (var scanResult in results) {
// //
// // if (scanResult.device.advName.isEmpty) {
// // return;
// // }
// AppLog.log("scanResult.device.advName:${scanResult.device.advName}"
// " scanResult.advertisementData.serviceUuids:${scanResult.advertisementData.serviceUuids}"
// " rssi:${scanResult.rssi}");
// if (((scanResult.advertisementData.serviceUuids.isNotEmpty ? scanResult.advertisementData.serviceUuids[0] : "").toString().contains("758824")) && (scanResult.rssi >= -100)) {
// // id相同的元素
// final knownDeviceIndex = scanDevices.indexWhere((d) => d.advertisementData.advName == scanResult.advertisementData.advName);
// // -1
// if (knownDeviceIndex >= 0) {
// scanDevices[knownDeviceIndex] = scanResult;
// } else {
// scanDevices.add(scanResult);
// }
// }
// }
// EventBusManager().eventBusFir(scanDevices);
// // FlutterBluePlus.stopScan();
// }, onError: (e) {
// AppLog.log("Scan Error:$e", );
// });
//
// FlutterBluePlus.cancelWhenScanComplete(subscription);
// FlutterBluePlus.isScanning.listen((state) {
// if (state) {
// prAppLog.logint('Scanning');
// } else {
// AppLog.log('Not scanning');
// }
// });
// }
void _initListenConnectionState() { void _initListenConnectionState() {
_connectionStateSubscription?.cancel(); _connectionStateSubscription?.cancel();
_connectionStateSubscription = null; _connectionStateSubscription = null;
_connectionStateSubscription = _connectionStateSubscription = bluetoothConnectDevice!.connectionState
bluetoothConnectDevice!.connectionState.listen((state) async { .listen((BluetoothConnectionState state) async {
bluetoothConnectionState = state; bluetoothConnectionState = state;
// AppLog.log("蓝牙连接状态:$state"); // AppLog.log("蓝牙连接状态:$state");
}); });
@ -162,18 +118,18 @@ class BlueManage {
.on<EventSendModel>() .on<EventSendModel>()
.listen((EventSendModel model) { .listen((EventSendModel model) {
if (model.sendChannel == DataChannel.ble) { if (model.sendChannel == DataChannel.ble) {
FlutterBluePlus.isSupported.then((isAvailable) async { FlutterBluePlus.isSupported.then((bool isAvailable) async {
if (isAvailable) { if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) { if (_adapterState == BluetoothAdapterState.on) {
// //
writeCharacteristicWithResponse(model.data); writeCharacteristicWithResponse(model.data);
} else { } else {
try {} catch (e) { try {} catch (e) {
AppLog.log("蓝牙打开失败"); AppLog.log('蓝牙打开失败');
} }
} }
} else { } else {
AppLog.log("写入数据 蓝牙不可用,不能进行蓝牙操作"); AppLog.log('写入数据 蓝牙不可用,不能进行蓝牙操作');
} }
}); });
} }
@ -183,31 +139,44 @@ class BlueManage {
/// ///
Future<void> startScanSingle(String deviceName, int timeout, Future<void> startScanSingle(String deviceName, int timeout,
ScanDevicesCallBack scanDevicesCallBack) async { ScanDevicesCallBack scanDevicesCallBack) async {
FlutterBluePlus.isSupported.then((isAvailable) async { final DateTime start = DateTime.now();
FlutterBluePlus.isSupported.then((bool isAvailable) async {
if (isAvailable) { if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) { if (_adapterState == BluetoothAdapterState.on) {
try { try {
FlutterBluePlus.startScan(timeout: Duration(seconds: timeout)); //android 8
Completer<dynamic> completer = Completer<dynamic>(); final int divisor = Platform.isAndroid ? 3 : 1;
var subscription = FlutterBluePlus.scanResults.listen((results) { FlutterBluePlus.startScan(
// AppLog.log("startScanSingle扫描到的设备:$results"); continuousDivisor: divisor,
bool isExit = results.any((element) => continuousUpdates: true,
// withServiceData:[ServiceDataFilter()],
withKeywords: <String>[deviceName],
timeout: Duration(seconds: timeout));
final Completer<dynamic> completer = Completer<dynamic>();
final StreamSubscription<List<ScanResult>> subscription =
FlutterBluePlus.scanResults.listen((List<ScanResult> results) {
final bool isExit = results.any((ScanResult element) =>
(element.device.platformName == deviceName) || (element.device.platformName == deviceName) ||
(element.advertisementData.advName == deviceName)); (element.advertisementData.advName == deviceName));
final int milliseconds = DateTime.now().millisecondsSinceEpoch -
start.millisecondsSinceEpoch;
AppLog.log(
'扫描到的设备数:${results.length} 是否查找到 $isExit 以查找$milliseconds毫秒');
if (isExit) { if (isExit) {
for (var scanResult in results) { for (final ScanResult scanResult in results) {
if (((scanResult.advertisementData.serviceUuids.isNotEmpty if (((scanResult.advertisementData.serviceUuids.isNotEmpty
? scanResult.advertisementData.serviceUuids[0] ? scanResult.advertisementData.serviceUuids[0]
: "") : '')
.toString() .toString()
.contains("758824")) && .contains('758824')) &&
(scanResult.rssi >= -100)) { (scanResult.rssi >= -100)) {
// id相同的元素 // id相同的元素
final knownDeviceIndex = scanDevices.indexWhere((d) => final int knownDeviceIndex = scanDevices.indexWhere(
(d.device.platformName == (ScanResult d) =>
scanResult.device.platformName) || (d.device.platformName ==
(d.advertisementData.advName == scanResult.device.platformName) ||
scanResult.advertisementData.advName)); (d.advertisementData.advName ==
scanResult.advertisementData.advName));
// -1 // -1
if (knownDeviceIndex >= 0) { if (knownDeviceIndex >= 0) {
scanDevices[knownDeviceIndex] = scanResult; scanDevices[knownDeviceIndex] = scanResult;
@ -216,11 +185,12 @@ class BlueManage {
} }
} }
} }
completer.complete(); completer.complete();
} }
}, onError: (e) { }, onError: (e) {
AppLog.log( AppLog.log(
"扫描失败:$e", '扫描失败:$e',
); );
}); });
FlutterBluePlus.cancelWhenScanComplete(subscription); FlutterBluePlus.cancelWhenScanComplete(subscription);
@ -228,7 +198,7 @@ class BlueManage {
scanDevicesCallBack(scanDevices); scanDevicesCallBack(scanDevices);
subscription.cancel(); subscription.cancel();
} catch (e) { } catch (e) {
AppLog.log("扫描失败"); AppLog.log('扫描失败');
} }
} else { } else {
try { try {
@ -236,11 +206,11 @@ class BlueManage {
await FlutterBluePlus.turnOn(); await FlutterBluePlus.turnOn();
} }
} catch (e) { } catch (e) {
AppLog.log("蓝牙打开失败"); AppLog.log('蓝牙打开失败');
} }
} }
} else { } else {
AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作"); AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作');
} }
}); });
} }
@ -248,34 +218,29 @@ class BlueManage {
/// ///
Future<void> startScan(int timeout, ScanDevicesCallBack scanDevicesCallBack, Future<void> startScan(int timeout, ScanDevicesCallBack scanDevicesCallBack,
{List<Guid>? idList}) async { {List<Guid>? idList}) async {
FlutterBluePlus.isSupported.then((isAvailable) async { FlutterBluePlus.isSupported.then((bool isAvailable) async {
if (isAvailable) { if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) { if (_adapterState == BluetoothAdapterState.on) {
try { try {
FlutterBluePlus.startScan(timeout: Duration(seconds: timeout)); FlutterBluePlus.startScan(timeout: Duration(seconds: timeout));
final StreamSubscription<List<ScanResult>> subscription =
var subscription = FlutterBluePlus.scanResults.listen((results) { FlutterBluePlus.scanResults.listen((List<ScanResult> results) {
scanDevices.clear(); scanDevices.clear();
for (var scanResult in results) { for (final ScanResult scanResult in results) {
// //
// if (scanResult.device.advName.isEmpty) {
// return;
// }
// AppLog.log("scanResult.device.advName:${scanResult.device.advName}"
// " scanResult.advertisementData.serviceUuids:${scanResult.advertisementData.serviceUuids}"
// " rssi:${scanResult.rssi}");
if (((scanResult.advertisementData.serviceUuids.isNotEmpty if (((scanResult.advertisementData.serviceUuids.isNotEmpty
? scanResult.advertisementData.serviceUuids[0] ? scanResult.advertisementData.serviceUuids[0]
: "") : '')
.toString() .toString()
.contains("758824")) && .contains('758824')) &&
(scanResult.rssi >= -100)) { (scanResult.rssi >= -100)) {
// id相同的元素 // id相同的元素
final knownDeviceIndex = scanDevices.indexWhere((d) => final int knownDeviceIndex = scanDevices.indexWhere(
(d.device.platformName == (ScanResult d) =>
scanResult.device.platformName) || (d.device.platformName ==
(d.advertisementData.advName == scanResult.device.platformName) ||
scanResult.advertisementData.advName)); (d.advertisementData.advName ==
scanResult.advertisementData.advName));
// -1 // -1
if (knownDeviceIndex >= 0) { if (knownDeviceIndex >= 0) {
scanDevices[knownDeviceIndex] = scanResult; scanDevices[knownDeviceIndex] = scanResult;
@ -284,32 +249,16 @@ class BlueManage {
} }
} }
} }
// String listStr = scanDevices
// .where((element) =>
// element.advertisementData.advName == 'TMH_dc8f928369ed' ||
// element.device.platformName == 'TMH_dc8f928369ed')
// .map((e) => 'advName:${e.advertisementData.advName} '
// 'serviceUuids:${e.advertisementData.serviceUuids} '
// '是否被重置:${e.advertisementData.serviceUuids[0].toString()[31]}')
// .join(',')
// .toString();
// if (listStr.trim() != '') {
// AppLog.log('--->扫描到的设备 ${listStr} ');
// }
scanDevicesCallBack(scanDevices); scanDevicesCallBack(scanDevices);
// EventBusManager().eventBusFir(scanDevices);
// FlutterBluePlus.stopScan();
}, onError: (e) { }, onError: (e) {
AppLog.log( AppLog.log(
"扫描失败:$e", '扫描失败:$e',
); );
}); });
FlutterBluePlus.cancelWhenScanComplete(subscription); FlutterBluePlus.cancelWhenScanComplete(subscription);
} catch (e) { } catch (e) {
AppLog.log("扫描失败"); AppLog.log('扫描失败');
} }
} else { } else {
try { try {
@ -317,25 +266,27 @@ class BlueManage {
await FlutterBluePlus.turnOn(); await FlutterBluePlus.turnOn();
} }
} catch (e) { } catch (e) {
AppLog.log("蓝牙打开失败"); AppLog.log('蓝牙打开失败');
} }
} }
} else { } else {
AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作"); AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作');
} }
}); });
} }
/// List senderData, /// List senderData,
Future<void> bludSendData( Future<void> blueSendData(
String deviceName, ConnectStateCallBack stateCallBack, String deviceName, ConnectStateCallBack stateCallBack,
{bool isAddEquipment = false}) async { {bool isAddEquipment = false}) async {
FlutterBluePlus.isSupported.then((isAvailable) async { FlutterBluePlus.isSupported.then((bool isAvailable) async {
if (isAvailable) { if (isAvailable) {
AppLog.log(
'蓝牙状态 系统蓝牙状态:$_adapterState 蓝牙连接状态:$bluetoothConnectionState');
if (_adapterState == BluetoothAdapterState.on) { if (_adapterState == BluetoothAdapterState.on) {
// //
if (bluetoothConnectionState != BluetoothConnectionState.connected) { if (bluetoothConnectionState != BluetoothConnectionState.connected) {
_connect(deviceName, (state) { _connect(deviceName, (BluetoothConnectionState state) {
stateCallBack(bluetoothConnectionState!); stateCallBack(bluetoothConnectionState!);
}, isAddEquipment: isAddEquipment); }, isAddEquipment: isAddEquipment);
} else { } else {
@ -346,11 +297,11 @@ class BlueManage {
stateCallBack(BluetoothConnectionState.disconnected); stateCallBack(BluetoothConnectionState.disconnected);
openBlue(); openBlue();
} catch (e) { } catch (e) {
AppLog.log("蓝牙打开失败"); AppLog.log('蓝牙打开失败');
} }
} }
} else { } else {
AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作"); AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作');
} }
}); });
} }
@ -360,13 +311,11 @@ class BlueManage {
String deviceName, ConnectStateCallBack connectStateCallBack, String deviceName, ConnectStateCallBack connectStateCallBack,
{bool isAddEquipment = false}) async { {bool isAddEquipment = false}) async {
connectDeviceName = deviceName; connectDeviceName = deviceName;
List<ScanResult> devicesList = scanDevices; final List<ScanResult> devicesList = scanDevices;
bool isExistDevice = scanDevices.any((element) => final bool isExistDevice = isExistScanDevices(connectDeviceName);
element.device.platformName == connectDeviceName ||
element.advertisementData.advName == connectDeviceName);
if (isAddEquipment == false || isExistDevice == false) { if (isAddEquipment == false && isExistDevice == false) {
//使 //使
startScanSingle(deviceName, 10, (List<ScanResult> scanDevices) { startScanSingle(deviceName, 10, (List<ScanResult> scanDevices) {
_connectDevice(scanDevices, deviceName, connectStateCallBack, _connectDevice(scanDevices, deviceName, connectStateCallBack,
@ -378,12 +327,20 @@ class BlueManage {
} }
} }
//
bool isExistScanDevices(String connectDeviceName) {
final bool isExistDevice = scanDevices.any((ScanResult element) =>
element.device.platformName == connectDeviceName ||
element.advertisementData.advName == connectDeviceName);
return isExistDevice;
}
Future<void> _connectDevice(List<ScanResult> devicesList, String deviceName, Future<void> _connectDevice(List<ScanResult> devicesList, String deviceName,
ConnectStateCallBack connectStateCallBack, ConnectStateCallBack connectStateCallBack,
{bool isAddEquipment = false}) async { {bool isAddEquipment = false}) async {
// //
// AppLog.log("devicesList:$devicesList"); // AppLog.log("devicesList:$devicesList");
final knownDeviceIndex = devicesList.indexWhere((d) => final int knownDeviceIndex = devicesList.indexWhere((ScanResult d) =>
(d.device.platformName == deviceName) || (d.device.platformName == deviceName) ||
(d.advertisementData.advName == deviceName)); (d.advertisementData.advName == deviceName));
@ -402,25 +359,21 @@ class BlueManage {
_initGetMtuSubscription(); _initGetMtuSubscription();
_initListenConnectionState(); _initListenConnectionState();
} }
// AppLog.log("1 connectDeviceId:$connectDeviceMacAddress connectDeviceName:$connectDeviceName");
// stopScan();
if (scanResult == null || connectDeviceMacAddress.isEmpty) { if (scanResult == null || connectDeviceMacAddress.isEmpty) {
// connectStateCallBack(BluetoothConnectionState.disconnected!);
return; return;
} }
// AppLog.log("调用了停止扫描的方法"); // AppLog.log("调用了停止扫描的方法");
await stopScan(); await stopScan();
if ((scanResult.advertisementData.serviceUuids[0].toString()[31] == "0") && if ((scanResult.advertisementData.serviceUuids[0].toString()[31] == '0') &&
isAddEquipment == false) { isAddEquipment == false) {
connectStateCallBack(BluetoothConnectionState.disconnected); connectStateCallBack(BluetoothConnectionState.disconnected);
EasyLoading.showToast("该锁已被重置".tr, duration: 2000.milliseconds); EasyLoading.showToast('该锁已被重置'.tr, duration: 2000.milliseconds);
return; return;
} }
// //
int maxAttempts = 3; const int maxAttempts = 3;
int attempt = 0; int attempt = 0;
while (attempt < maxAttempts) { while (attempt < maxAttempts) {
try { try {
@ -440,26 +393,18 @@ class BlueManage {
connectStateCallBack(BluetoothConnectionState.disconnected); connectStateCallBack(BluetoothConnectionState.disconnected);
} }
// await bluetoothConnectDevice!.connect();
if (bluetoothConnectionState == BluetoothConnectionState.connected) { if (bluetoothConnectionState == BluetoothConnectionState.connected) {
try { try {
bluetoothConnectDevice!.discoverServices().then((services) { bluetoothConnectDevice!
for (BluetoothService service in services) { .discoverServices()
// AppLog.log("11111service.remoteId:${service.remoteId}" .then((List<BluetoothService> services) {
// " service.uuid:${service.uuid}" for (final BluetoothService service in services) {
// " service.characteristics:${service.characteristics}"
// " service.includedServices:${service.includedServices}");
if (service.uuid == _serviceIdConnect) { if (service.uuid == _serviceIdConnect) {
for (BluetoothCharacteristic characteristic for (final BluetoothCharacteristic characteristic
in service.characteristics) { in service.characteristics) {
// Get.log("22222characteristic.remoteId:${characteristic.remoteId}"
// " characteristic.uuid:${characteristic.uuid}"
// " characteristic.secondaryServiceUuid:${characteristic.secondaryServiceUuid}"
// " characteristic.characteristicUuid:${characteristic.characteristicUuid}");
if (characteristic.characteristicUuid == if (characteristic.characteristicUuid ==
_characteristicIdSubscription) { _characteristicIdSubscription) {
_subScribeToCharacteristic(characteristic); _subScribeToCharacteristic(characteristic);
// AppLog.log('Discovering services finished');
bluetoothConnectionState = BluetoothConnectionState.connected; bluetoothConnectionState = BluetoothConnectionState.connected;
connectStateCallBack(bluetoothConnectionState!); connectStateCallBack(bluetoothConnectionState!);
} }
@ -477,47 +422,41 @@ class BlueManage {
} }
} }
// ,
var allData = <int>[];
//
var lastTimeData = <int>[];
int? dataLen;
_subScribeToCharacteristic(BluetoothCharacteristic characteristic) async { Future<void> _subScribeToCharacteristic(
final subscription = characteristic.onValueReceived.listen((data) { BluetoothCharacteristic characteristic) async {
// AppLog.log("订阅获取的数据:$data"); final StreamSubscription<List<int>> subscription =
characteristic.onValueReceived.listen((List<int> data) {
AppLog.log('订阅获取的数据: $data ');
if (data == lastTimeData || data.isEmpty) { if (data == lastTimeData || data.isEmpty) {
return; return;
} else { } else {
lastTimeData = data; lastTimeData = data;
} }
// code to handle incoming data final bool dataHeadCorrect = isDataHeadCorrect(data);
// AppLog.log("subscribeToCharacteristic: deviceId = ${characteristic.deviceId} characteristicId =${characteristic.characteristicId}---上报来的数据data = $data"); final bool allDataHeadCorrect = isDataHeadCorrect(allData);
if ((data[0] == 0xEF) && if (dataHeadCorrect && allDataHeadCorrect) {
(data[1] == 0x01) && //
(data[2] == 0xEE) && allData = <int>[];
(data[3] == 0x02)) { }
if (dataHeadCorrect) {
// //
// //
dataLen = data[8] * 256 + data[9]; // 16 dataLen = data[8] * 256 + data[9]; // 16
// AppLog.log("dataLen1111:$dataLen getDataLength:${data.length} data:$data");
if (dataLen! + 14 > data.length) { if (dataLen! + 14 > data.length) {
// //
allData.addAll(data); allData.addAll(data);
} else { } else {
// //
allData.addAll(data); allData.addAll(data);
// AppLog.log("dataLen2222:$dataLen getDataLength:${data.length}");
CommandReciverManager.appDataReceive(allData); CommandReciverManager.appDataReceive(allData);
// //
allData = <int>[]; allData = <int>[];
} }
} else { } else if (allDataHeadCorrect) {
// //
allData.addAll(data); allData.addAll(data);
// var len = allData[8] * 256 + allData[9];
// AppLog.log("dataLen3333:$dataLen allData.length:${allData.length} allData:$allData");
if (((dataLen ?? 0) + 14) <= allData.length) { if (((dataLen ?? 0) + 14) <= allData.length) {
// //
CommandReciverManager.appDataReceive(allData); CommandReciverManager.appDataReceive(allData);
@ -526,100 +465,46 @@ class BlueManage {
} }
} }
}); });
// cleanup: cancel subscription when disconnected
bluetoothConnectDevice!.cancelWhenDisconnected(subscription); bluetoothConnectDevice!.cancelWhenDisconnected(subscription);
// enable notifications
await characteristic.setNotifyValue(true); await characteristic.setNotifyValue(true);
}
// characteristic.setNotifyValue(true).then((_) { //
// AppLog.log("启动对特性的通知。当特性的值发生变化时,设备会发送一个通知"); bool isDataHeadCorrect(List<int> data) {
// characteristic.lastValueStream.listen((data) { if (data.length < 4) {
// AppLog.log("订阅获取的数据:$data"); return false;
// // do something with new value }
// if(data == lastTimeData || data.isEmpty){ //239, 1, 238, 2,
// return; if ((data[0] == 0xEF) &&
// }else{ (data[1] == 0x01) &&
// lastTimeData = data; (data[2] == 0xEE) &&
// } (data[3] == 0x02)) {
// // code to handle incoming data return true;
// // AppLog.log("subscribeToCharacteristic: deviceId = ${characteristic.deviceId} characteristicId =${characteristic.characteristicId}---上报来的数据data = $data"); } else {
// if ((data[0] == 0xEF) && (data[1] == 0x01) && (data[2] == 0xEE) && (data[3] == 0x02)) { return false;
// // }
// //
// dataLen = data[8] * 256 + data[9]; // 16
// // AppLog.log("dataLen1111:$dataLen getDataLength:${data.length}");
// if (dataLen! + 12 > data.length) {
// //
// allData.addAll(data);
// } else {
// //
// allData.addAll(data);
// // AppLog.log("dataLen2222:$dataLen getDataLength:${data.length}");
// CommandReciverManager.appDataReceive(allData);
// //
// allData = <int>[];
// }
// } else {
// //
// allData.addAll(data);
// // var len = allData[8] * 256 + allData[9];
// // AppLog.log("dataLen3333:$dataLen");
// if ((dataLen! + 14) <= allData.length) {
// // AppLog.log("44444数据被解析了");
// //
// CommandReciverManager.appDataReceive(allData);
// //
// allData = <int>[];
// }
// }
// });
// });
} }
// //
Future<void> writeCharacteristicWithResponse(List<int> value) async { Future<void> writeCharacteristicWithResponse(List<int> value) async {
List<BluetoothService> services = final List<BluetoothService> services =
await bluetoothConnectDevice!.discoverServices(); await bluetoothConnectDevice!.discoverServices();
for (BluetoothService service in services) { for (final BluetoothService service in services) {
// AppLog.log("33333 service.remoteId:${service.remoteId}"
// " service.uuid:${service.uuid}\n\n"
// " service.characteristics:${service.characteristics}\n\n"
// " service.includedServices:${service.includedServices}");
if (service.uuid == _serviceIdConnect) { if (service.uuid == _serviceIdConnect) {
for (BluetoothCharacteristic characteristic for (final BluetoothCharacteristic characteristic
in service.characteristics) { in service.characteristics) {
// AppLog.log("44444 characteristic.remoteId:${characteristic.remoteId}"
// " characteristic.uuid:${characteristic.uuid}\n\n"
// " characteristic.secondaryServiceUuid:${characteristic
// .secondaryServiceUuid}\n\n"
// " characteristic.characteristicUuid:${characteristic
// .characteristicUuid}");
if (characteristic.characteristicUuid == _characteristicIdWrite) { if (characteristic.characteristicUuid == _characteristicIdWrite) {
try { try {
List<int> valueList = value; final List<int> valueList = value;
List subData = splitList(valueList, _mtuSize!); final List subData = splitList(valueList, _mtuSize!);
// AppLog.log('writeCharacteristicWithResponse _mtuSize:$_mtuSize 得到的分割数据:$subData'); // AppLog.log('writeCharacteristicWithResponse _mtuSize:$_mtuSize 得到的分割数据:$subData');
for (int i = 0; i < subData.length; i++) { for (int i = 0; i < subData.length; i++) {
if (characteristic.properties.writeWithoutResponse) { if (characteristic.properties.writeWithoutResponse) {
// 使WRITE_NO_RESPONSE属性写入值 // 使WRITE_NO_RESPONSE属性写入值
await characteristic await characteristic.write(subData[i], withoutResponse: true);
.write(subData[i], withoutResponse: true)
.then((value) async {
// await Future.delayed(const Duration(milliseconds: 1)).then((
// value) async {
// AppLog.log('分包发送成功了');
// });
});
} else if (characteristic.properties.write) { } else if (characteristic.properties.write) {
// 使WRITE属性写入值 // 使WRITE属性写入值
await characteristic.write(subData[i]).then((value) async { await characteristic.write(subData[i]);
// await Future.delayed(const Duration(milliseconds: 1)).then((
// value) async {
// AppLog.log('分包发送成功了');
// });
});
} else { } else {
// //
throw Exception( throw Exception(
@ -634,122 +519,45 @@ class BlueManage {
} }
} }
} }
// List<BluetoothService> services = await bluetoothConnectDevice!.discoverServices();
// BluetoothCharacteristic characteristic = services
// .firstWhere((service) => service.uuid == _serviceIdWrite)
// .characteristics
// .firstWhere((char) => char.uuid == _characteristicIdWrite);
// try {
// List<int> valueList = value;
// List subData = splitList(valueList, _mtuSize!);
// AppLog.log('writeCharacteristicWithResponse 得到的分割数据:$subData');
//
// for (int i = 0; i < subData.length; i++) {
// await characteristic.write(subData[i]).then((value) async {
// await Future.delayed(const Duration(milliseconds: 1)).then((value) async {
// AppLog.log('分包发送成功了');
// });
// });
// }
// } on Exception catch (e, s) {
// AppLog.log('Error occurred when writing: $e');
// AppLog.log(s);
// rethrow;
// }
} }
//
Future<void> writeNull() async {
List<BluetoothService> services =
await bluetoothConnectDevice!.discoverServices();
for (BluetoothService service in services) {
if (service.uuid == _serviceIdConnect) {
for (BluetoothCharacteristic characteristic
in service.characteristics) {
if (characteristic.characteristicUuid == _characteristicIdWrite) {
try {
List<int> valueList = [1];
AppLog.log('APP写入 writeNull ');
await characteristic.write(valueList);
} on Exception catch (e, s) {
AppLog.log('APP写入失败 writeNull : $e $s');
rethrow;
}
}
}
}
}
}
//
// Future<List<int>> _readCharacteristic(QualifiedCharacteristic characteristic) async {
// try {
// final result =
// await _flutterReactiveBle!.readCharacteristic(characteristic);
// AppLog.log("readListresult$result");
// return result;
// } on Exception catch (e, s) {
// AppLog.log(
// 'Error occurred when reading ${characteristic.characteristicId} : $e',
// );
// rethrow;
// }
// }
// Future<void> writeCharacteristicWithoutResponse(
// QualifiedCharacteristic characteristic, List<int> value) async {
// try {
// await _flutterReactiveBle!
// .writeCharacteristicWithoutResponse(characteristic, value: value);
// } on Exception catch (e, s) {
// // ignore: avoid_print
// AppLog.log(s);
// rethrow;
// }
// }
// //
Future<void> stopScan() async { Future<void> stopScan() async {
try { try {
await FlutterBluePlus.stopScan(); await FlutterBluePlus.stopScan();
} catch (e) { } catch (e) {
AppLog.log("停止扫描失败"); AppLog.log('停止扫描失败');
} }
} }
// //
Future<void> disconnect() async { Future<void> disconnect() async {
try { try {
// if(bluetoothConnectDevice != null && bluetoothConnectDevice!.connectionState == BluetoothConnectionState.connected){ connectDeviceMacAddress = '';
connectDeviceMacAddress = "";
if (bluetoothConnectionState == BluetoothConnectionState.connected) { if (bluetoothConnectionState == BluetoothConnectionState.connected) {
// await writeNull();
// await Future.delayed(const Duration(milliseconds: 1000));
// //
await bluetoothConnectDevice!.disconnect(timeout: 2); await bluetoothConnectDevice!.disconnect(timeout: 3);
AppLog.log("断开连接成功"); AppLog.log('断开连接成功');
} }
// }
} on Exception catch (e, _) { } on Exception catch (e, _) {
AppLog.log("断开连接失败: $e"); AppLog.log('断开连接失败: $e');
} finally { } finally {
bluetoothConnectionState = BluetoothConnectionState.disconnected; bluetoothConnectionState = BluetoothConnectionState.disconnected;
} }
} }
openBlue() async { Future<void> openBlue() async {
if (Platform.isAndroid) { if (Platform.isAndroid) {
await FlutterBluePlus.turnOn(); await FlutterBluePlus.turnOn();
} }
if (Platform.isIOS) { if (Platform.isIOS) {
EasyLoading.showToast("请开启蓝牙".tr, duration: 2000.milliseconds); EasyLoading.showToast('请开启蓝牙'.tr, duration: 2000.milliseconds);
} }
} }
disposed() { void disposed() {
_sendStreamSubscription?.cancel(); _sendStreamSubscription?.cancel();
_mtuSubscription!.cancel(); _mtuSubscription!.cancel();
// _scanResultsSubscription!.cancel();
_adapterStateStateSubscription!.cancel(); _adapterStateStateSubscription!.cancel();
_connectionStateSubscription!.cancel(); _connectionStateSubscription!.cancel();
} }

View File

@ -6,6 +6,7 @@ import '../app_settings/app_settings.dart';
import 'io_type.dart'; import 'io_type.dart';
abstract class Reply{ abstract class Reply{
Reply.parseData(this.commandType, List<int> dataDetail);
CommandType? commandType; CommandType? commandType;
@ -13,122 +14,121 @@ abstract class Reply{
int status = 0; int status = 0;
List<int> data = []; List<int> data = [];
static String logTag= '锁 -> App指令订阅类型 :'; static String logTag= '锁 -> App指令订阅类型 :';
Reply.parseData(this.commandType, List<int> dataDetail);
void errorWithStstus(int status){ void errorWithStstus(int status){
switch(status){ switch(status){
case 0x00: case 0x00:
// //
AppLog.log("$logTag ${commandType?.typeName} 0x00 成功"); AppLog.log('$logTag ${commandType?.typeName} 0x00 成功');
break; break;
case 0x01: case 0x01:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x01 包格式错误"); AppLog.log('$logTag ${commandType!.typeName} 0x01 包格式错误');
showErrorMessage("包格式错误"); showErrorMessage('包格式错误');
break; break;
case 0x02: case 0x02:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x02 密码错误"); AppLog.log('$logTag ${commandType!.typeName} 0x02 密码错误');
showErrorMessage("密码错误"); showErrorMessage('密码错误');
break; break;
case 0x03: case 0x03:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x03 网络中断"); AppLog.log('$logTag ${commandType!.typeName} 0x03 网络中断');
showErrorMessage("网络中断"); showErrorMessage('网络中断');
break; break;
case 0x04: case 0x04:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x04 用户未登记"); AppLog.log('$logTag ${commandType!.typeName} 0x04 用户未登记');
showErrorMessage("用户未登记"); showErrorMessage('用户未登记');
break; break;
case 0x05: case 0x05:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x05 参数错误"); AppLog.log('$logTag ${commandType!.typeName} 0x05 参数错误');
showErrorMessage("参数错误"); showErrorMessage('参数错误');
break; break;
case 0x06: case 0x06:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x06 需要鉴权"); AppLog.log('$logTag ${commandType!.typeName} 0x06 需要鉴权');
// showErrorMessage("需要鉴权"); // showErrorMessage("需要鉴权");
break; break;
case 0x07: case 0x07:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x07 无权限"); AppLog.log('$logTag ${commandType!.typeName} 0x07 无权限');
// showErrorMessage("无权限"); // showErrorMessage("无权限");
break; break;
case 0x08: case 0x08:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x08 应答超时"); AppLog.log('$logTag ${commandType!.typeName} 0x08 应答超时');
showErrorMessage("应答超时"); showErrorMessage('应答超时');
break; break;
case 0x09: case 0x09:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x09 权限校验错误"); AppLog.log('$logTag ${commandType!.typeName} 0x09 权限校验错误');
showErrorMessage("权限校验错误"); showErrorMessage('权限校验错误');
break; break;
case 0x0a: case 0x0a:
// //
showErrorMessage("钥匙不存在"); showErrorMessage('钥匙不存在');
AppLog.log("$logTag ${commandType!.typeName} 0x0a 钥匙不存在"); AppLog.log('$logTag ${commandType!.typeName} 0x0a 钥匙不存在');
break; break;
case 0x0b: case 0x0b:
// //
showErrorMessage("钥匙过期"); showErrorMessage('钥匙过期');
AppLog.log("$logTag ${commandType!.typeName} 0x0b 钥匙过期"); AppLog.log('$logTag ${commandType!.typeName} 0x0b 钥匙过期');
break; break;
case 0x0c: case 0x0c:
// //
showErrorMessage("钥匙数量已到上限"); showErrorMessage('钥匙数量已到上限');
AppLog.log("$logTag ${commandType!.typeName} 0x0c 钥匙数量已到上限"); AppLog.log('$logTag ${commandType!.typeName} 0x0c 钥匙数量已到上限');
break; break;
case 0x0d: case 0x0d:
// //
showErrorMessage("钥匙无效"); showErrorMessage('钥匙无效');
AppLog.log("$logTag ${commandType!.typeName} 0x0d 钥匙无效"); AppLog.log('$logTag ${commandType!.typeName} 0x0d 钥匙无效');
break; break;
case 0x0e: case 0x0e:
// //
showErrorMessage("钥匙已存在"); showErrorMessage('钥匙已存在');
AppLog.log("$logTag ${commandType!.typeName} 0x0e 钥匙已存在"); AppLog.log('$logTag ${commandType!.typeName} 0x0e 钥匙已存在');
break; break;
case 0x0f: case 0x0f:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x0f 用户已存在"); AppLog.log('$logTag ${commandType!.typeName} 0x0f 用户已存在');
showErrorMessage("用户已存在"); showErrorMessage('用户已存在');
break; break;
case 0x10: case 0x10:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x11 密码失效"); AppLog.log('$logTag ${commandType!.typeName} 0x11 密码失效');
showErrorMessage("密码失效"); showErrorMessage('密码失效');
break; break;
case 0x11: case 0x11:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x11 无效指令"); AppLog.log('$logTag ${commandType!.typeName} 0x11 无效指令');
showErrorMessage("无效指令"); showErrorMessage('无效指令');
break; break;
case 0x12: case 0x12:
// //
AppLog.log("$logTag ${commandType!.typeName} 0x12 门锁时间异常"); AppLog.log('$logTag ${commandType!.typeName} 0x12 门锁时间异常');
showErrorMessage("门锁时间异常"); showErrorMessage('门锁时间异常');
break; break;
case 0x15: case 0x15:
// APP() // APP()
AppLog.log("$logTag ${commandType!.typeName} 0x15 APP(手机)未联网"); AppLog.log('$logTag ${commandType!.typeName} 0x15 APP(手机)未联网');
showErrorMessage("APP(手机)未联网"); showErrorMessage('APP(手机)未联网');
break; break;
case 0x16: case 0x16:
// ... // ...
AppLog.log("$logTag ${commandType!.typeName} $status 正在开锁中..."); AppLog.log('$logTag ${commandType!.typeName} $status 正在开锁中...');
showErrorMessage("正在开锁中..."); showErrorMessage('正在开锁中...');
break; break;
case 0xff: case 0xff:
// //
AppLog.log("$logTag ${commandType!.typeName} 0xff 异常,未知错误"); AppLog.log('$logTag ${commandType!.typeName} 0xff 异常,未知错误');
showErrorMessage("异常,未知错误"); showErrorMessage('异常,未知错误');
break; break;
default: default:
// //
AppLog.log("$logTag ${commandType!.typeName} $status 蓝牙返回其他错误问题"); AppLog.log('$logTag ${commandType!.typeName} $status 蓝牙返回其他错误问题');
break; break;
} }
} }

View File

@ -39,7 +39,7 @@ abstract class SenderProtocol extends IOData {
? '子命令:${data[3]}' : ''} \n参数是:\n${toString()} \n加密之前数据是:\n$data :${data.length}"); ? '子命令:${data[3]}' : ''} \n参数是:\n${toString()} \n加密之前数据是:\n$data :${data.length}");
} }
//TODO:Ï //TODO:
List<int> packageData() { List<int> packageData() {
commandData = messageDetail(); commandData = messageDetail();
List<int> commandList = []; List<int> commandList = [];

View File

@ -52,12 +52,12 @@ import 'io_tool/manager_event_bus.dart';
import 'sm4Encipher/sm4.dart'; import 'sm4Encipher/sm4.dart';
class CommandReciverManager { class CommandReciverManager {
static void appDataReceive(List<int> data) async { static Future<void> appDataReceive(List<int> data) async {
/// ///
if (data.isEmpty) { if (data.isEmpty) {
return; return;
} }
int dataSize = data.length; final int dataSize = data.length;
// 13 // 13
if (dataSize < 13) { if (dataSize < 13) {
return; return;
@ -67,20 +67,20 @@ class CommandReciverManager {
(data[1] == 0x01) && (data[1] == 0x01) &&
(data[2] == 0xEE) && (data[2] == 0xEE) &&
(data[3] == 0x02)) { (data[3] == 0x02)) {
var tmpType = (data[7] & 0x0f); // final int tmpType = data[7] & 0x0f; //
// AppLog.log("temType:$tmpType"); // AppLog.log('temType:$tmpType');
var dataLen = data[8] * 256 + data[9]; // 16 final int dataLen = data[8] * 256 + data[9]; // 16
var oriLen = data[10] * 256 + data[11]; // 16 final int oriLen = data[10] * 256 + data[11]; // 16
// AppLog.log("dataLen:$dataLen oriLen:$oriLen"); // AppLog.log("dataLen:$dataLen oriLen:$oriLen");
List<int> oriDataList = []; List<int> oriDataList = <int>[];
switch (tmpType) { switch (tmpType) {
case 0: // case 0: //
// for (var i = 0; i < oriLen ; i++) { // for (var i = 0; i < oriLen ; i++) {
// oriDataList.add(data[12 + i]); // oriDataList.add(data[12 + i]);
// } // }
oriDataList = data.sublist(12, 12 + dataLen); oriDataList = data.sublist(12, 12 + dataLen);
AppLog.log("不加密 :$oriDataList"); AppLog.log('不加密 :$oriDataList');
break; break;
case 1: case 1:
//AES128 //AES128
@ -88,7 +88,7 @@ class CommandReciverManager {
case 2: case 2:
// SM4 // SM4
// //
var getDataList = data.sublist(12, 12 + dataLen); final List<int> getDataList = data.sublist(12, 12 + dataLen);
// //
// String key = SM4.createHexKey(key: IoManager().getCurrentDeviceLockId); // String key = SM4.createHexKey(key: IoManager().getCurrentDeviceLockId);
@ -96,39 +96,39 @@ class CommandReciverManager {
key: utf8.encode(BlueManage().connectDeviceName), key: utf8.encode(BlueManage().connectDeviceName),
mode: SM4CryptoMode.ECB); mode: SM4CryptoMode.ECB);
oriDataList = oriDataList.sublist(0, oriLen); oriDataList = oriDataList.sublist(0, oriLen);
AppLog.log("APP收到的解密后的数据:$oriDataList"); AppLog.log('APP收到的解密后的数据:$oriDataList');
break; break;
case 3: case 3:
//SM4 //SM4
// //
var getDataList = data.sublist(12, 12 + dataLen); final List<int> getDataList = data.sublist(12, 12 + dataLen);
var res = await Storage.getStringList(saveBluePrivateKey); final List<String>? res = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(res!); final List<int> getPrivateKeyList = changeStringListToIntList(res!);
// //
oriDataList = SM4.decrypt(getDataList, oriDataList = SM4.decrypt(getDataList,
key: getPrivateKeyList, mode: SM4CryptoMode.ECB); key: getPrivateKeyList, mode: SM4CryptoMode.ECB);
oriDataList = oriDataList.sublist(0, oriLen); oriDataList = oriDataList.sublist(0, oriLen);
AppLog.log("APP收到的解密后的数据:$oriDataList"); AppLog.log('APP收到的解密后的数据:$oriDataList data:$data');
break; break;
} }
parseData(oriDataList).then((Reply? value) async { parseData(oriDataList).then((Reply? value) async {
EasyLoading.dismiss(); EasyLoading.dismiss();
await EventBusManager().eventBusFir(value); await EventBusManager().eventBusFir(value);
}).catchError((error) { }).catchError((error) {
AppLog.log("APP解析数据时发生错误: $error"); AppLog.log('APP解析数据时发生错误: $error');
}); });
} }
} }
static Future<Reply?> parseData(List<int> data) async { static Future<Reply?> parseData(List<int> data) async {
if (data.isNotEmpty) { if (data.isNotEmpty) {
var cmd = data[0] * 256 + data[1]; final int cmd = data[0] * 256 + data[1];
CommandType commandType = ExtensionCommandType.getCommandType(cmd); final CommandType commandType = ExtensionCommandType.getCommandType(cmd);
await IoManager().increaseCommandIndex(); await IoManager().increaseCommandIndex();
// data.removeRange(0, 2); // data.removeRange(0, 2);
var reply; Reply? reply;
switch (commandType) { switch (commandType) {
case CommandType.getLockPublicKey: case CommandType.getLockPublicKey:
{ {
@ -234,7 +234,7 @@ class CommandReciverManager {
case CommandType.generalExtendedCommond: case CommandType.generalExtendedCommond:
{ {
// //
int subType = data[3]; final int subType = data[3];
switch (subType) { switch (subType) {
case 2: case 2:
{ {
@ -467,5 +467,6 @@ class CommandReciverManager {
} }
return reply; return reply;
} }
return null;
} }
} }

View File

@ -70,4 +70,13 @@ class XSConstantMacro {
static int catEyeWorkModeStayCapture = 2; // static int catEyeWorkModeStayCapture = 2; //
static int catEyeWorkModeRealTimeMonitoring = 3; // static int catEyeWorkModeRealTimeMonitoring = 3; //
static int catEyeWorkModeCustom = 4; // static int catEyeWorkModeCustom = 4; //
//
static int userTypeSuperAdmin = 110301; //
static int userTypeAuthorizedAdmin = 110302; //
//
static int keyRightAdmin = 1; //
static int keyRightOrdinary = 2; //
} }

View File

@ -86,7 +86,7 @@ class F {
switch (appFlavor) { switch (appFlavor) {
case Flavor.local: case Flavor.local:
return 'https://ge.lock.star-lock.cn'; // return 'https://ge.lock.star-lock.cn'; //
// return 'http://192.168.1.15:8022'; // // return 'http://192.168.1.15:8022'; //
case Flavor.dev: case Flavor.dev:
return 'https://dev.lock.star-lock.cn'; return 'https://dev.lock.star-lock.cn';
case Flavor.pre: case Flavor.pre:
@ -95,7 +95,7 @@ class F {
return 'https://lock.skychip.top'; return 'https://lock.skychip.top';
case Flavor.xhj: case Flavor.xhj:
return 'https://lock.xhjcn.ltd'; return 'https://lock.xhjcn.ltd';
// return 'https://pre.lock.star-lock.cn'; // return 'https://pre.lock.star-lock.cn';
default: default:
throw Exception('flavor[$name] apiPrefix not found'); throw Exception('flavor[$name] apiPrefix not found');
} }
@ -125,4 +125,19 @@ class F {
throw Exception('flavor[$name] aMapKey not found'); throw Exception('flavor[$name] aMapKey not found');
} }
} }
//
static bool get isProductionEnv {
switch (appFlavor) {
case Flavor.local:
case Flavor.dev:
case Flavor.pre:
return false;
case Flavor.sky:
case Flavor.xhj:
return true;
default:
return false;
}
}
} }

View File

@ -1,8 +1,12 @@
import 'dart:io'; import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bugly_plugin/flutter_bugly_plugin.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/appRouters.dart'; import 'package:star_lock/appRouters.dart';
import 'package:star_lock/blue/blue_manage.dart';
import 'package:star_lock/login/login/entity/LoginEntity.dart';
import 'package:star_lock/mine/mine/starLockMine_state.dart';
import 'package:star_lock/tools/baseGetXController.dart'; import 'package:star_lock/tools/baseGetXController.dart';
import 'package:star_lock/tools/xs_jPhush.dart'; import 'package:star_lock/tools/xs_jPhush.dart';
@ -14,34 +18,15 @@ import 'starLock_login_state.dart';
class StarLockLoginLogic extends BaseGetXController { class StarLockLoginLogic extends BaseGetXController {
final StarLockLoginState state = StarLockLoginState(); final StarLockLoginState state = StarLockLoginState();
final stateMyLogic = Get.put(StarLockMineLogic()).state; final StarLockMineState stateMyLogic = Get.put(StarLockMineLogic()).state;
int indexFocusNode = noneFocusNode; int indexFocusNode = noneFocusNode;
static int noneFocusNode = 0; static int noneFocusNode = 0;
static int emailOrPhoneFocusNode = 1; static int emailOrPhoneFocusNode = 1;
static int pwdFocusNode = 2; static int pwdFocusNode = 2;
@override
void onInit() {
super.onInit();
// state.emailOrPhoneFocusNode.addListener(() {
// if (state.emailOrPhoneFocusNode.hasFocus) {
// indexFocusNode = emailOrPhoneFocusNode;
// } else {
// changeInputFocusNode();
// }
// });
// state.pwdFocusNode.addListener(() {
// if (state.pwdFocusNode.hasFocus) {
// indexFocusNode = pwdFocusNode;
// } else {
// changeInputFocusNode();
// }
// });
}
// //
void changeInputFocusNode() { void changeInputFocusNode() {
Future.delayed(Duration(milliseconds: 100), () { Future<void>.delayed(const Duration(milliseconds: 100), () {
if (indexFocusNode == noneFocusNode) { if (indexFocusNode == noneFocusNode) {
return; return;
} }
@ -53,9 +38,9 @@ class StarLockLoginLogic extends BaseGetXController {
}); });
} }
void login() async { Future<void> login() async {
var entity = await ApiRepository.to.login( final LoginEntity entity = await ApiRepository.to.login(
loginType: "1", loginType: '1',
password: state.pwd.value, password: state.pwd.value,
countryCode: state.countryCode.value, countryCode: state.countryCode.value,
username: state.emailOrPhone.value); username: state.emailOrPhone.value);
@ -63,11 +48,10 @@ class StarLockLoginLogic extends BaseGetXController {
Storage.saveLoginData(entity.data); Storage.saveLoginData(entity.data);
Storage.setBool(saveIsVip, entity.data!.isVip == 0 ? false : true); Storage.setBool(saveIsVip, entity.data!.isVip == 0 ? false : true);
eventBus.fire(MineInfoChangeRefreshUI()); eventBus.fire(MineInfoChangeRefreshUI());
// Get.back();
// Get.toNamed(Routers.starLockMain);
XSJPushProvider().initJPushService(); XSJPushProvider().initJPushService();
XSJPushProvider().initLocalNotification(false); XSJPushProvider().initLocalNotification(false);
Get.offNamedUntil(Routers.starLockMain, (route) => false); Get.offNamedUntil(Routers.starLockMain, (Route route) => false);
BlueManage().scanDevices.clear(); //
} }
} }

View File

@ -1,14 +1,19 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_bugly_plugin/flutter_bugly_plugin.dart';
import 'package:get/get.dart';
import 'package:star_lock/flavors.dart'; import 'package:star_lock/flavors.dart';
import 'package:star_lock/translations/trans_lib.dart'; import 'package:star_lock/tools/bugly/bugly_tool.dart';
import 'app.dart';
import 'package:star_lock/tools/device_info_service.dart'; import 'package:star_lock/tools/device_info_service.dart';
import 'package:star_lock/tools/platform_info_services.dart'; import 'package:star_lock/tools/platform_info_services.dart';
import 'package:star_lock/translations/trans_lib.dart';
import 'app.dart';
import 'app_settings/app_settings.dart'; import 'app_settings/app_settings.dart';
import 'tools/store_service.dart'; import 'tools/store_service.dart';
import 'package:get/get.dart';
// flavorizr.yaml // flavorizr.yaml
FutureOr<void> main() async { FutureOr<void> main() async {
@ -19,20 +24,23 @@ FutureOr<void> main() async {
// //
await _initTranslation(); await _initTranslation();
// bugly错误日志监控
await BuglyTool.init();
runApp(const MyApp()); runApp(const MyApp());
if (AppPlatform.isAndroid) { if (AppPlatform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle systemUiOverlayStyle =
const SystemUiOverlayStyle(statusBarColor: Colors.transparent); SystemUiOverlayStyle(statusBarColor: Colors.transparent);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle); SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
} }
} }
// //
Future _initTranslation() async => TranslationLoader.loadTranslation( Future _initTranslation() async => TranslationLoader.loadTranslation(
zhSource: "images/lan/lan_zh.json", zhSource: 'images/lan/lan_zh.json',
enSource: "images/lan/lan_en.json", enSource: 'images/lan/lan_en.json',
keySource: "images/lan/lan_keys.json", keySource: 'images/lan/lan_keys.json',
); );
// //

View File

@ -5,13 +5,17 @@ import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/appRouters.dart'; import 'package:star_lock/appRouters.dart';
import 'package:star_lock/app_settings/app_settings.dart'; import 'package:star_lock/app_settings/app_settings.dart';
import 'package:star_lock/login/login/entity/LoginEntity.dart';
import 'package:star_lock/main/lockDetail/authorizedAdmin/authorizedAdmin/authorizedAdmin_entity.dart';
import 'package:star_lock/main/lockDetail/authorizedAdmin/authorizedAdmin/notice_template_entity.dart';
import 'package:star_lock/mine/valueAddedServices/advancedFunctionRecord/advancedFunctionRecord_entity.dart'; import 'package:star_lock/mine/valueAddedServices/advancedFunctionRecord/advancedFunctionRecord_entity.dart';
import 'package:star_lock/tools/NativeInteractionTool.dart';
import 'package:star_lock/tools/dateTool.dart'; import 'package:star_lock/tools/dateTool.dart';
import 'package:star_lock/tools/showCupertinoAlertView.dart'; import 'package:star_lock/tools/showCupertinoAlertView.dart';
import '../../../../blue/blue_manage.dart'; import '../../../../blue/blue_manage.dart';
import '../../../../blue/io_reply.dart';
import '../../../../blue/io_protocol/io_transferPermissions.dart'; import '../../../../blue/io_protocol/io_transferPermissions.dart';
import '../../../../blue/io_reply.dart';
import '../../../../blue/io_tool/io_tool.dart'; import '../../../../blue/io_tool/io_tool.dart';
import '../../../../blue/io_tool/manager_event_bus.dart'; import '../../../../blue/io_tool/manager_event_bus.dart';
import '../../../../blue/sender_manage.dart'; import '../../../../blue/sender_manage.dart';
@ -26,18 +30,21 @@ import 'authorizedAdmin_state.dart';
class AuthorizedAdminLogic extends BaseGetXController { class AuthorizedAdminLogic extends BaseGetXController {
final AuthorizedAdminState state = AuthorizedAdminState(); final AuthorizedAdminState state = AuthorizedAdminState();
int? keyId;
// //
late StreamSubscription<Reply> _replySubscription; late StreamSubscription<Reply> _replySubscription;
void _initReplySubscription() { void _initReplySubscription() {
_replySubscription = _replySubscription =
EventBusManager().eventBus!.on<Reply>().listen((reply) async { EventBusManager().eventBus!.on<Reply>().listen((Reply reply) async {
// //
if (reply is TransferPermissionsReply) { if (reply is TransferPermissionsReply) {
var token = reply.data.sublist(2, 6); final List<int> token = reply.data.sublist(2, 6);
var saveStrList = changeIntListToStringList(token); final List<String> saveStrList = changeIntListToStringList(token);
Storage.setStringList(saveBlueToken, saveStrList); Storage.setStringList(saveBlueToken, saveStrList);
int status = reply.data[6]; final int status = reply.data[6];
switch (status) { switch (status) {
case 0x00: case 0x00:
@ -45,20 +52,24 @@ class AuthorizedAdminLogic extends BaseGetXController {
break; break;
case 0x06: case 0x06:
// //
var privateKey = await Storage.getStringList(saveBluePrivateKey); final List<String>? privateKey =
List<int> getPrivateKeyList = await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList =
changeStringListToIntList(privateKey!); changeStringListToIntList(privateKey!);
var publicKey = await Storage.getStringList(saveBluePublicKey); final List<String>? publicKey =
List<int> publicKeyDataList = changeStringListToIntList(publicKey!); await Storage.getStringList(saveBluePublicKey);
final List<int> publicKeyDataList =
changeStringListToIntList(publicKey!);
var token = await Storage.getStringList(saveBlueToken); final List<String>? token =
List<int> getTokenList = changeStringListToIntList(token!); await Storage.getStringList(saveBlueToken);
final List<int> getTokenList = changeStringListToIntList(token!);
IoSenderManage.senderFactoryDataReset( IoSenderManage.senderFactoryDataReset(
lockID: BlueManage().connectDeviceName, lockID: BlueManage().connectDeviceName,
userID: await Storage.getUid(), userID: await Storage.getUid(),
keyID: "1", keyID: '1',
needAuthor: 1, needAuthor: 1,
publicKey: publicKeyDataList, publicKey: publicKeyDataList,
privateKey: getPrivateKeyList, privateKey: getPrivateKeyList,
@ -73,24 +84,28 @@ class AuthorizedAdminLogic extends BaseGetXController {
// //
Future<void> transferPermissionsAction() async { Future<void> transferPermissionsAction() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState state) async { (BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.connected) { if (state == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); final List<String>? privateKey =
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList =
changeStringListToIntList(privateKey!);
var publicKey = await Storage.getStringList(saveBluePublicKey); final List<String>? publicKey =
List<int> publicKeyDataList = changeStringListToIntList(publicKey!); await Storage.getStringList(saveBluePublicKey);
final List<int> publicKeyDataList =
changeStringListToIntList(publicKey!);
var token = await Storage.getStringList(saveBlueToken); final List<String>? token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); final List<int> getTokenList = changeStringListToIntList(token!);
IoSenderManage.senderTransferPermissions( IoSenderManage.senderTransferPermissions(
lockID: BlueManage().connectDeviceName, lockID: BlueManage().connectDeviceName,
authUserID: await Storage.getUid(), authUserID: await Storage.getUid(),
keyID: "1", keyID: '1',
oldUserID: await Storage.getUid(), oldUserID: await Storage.getUid(),
newUserID: "100002", newUserID: '100002',
needAuthor: 1, needAuthor: 1,
publicKey: publicKeyDataList, publicKey: publicKeyDataList,
privateKey: getPrivateKeyList, privateKey: getPrivateKeyList,
@ -102,40 +117,40 @@ class AuthorizedAdminLogic extends BaseGetXController {
// //
Future<void> sendElectronicKeyRequest() async { Future<void> sendElectronicKeyRequest() async {
if (state.emailOrPhoneController.text.isEmpty) { if (state.emailOrPhoneController.text.isEmpty) {
showToast("请输入接收者账号"); showToast('请输入接收者账号');
return; return;
} }
if (state.keyNameController.text.isEmpty) { if (state.keyNameController.text.isEmpty) {
showToast("请输入接收者姓名"); showToast('请输入接收者姓名');
return; return;
} }
var startDate = "0"; String startDate = '0';
var endDate = "0"; String endDate = '0';
var startTime = "0"; String startTime = '0';
var endTime = "0"; String endTime = '0';
AppLog.log("state.type.value:${state.seletType.value}"); AppLog.log('state.type.value:${state.seletType.value}');
String getKeyType = "1"; String getKeyType = '1';
if (state.seletType.value == 0) { if (state.seletType.value == 0) {
getKeyType = "2"; getKeyType = '2';
startDate = startDate =
DateTool().dateToTimestamp(state.beginDate.value, 1).toString(); DateTool().dateToTimestamp(state.beginDate.value, 1).toString();
endDate = DateTool().dateToTimestamp(state.endDate.value, 1).toString(); endDate = DateTool().dateToTimestamp(state.endDate.value, 1).toString();
startTime = "0"; startTime = '0';
endTime = "0"; endTime = '0';
if (startDate.isEmpty) { if (startDate.isEmpty) {
showToast("请选择开始时间"); showToast('请选择开始时间');
return; return;
} }
if (endDate.isEmpty) { if (endDate.isEmpty) {
showToast("请选择结束时间"); showToast('请选择结束时间');
return; return;
} }
if (int.parse(startDate) >= int.parse(endDate)) { if (int.parse(startDate) >= int.parse(endDate)) {
showToast("失效时间要大于生效时间"); showToast('失效时间要大于生效时间');
return; return;
} }
} }
@ -143,12 +158,12 @@ class AuthorizedAdminLogic extends BaseGetXController {
// //
if (state.isAuthentication.value == true) { if (state.isAuthentication.value == true) {
if (state.realNameController.text.isEmpty) { if (state.realNameController.text.isEmpty) {
showToast("请输入真实姓名".tr); showToast('请输入真实姓名'.tr);
return; return;
} }
if (state.idCardController.text.isEmpty) { if (state.idCardController.text.isEmpty) {
showToast("请输入身份证号".tr); showToast('请输入身份证号'.tr);
return; return;
} }
// //
@ -179,38 +194,39 @@ class AuthorizedAdminLogic extends BaseGetXController {
required String startDate, required String startDate,
required String startTime, required String startTime,
required String endTime}) async { required String endTime}) async {
var entity = await ApiRepository.to.sendElectronicKey( final AuthorizedAdminSendEntity entity = await ApiRepository.to
createUser: state.isCreateUser.value ? "1" : "0", .sendElectronicKey(
countryCode: state.countryCode.value, createUser: state.isCreateUser.value ? '1' : '0',
usernameType: '1', countryCode: state.countryCode.value,
endDate: int.parse(endDate), usernameType: '1',
faceAuthentication: state.isAuthentication.value == true ? '1' : '2', endDate: int.parse(endDate),
isCameraEnable: '2', faceAuthentication:
isRemoteUnlock: '2', state.isAuthentication.value == true ? '1' : '2',
keyNameForAdmin: state.keyNameController.text, isCameraEnable: '2',
keyRight: '1', isRemoteUnlock: '2',
keyType: getKeyType, keyNameForAdmin: state.keyNameController.text,
lockId: CommonDataManage().currentKeyInfo.lockId!.toString(), keyRight: '1',
operatorUid: '', keyType: getKeyType,
receiverUsername: state.emailOrPhoneController.text, lockId: CommonDataManage().currentKeyInfo.lockId!.toString(),
remarks: '', operatorUid: '',
startDate: int.parse(startDate), receiverUsername: state.emailOrPhoneController.text,
weekDays: state.weekdaysList, remarks: '',
startTime: int.parse(startTime), startDate: int.parse(startDate),
endTime: int.parse(endTime), weekDays: state.weekdaysList,
isOnlyManageSelf: state.onlyManageYouCreatesUser.value ? 1 : 0, startTime: int.parse(startTime),
realName: state.isRequireAuth.value == true endTime: int.parse(endTime),
? state.realNameController.text isOnlyManageSelf: state.onlyManageYouCreatesUser.value ? 1 : 0,
: "", realName: state.isRequireAuth.value == true
idCardNumber: state.isRequireAuth.value == true ? state.realNameController.text
? state.idCardController.text : '',
: ""); idCardNumber: state.isRequireAuth.value == true
? state.idCardController.text
: '');
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
state.isCreateUser.value = false; state.isCreateUser.value = false;
state.isSendSuccess.value = true; state.isSendSuccess.value = true;
// Toast.show(msg: "添加成功");
state.addUserId.value = entity.data!.receiverUser!.id.toString(); state.addUserId.value = entity.data!.receiverUser!.id.toString();
// addUserConnectBlue(state.addUserId.value); keyId = entity.data!.keyId;
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
} else { } else {
if (entity.errorCode == 425) { if (entity.errorCode == 425) {
@ -218,16 +234,15 @@ class AuthorizedAdminLogic extends BaseGetXController {
state.isCreateUser.value = true; state.isCreateUser.value = true;
ShowTipView().showIosTipWithContentDialog( ShowTipView().showIosTipWithContentDialog(
'${"是否发送授权管理员给未注册账号".tr}\n${state.emailOrPhoneController.text}', '${"是否发送授权管理员给未注册账号".tr}\n${state.emailOrPhoneController.text}',
() { sendElectronicKeyRequest);
sendElectronicKeyRequest();
});
} }
} }
} }
// //
Future<void> keyCheckFace() async { Future<void> keyCheckFace() async {
AdvancedFunctionRecordEntity entity = await ApiRepository.to.keyCheckFace( final AdvancedFunctionRecordEntity entity =
await ApiRepository.to.keyCheckFace(
lockId: CommonDataManage().currentKeyInfo.lockId ?? 0, lockId: CommonDataManage().currentKeyInfo.lockId ?? 0,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
@ -240,7 +255,7 @@ class AuthorizedAdminLogic extends BaseGetXController {
titleStr: '实名认证为付费功能,请购买后再使用'.tr, titleStr: '实名认证为付费功能,请购买后再使用'.tr,
sureClick: () { sureClick: () {
Get.toNamed(Routers.advancedFeaturesWebPage, Get.toNamed(Routers.advancedFeaturesWebPage,
arguments: {'isShop': false}); arguments: <String, bool>{'isShop': false});
}); });
} else if (entity.errorCode == 433) { } else if (entity.errorCode == 433) {
// //
@ -250,12 +265,12 @@ class AuthorizedAdminLogic extends BaseGetXController {
// isOn:: 1 2 // isOn:: 1 2
Future<void> updateRoomCheckIn() async { Future<void> updateRoomCheckIn() async {
var entity = await ApiRepository.to.setRoomStatusData( final LoginEntity entity = await ApiRepository.to.setRoomStatusData(
lockId: CommonDataManage().currentKeyInfo.lockId!, lockId: CommonDataManage().currentKeyInfo.lockId!,
roomStatus: 1, roomStatus: 1,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
showToast("标记成功"); showToast('标记成功');
} }
} }
@ -279,6 +294,31 @@ class AuthorizedAdminLogic extends BaseGetXController {
return currentController; return currentController;
} }
//
Future<void> sendMsg({required bool isPhone}) async {
if (keyId == null) {
return;
}
final NoticeTemplateEntity entity = await ApiRepository.to
.getNoticeTemplate(
lockId: CommonDataManage().currentKeyInfo.lockId!,
keyId: keyId!,
channelType: isPhone ? 1 : 2);
if (entity.errorCode!.codeIsSuccessful) {
final List<Item?> list =
entity.data!.list!.where((Item item) => item.isUse == 0).toList();
if (list.isNotEmpty) {
final Item item = list.first!;
final String template = item.template ?? '';
NativeInteractionTool().loadNativeShare(shareText: template);
} else {
showToast('获取模板失败 0x02');
}
} else {
showToast('获取模板失败 0x01');
}
}
@override @override
void onReady() { void onReady() {
// TODO: implement onReady // TODO: implement onReady

View File

@ -4,6 +4,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_native_contact_picker/flutter_native_contact_picker.dart'; import 'package:flutter_native_contact_picker/flutter_native_contact_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/authorizedAdmin/authorizedAdmin/authorizedAdmin_state.dart';
import 'package:star_lock/tools/dateTool.dart'; import 'package:star_lock/tools/dateTool.dart';
import 'package:star_lock/tools/pickers/pickers.dart'; import 'package:star_lock/tools/pickers/pickers.dart';
@ -31,8 +32,8 @@ class AuthorizedAdminPage extends StatefulWidget {
class _AuthorizedAdminPageState extends State<AuthorizedAdminPage> class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
with SingleTickerProviderStateMixin { with SingleTickerProviderStateMixin {
final logic = Get.put(AuthorizedAdminLogic()); final AuthorizedAdminLogic logic = Get.put(AuthorizedAdminLogic());
final state = Get.find<AuthorizedAdminLogic>().state; final AuthorizedAdminState state = Get.find<AuthorizedAdminLogic>().state;
@override @override
void initState() { void initState() {
@ -60,7 +61,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor), backgroundColor: AppColors.mainColor),
body: Column( body: Column(
children: [ children: <Widget>[
_tabBar(), _tabBar(),
_pageWidget(), _pageWidget(),
], ],
@ -78,7 +79,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
// //
return SingleChildScrollView( return SingleChildScrollView(
child: Column( child: Column(
children: [ children: <Widget>[
keyInfoWidget(), keyInfoWidget(),
keyTimeWidget(), keyTimeWidget(),
keyOnlyManageWidget(), keyOnlyManageWidget(),
@ -92,7 +93,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
// //
return SingleChildScrollView( return SingleChildScrollView(
child: Column( child: Column(
children: [ children: <Widget>[
keyInfoWidget(), keyInfoWidget(),
keyOnlyManageWidget(), keyOnlyManageWidget(),
keyBottomWidget( keyBottomWidget(
@ -107,17 +108,17 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
// widget // widget
Widget keyInfoWidget() { Widget keyInfoWidget() {
return Column( return Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.receiver!.tr, leftTitel: TranslationLoader.lanKeys!.receiver!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: getTFWidget(true, rightWidget: getTFWidget(true,
TranslationLoader.lanKeys!.pleaseEnterNumberOrEmail!.tr, 1)), TranslationLoader.lanKeys!.pleaseEnterNumberOrEmail!.tr, 1)),
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.countryAndRegion!.tr, leftTitel: TranslationLoader.lanKeys!.countryAndRegion!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
isHaveDirection: true, isHaveDirection: true,
@ -128,7 +129,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
TextStyle(fontSize: 22.sp, color: AppColors.darkGrayTextColor), TextStyle(fontSize: 22.sp, color: AppColors.darkGrayTextColor),
), ),
action: () async { action: () async {
var result = await Navigator.pushNamed( final Object? result = await Navigator.pushNamed(
context, Routers.selectCountryRegionPage); context, Routers.selectCountryRegionPage);
if (result != null) { if (result != null) {
result as Map<String, dynamic>; result as Map<String, dynamic>;
@ -140,7 +141,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
), ),
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.name!.tr, leftTitel: TranslationLoader.lanKeys!.name!.tr,
rightTitle: "", rightTitle: '',
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: getTFWidget( rightWidget: getTFWidget(
false, TranslationLoader.lanKeys!.enterYourName!.tr, 2)), false, TranslationLoader.lanKeys!.enterYourName!.tr, 2)),
@ -152,17 +153,18 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
// //
Widget keyTimeWidget() { Widget keyTimeWidget() {
return Column( return Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.effectiveTime!.tr, leftTitel: TranslationLoader.lanKeys!.effectiveTime!.tr,
rightTitle: state.beginDate.value, rightTitle: state.beginDate.value,
isHaveLine: true, isHaveLine: true,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
PDuration selectDate = final PDuration selectDate =
PDuration.parse(DateTime.tryParse(state.beginDate.value)); PDuration.parse(DateTime.tryParse(state.beginDate.value));
Pickers.showDatePicker(context, Pickers.showDatePicker(context,
selectDate: selectDate, mode: DateMode.YMDHM, onConfirm: (p) { selectDate: selectDate,
mode: DateMode.YMDHM, onConfirm: (PDuration p) {
setState(() { setState(() {
state.beginDate.value = DateTool().getYMDHNDateString(p, 1); state.beginDate.value = DateTool().getYMDHNDateString(p, 1);
}); });
@ -173,10 +175,11 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
rightTitle: state.endDate.value, rightTitle: state.endDate.value,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
PDuration selectDate = final PDuration selectDate =
PDuration.parse(DateTime.tryParse(state.endDate.value)); PDuration.parse(DateTime.tryParse(state.endDate.value));
Pickers.showDatePicker(context, Pickers.showDatePicker(context,
selectDate: selectDate, mode: DateMode.YMDHM, onConfirm: (p) { selectDate: selectDate,
mode: DateMode.YMDHM, onConfirm: (PDuration p) {
setState(() { setState(() {
state.endDate.value = DateTool().getYMDHNDateString(p, 1); state.endDate.value = DateTool().getYMDHNDateString(p, 1);
}); });
@ -190,14 +193,14 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
// //
Widget keyOnlyManageWidget() { Widget keyOnlyManageWidget() {
return Column( return Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: "仅管理自己创建的用户", leftTitel: '仅管理自己创建的用户',
rightTitle: "", rightTitle: '',
isHaveRightWidget: true, isHaveRightWidget: true,
isTipsImg: true, isTipsImg: true,
tipsImgAction: () { tipsImgAction: () {
ShowTipView().showSureAlertDialog("授权管理员只能查看和管理自己下发的钥匙、密码等权限"); ShowTipView().showSureAlertDialog('授权管理员只能查看和管理自己下发的钥匙、密码等权限');
}, },
rightWidget: SizedBox( rightWidget: SizedBox(
width: 60.w, width: 60.w,
@ -212,11 +215,11 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
Widget keyBottomWidget(String tipStr) { Widget keyBottomWidget(String tipStr) {
return Column( return Column(
children: [ children: <Widget>[
Container( Container(
padding: EdgeInsets.all(20.w), padding: EdgeInsets.all(20.w),
child: Row( child: Row(
children: [ children: <Widget>[
Expanded( Expanded(
child: Text( child: Text(
tipStr, tipStr,
@ -233,26 +236,27 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
SubmitBtn( SubmitBtn(
btnName: TranslationLoader.lanKeys!.send!.tr, btnName: TranslationLoader.lanKeys!.send!.tr,
onClick: () async { onClick: () async {
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode = await Storage.getBool(ifIsDemoModeOrNot);
if (isDemoMode == false) { if (isDemoMode == false) {
// //
logic.sendElectronicKeyRequest(); logic.sendElectronicKeyRequest();
} else { } else {
logic.showToast("演示模式"); logic.showToast('演示模式');
} }
}), }),
Container( Container(
padding: EdgeInsets.only(right: 30.w), padding: EdgeInsets.only(right: 30.w),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: <Widget>[
TextButton( TextButton(
onPressed: () async { onPressed: () async {
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode =
await Storage.getBool(ifIsDemoModeOrNot);
if (isDemoMode == false) { if (isDemoMode == false) {
Get.toNamed(Routers.volumeAuthorizationLockManagePage); Get.toNamed(Routers.volumeAuthorizationLockManagePage);
} else { } else {
logic.showToast("演示模式"); logic.showToast('演示模式');
} }
}, },
child: Text( child: Text(
@ -270,16 +274,15 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
// //
Widget keyRealNameWidget() { Widget keyRealNameWidget() {
return Column( return Column(
children: [ children: <Widget>[
Obx(() => CommonItem( Obx(() => CommonItem(
leftTitel: TranslationLoader.lanKeys!.realNameAuthentication!.tr, leftTitel: TranslationLoader.lanKeys!.realNameAuthentication!.tr,
rightTitle: "", rightTitle: '',
isTipsImg: true, isTipsImg: true,
isHaveLine: isHaveLine: logic.state.isRequireAuth.value == true,
logic.state.isRequireAuth.value == true ? true : false,
tipsImgAction: () { tipsImgAction: () {
ShowTipView().showSureAlertDialog( ShowTipView().showSureAlertDialog(
"人脸实名认证指的是用户在使用手机APP开锁时需要先进行本人人脸验证验证通过才能开锁。".tr); '人脸实名认证指的是用户在使用手机APP开锁时需要先进行本人人脸验证验证通过才能开锁。'.tr);
}, },
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: SizedBox( rightWidget: SizedBox(
@ -289,7 +292,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
visible: logic.state.isRequireAuth.value, visible: logic.state.isRequireAuth.value,
child: CommonItem( child: CommonItem(
leftTitel: '真实姓名'.tr, leftTitel: '真实姓名'.tr,
rightTitle: "", rightTitle: '',
isHaveRightWidget: true, isHaveRightWidget: true,
isHaveLine: true, isHaveLine: true,
rightWidget: getTFWidget(false, '请输入真实姓名'.tr, 3)))), rightWidget: getTFWidget(false, '请输入真实姓名'.tr, 3)))),
@ -297,7 +300,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
visible: logic.state.isRequireAuth.value, visible: logic.state.isRequireAuth.value,
child: CommonItem( child: CommonItem(
leftTitel: '身份证号'.tr, leftTitel: '身份证号'.tr,
rightTitle: "", rightTitle: '',
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: getTFWidget(false, '请输入身份证号'.tr, 4)))), rightWidget: getTFWidget(false, '请输入身份证号'.tr, 4)))),
], ],
@ -307,13 +310,13 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
// //
Widget sendElectronicKeySucceed() { Widget sendElectronicKeySucceed() {
return Column( return Column(
children: [ children: <Widget>[
Container( Container(
height: 250.h, height: 250.h,
width: 1.sw, width: 1.sw,
color: Colors.white, color: Colors.white,
child: Column( child: Column(
children: [ children: <Widget>[
SizedBox( SizedBox(
height: 30.h, height: 30.h,
), ),
@ -327,9 +330,9 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Text( Text(
"发送成功", '发送成功',
style: TextStyle( style: TextStyle(
fontSize: 26.sp, fontSize: 26.sp,
color: Colors.black, color: Colors.black,
@ -354,13 +357,12 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
), ),
OutLineBtn( OutLineBtn(
btnName: btnName:
state.emailOrPhoneController.text.contains("@") ? '邮件通知' : "短信通知", state.emailOrPhoneController.text.contains('@') ? '邮件通知' : '短信通知',
onClick: () { onClick: () {
if (state.emailOrPhoneController.text.contains("@")) { if (state.emailOrPhoneController.text.contains('@')) {
Get.toNamed(Routers.sendEmailNotificationPage); Get.toNamed(Routers.sendEmailNotificationPage);
} else { } else {
NativeInteractionTool() logic.sendMsg(isPhone: true);
.loadNativeShare(shareText: state.pwdShareStr);
} }
}, },
), ),
@ -370,8 +372,8 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
OutLineBtn( OutLineBtn(
btnName: '微信通知', btnName: '微信通知',
onClick: () { onClick: () {
NativeInteractionTool() logic.sendMsg(
.loadNativeShare(shareText: state.pwdShareStr); isPhone: state.emailOrPhoneController.text.contains('@'));
}, },
), ),
SizedBox( SizedBox(
@ -387,7 +389,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
height: 65.h, height: 65.h,
width: 300.w, width: 300.w,
child: Row( child: Row(
children: [ children: <Widget>[
Expanded( Expanded(
child: TextField( child: TextField(
// //
@ -425,38 +427,37 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
SizedBox( SizedBox(
width: 10.w, width: 10.w,
), ),
isHaveBtn if (isHaveBtn)
? Container( Container(
width: 30.w, width: 30.w,
height: 30.w, height: 30.w,
decoration: const BoxDecoration( decoration: const BoxDecoration(
color: Colors.white, color: Colors.white,
image: DecorationImage( image: DecorationImage(
image: AssetImage('images/icon_addressBook.png'), image: AssetImage('images/icon_addressBook.png'),
fit: BoxFit.fill), fit: BoxFit.fill),
), ),
alignment: Alignment.center, alignment: Alignment.center,
child: InkWell( child: InkWell(
onTap: () async { onTap: () async {
Contact? currentContact = final Contact? currentContact =
await state.contactPicker.selectContact(); await state.contactPicker.selectContact();
setState(() { setState(() {
state.contact = currentContact!; state.contact = currentContact!;
if (currentContact.phoneNumbers!.isNotEmpty) { if (currentContact.phoneNumbers!.isNotEmpty) {
state.emailOrPhoneController.text = currentContact state.emailOrPhoneController.text = currentContact
.phoneNumbers![0] .phoneNumbers![0]
.replaceAll(RegExp(r"\s+\b|\b\s"), ""); .replaceAll(RegExp(r'\s+\b|\b\s'), '');
} }
if (currentContact.fullName!.isNotEmpty) {
if (currentContact.fullName!.isNotEmpty) { state.keyNameController.text = currentContact.fullName!;
state.keyNameController.text = }
currentContact.fullName!; });
} },
}); ),
}, )
), else
) Container()
: Container()
], ],
), ),
); );
@ -469,7 +470,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
trackColor: CupertinoColors.systemGrey5, trackColor: CupertinoColors.systemGrey5,
thumbColor: CupertinoColors.white, thumbColor: CupertinoColors.white,
value: state.isAuthentication.value, value: state.isAuthentication.value,
onChanged: (value) { onChanged: (bool value) {
setState(() { setState(() {
if (logic.state.isAuthentication.value == false) { if (logic.state.isAuthentication.value == false) {
logic.keyCheckFace(); logic.keyCheckFace();
@ -489,7 +490,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
trackColor: CupertinoColors.systemGrey5, trackColor: CupertinoColors.systemGrey5,
thumbColor: CupertinoColors.white, thumbColor: CupertinoColors.white,
value: state.onlyManageYouCreatesUser.value, value: state.onlyManageYouCreatesUser.value,
onChanged: (value) { onChanged: (bool value) {
setState(() { setState(() {
state.onlyManageYouCreatesUser.value = state.onlyManageYouCreatesUser.value =
!state.onlyManageYouCreatesUser.value; !state.onlyManageYouCreatesUser.value;
@ -498,7 +499,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
); );
} }
Future _openModalBottomSheet() async { void _openModalBottomSheet() {
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
@ -506,7 +507,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
constraints: BoxConstraints(maxHeight: 270.h), constraints: BoxConstraints(maxHeight: 270.h),
builder: (BuildContext context) { builder: (BuildContext context) {
return Column( return Column(
children: [ children: <Widget>[
SizedBox( SizedBox(
width: ScreenUtil().screenWidth, width: ScreenUtil().screenWidth,
height: 180.h, height: 180.h,
@ -537,7 +538,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
} }
List<Widget> initBottomSheetList() { List<Widget> initBottomSheetList() {
List<Widget> widgetList = []; final List<Widget> widgetList = <Widget>[];
widgetList.add(buildCenter3('images/icon_wechat.png', '微信好友', 0)); widgetList.add(buildCenter3('images/icon_wechat.png', '微信好友', 0));
widgetList.add(buildCenter3('images/icon_message.png', '短信', 1)); widgetList.add(buildCenter3('images/icon_message.png', '短信', 1));
@ -557,7 +558,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
EdgeInsets.only(top: 20.w, bottom: 20.w, left: 10.w, right: 10.w), EdgeInsets.only(top: 20.w, bottom: 20.w, left: 10.w, right: 10.w),
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Image.asset( Image.asset(
imageName, imageName,
width: 50.w, width: 50.w,
@ -579,7 +580,7 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
} }
//\n生效时间${itemData.startDate}\n类型\n锁名${itemData.keyboardPwdName} //\n生效时间${itemData.startDate}\n类型\n锁名${itemData.keyboardPwdName}
_jumpSmartDeviceRoute(int itemIndex) { dynamic _jumpSmartDeviceRoute(int itemIndex) {
Get.back(); Get.back();
switch (itemIndex) { switch (itemIndex) {
case 0: case 0:
@ -613,8 +614,8 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
TabBar _tabBar() { TabBar _tabBar() {
return TabBar( return TabBar(
controller: state.tabController, controller: state.tabController,
tabs: _itemTabs.map((ItemView item) => _tab(item)).toList(), tabs: _itemTabs.map(_tab).toList(),
onTap: (index) { onTap: (int index) {
FocusScope.of(context).requestFocus(FocusNode()); FocusScope.of(context).requestFocus(FocusNode());
}, },
isScrollable: true, isScrollable: true,
@ -655,14 +656,14 @@ class _AuthorizedAdminPageState extends State<AuthorizedAdminPage>
child: TabBarView( child: TabBarView(
controller: state.tabController, controller: state.tabController,
children: _itemTabs children: _itemTabs
.map((ItemView item) => Obx(() => indexChangeWidget())) .map((ItemView item) => Obx(indexChangeWidget))
.toList()), .toList()),
); );
} }
final List<ItemView> _itemTabs = <ItemView>[ final List<ItemView> _itemTabs = <ItemView>[
ItemView(title: TranslationLoader.lanKeys!.timeLimit!.tr, type: "0"), ItemView(title: TranslationLoader.lanKeys!.timeLimit!.tr, type: '0'),
ItemView(title: TranslationLoader.lanKeys!.permanent!.tr, type: "1"), ItemView(title: TranslationLoader.lanKeys!.permanent!.tr, type: '1'),
]; ];
} }

View File

@ -15,25 +15,25 @@ class AuthorizedAdminState {
final FlutterContactPicker contactPicker = FlutterContactPicker(); final FlutterContactPicker contactPicker = FlutterContactPicker();
late Contact contact; late Contact contact;
var isAuthentication = false.obs; // RxBool isAuthentication = false.obs; //
final onlyManageYouCreatesUser = false.obs; // final RxBool onlyManageYouCreatesUser = false.obs; //
var beginDate = DateTool() RxString beginDate = DateTool()
.dateToYMDHNString(DateTime.now().millisecondsSinceEpoch.toString()) .dateToYMDHNString(DateTime.now().millisecondsSinceEpoch.toString())
.obs; // .obs; //
var endDate = DateTool() RxString endDate = DateTool()
.dateToYMDHNString(DateTime.now().millisecondsSinceEpoch.toString()) .dateToYMDHNString(DateTime.now().millisecondsSinceEpoch.toString())
.obs; // .obs; //
var isSendSuccess = false.obs; RxBool isSendSuccess = false.obs;
var countryName = '中国'.obs; RxString countryName = '中国'.obs;
var countryCode = '86'.obs; RxString countryCode = '86'.obs;
var weekdaysList = [].obs; RxList weekdaysList = [].obs;
var isCreateUser = false.obs; //1 0 RxBool isCreateUser = false.obs; //1 0
var seletType = 0.obs; RxInt seletType = 0.obs;
String pwdShareStr = '您好,您的授权管理员生成成功'; String pwdShareStr = '您好,您的授权管理员生成成功';
var addUserId = ''.obs; RxString addUserId = ''.obs;
var isRequireAuth = false.obs; // RxBool isRequireAuth = false.obs; //
} }

View File

@ -0,0 +1,71 @@
class NoticeTemplateEntity {
NoticeTemplateEntity(
{this.errorCode, this.description, this.errorMsg, this.data});
NoticeTemplateEntity.fromJson(Map<String, dynamic> json) {
errorCode = json['errorCode'];
description = json['description'];
errorMsg = json['errorMsg'];
if (json['data'] is Map) {
data = Data.fromJson(json['data']);
}
}
int? errorCode;
String? description;
String? errorMsg;
Data? data;
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['errorCode'] = errorCode;
data['description'] = description;
data['errorMsg'] = errorMsg;
data['data'] = this.data;
return data;
}
}
class Data {
Data.fromJson(Map<String, dynamic> json) {
if (json['list'] is List) {
json['list'].forEach((dynamic element) {
list?.add(Item.fromJson(element));
});
}
}
List<Item>? list = [];
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['list'] = list;
return data;
}
}
class Item {
Item.fromJson(Map<String, dynamic> json) {
type = json['type'];
name = json['name'];
template = json['template'];
isUse = json['isUse'];
fee = json['fee'];
}
String? type;
String? name;
String? template;
int? isUse;
int? fee;
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['type'] = type;
data['name'] = name;
data['template'] = template;
data['isUse'] = isUse;
data['fee'] = fee;
return data;
}
}

View File

@ -4,6 +4,7 @@ import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/common/XSConstantMacro/XSConstantMacro.dart'; import 'package:star_lock/common/XSConstantMacro/XSConstantMacro.dart';
import 'package:star_lock/main/lockDetail/authorizedAdmin/authorizedAdminList/authorizedAdminList_logic.dart'; import 'package:star_lock/main/lockDetail/authorizedAdmin/authorizedAdminList/authorizedAdminList_logic.dart';
import 'package:star_lock/main/lockDetail/authorizedAdmin/authorizedAdminList/authorizedAdminList_state.dart';
import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/entity/ElectronicKeyListEntity.dart'; import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/entity/ElectronicKeyListEntity.dart';
import 'package:star_lock/tools/noData.dart'; import 'package:star_lock/tools/noData.dart';
import 'package:star_lock/tools/storage.dart'; import 'package:star_lock/tools/storage.dart';
@ -25,8 +26,8 @@ class AuthorizedAdminListPage extends StatefulWidget {
} }
class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> { class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
final logic = Get.put(AuthorizedAdminListLogic()); final AuthorizedAdminListLogic logic = Get.put(AuthorizedAdminListLogic());
final state = Get.find<AuthorizedAdminListLogic>().state; final AuthorizedAdminListState state = Get.find<AuthorizedAdminListLogic>().state;
@override @override
void initState() { void initState() {
@ -37,7 +38,7 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
Future<void> mockRequest() async { Future<void> mockRequest() async {
// //
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode = await Storage.getBool(ifIsDemoModeOrNot);
if (isDemoMode == false) { if (isDemoMode == false) {
logic.mockNetworkDataRequest().then((ElectronicKeyListEntity value) { logic.mockNetworkDataRequest().then((ElectronicKeyListEntity value) {
setState(() {}); setState(() {});
@ -63,7 +64,7 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
mockRequest(); mockRequest();
}, },
child: Column( child: Column(
children: [ children: <Widget>[
Expanded(child: _buildMainUI()), Expanded(child: _buildMainUI()),
SizedBox( SizedBox(
height: 20.h, height: 20.h,
@ -72,7 +73,7 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
btnName: TranslationLoader.lanKeys!.addAuthorizedAdmin!.tr, btnName: TranslationLoader.lanKeys!.addAuthorizedAdmin!.tr,
onClick: () { onClick: () {
Navigator.pushNamed(context, Routers.authorizedAdminPage) Navigator.pushNamed(context, Routers.authorizedAdminPage)
.then((val) { .then((Object? val) {
if (val != null) { if (val != null) {
logic.pageNo = 1; logic.pageNo = 1;
mockRequest(); mockRequest();
@ -89,14 +90,14 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
} }
Widget _buildMainUI() { Widget _buildMainUI() {
return Obx(() => state.itemDataList.value.isEmpty return Obx(() => state.itemDataList.isEmpty
? NoData(noDataHeight: 1.sh - ScreenUtil().statusBarHeight - 90) ? NoData(noDataHeight: 1.sh - ScreenUtil().statusBarHeight - 90)
: SlidableAutoCloseBehavior( : SlidableAutoCloseBehavior(
child: ListView.separated( child: ListView.separated(
itemCount: state.itemDataList.value.length, itemCount: state.itemDataList.length,
itemBuilder: (c, index) { itemBuilder: (BuildContext c, int index) {
ElectronicKeyListItem indexEntity = final ElectronicKeyListItem indexEntity =
state.itemDataList.value[index]; state.itemDataList[index];
String useDateStr = ''; //使 String useDateStr = ''; //使
String keyStatus = ''; // String keyStatus = ''; //
@ -116,16 +117,16 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
} }
return Slidable( return Slidable(
key: ValueKey(indexEntity.keyId), key: ValueKey<int?>(indexEntity.keyId),
endActionPane: ActionPane( endActionPane: ActionPane(
extentRatio: 0.2, extentRatio: 0.2,
motion: const ScrollMotion(), motion: const ScrollMotion(),
children: [ children: <Widget>[
SlidableAction( SlidableAction(
onPressed: (BuildContext context) { onPressed: (BuildContext context) {
ShowTipView() ShowTipView()
.showDeleteAdministratorIsHaveAllDataDialog( .showDeleteAdministratorIsHaveAllDataDialog(
'同时删除其发送的所有钥匙,钥匙删除后不能恢复', (isAllData) { '同时删除其发送的所有钥匙,钥匙删除后不能恢复', (bool isAllData) {
logic.deleteKeyRequest(indexEntity.keyId.toString(), logic.deleteKeyRequest(indexEntity.keyId.toString(),
isAllData ? 1 : 0); isAllData ? 1 : 0);
}); });
@ -145,9 +146,9 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
isAdminKey, () { isAdminKey, () {
Navigator.pushNamed( Navigator.pushNamed(
context, Routers.electronicKeyDetailPage, context, Routers.electronicKeyDetailPage,
arguments: { arguments: <String, ElectronicKeyListItem>{
"itemData": indexEntity, 'itemData': indexEntity,
}).then((val) { }).then((Object? val) {
if (val != null) { if (val != null) {
logic.mockNetworkDataRequest(); logic.mockNetworkDataRequest();
setState(() {}); setState(() {});
@ -172,14 +173,14 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
if (indexEntity.keyType == XSConstantMacro.keyTypeTime) { if (indexEntity.keyType == XSConstantMacro.keyTypeTime) {
// //
DateTime startDateStr = final DateTime startDateStr =
DateTime.fromMillisecondsSinceEpoch(indexEntity.startDate!); DateTime.fromMillisecondsSinceEpoch(indexEntity.startDate!);
DateTime endDateStr = final DateTime endDateStr =
DateTime.fromMillisecondsSinceEpoch(indexEntity.endDate!); DateTime.fromMillisecondsSinceEpoch(indexEntity.endDate!);
useDateStr = useDateStr =
'${startDateStr.toLocal().toString().substring(0, 16)}-${endDateStr.toLocal().toString().substring(0, 16)}'; '${startDateStr.toLocal().toString().substring(0, 16)}-${endDateStr.toLocal().toString().substring(0, 16)}';
} else if (indexEntity.keyType == XSConstantMacro.keyTypeLong) { } else if (indexEntity.keyType == XSConstantMacro.keyTypeLong) {
useDateStr = "永久"; useDateStr = '永久';
} }
return useDateStr; return useDateStr;
} }
@ -192,7 +193,7 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
color: Colors.white, color: Colors.white,
height: 100.h, height: 100.h,
child: Row( child: Row(
children: [ children: <Widget>[
SizedBox(width: 30.w), SizedBox(width: 30.w),
Image.asset( Image.asset(
avatarURL, avatarURL,
@ -203,13 +204,13 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
Expanded( Expanded(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Row( Row(
children: [ children: <Widget>[
SizedBox( SizedBox(
width: 1.sw - 110.w - 100.w, width: 1.sw - 110.w - 100.w,
child: Row( child: Row(
children: [ children: <Widget>[
Flexible( Flexible(
child: Text(receiveUser, child: Text(receiveUser,
maxLines: 1, maxLines: 1,
@ -231,7 +232,7 @@ class _AuthorizedAdminListPageState extends State<AuthorizedAdminListPage> {
SizedBox(height: 10.h), SizedBox(height: 10.h),
Row( Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: <Widget>[
Text( Text(
useDate, useDate,
style: TextStyle( style: TextStyle(

View File

@ -1,10 +1,56 @@
import 'dart:ffi';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/authorizedAdmin/authorizedAdmin/notice_template_entity.dart';
import 'package:star_lock/main/lockDetail/lockSet/basicInformation/basicInformation/KeyDetailEntity.dart';
import 'package:star_lock/network/api_repository.dart';
import 'package:star_lock/tools/baseGetXController.dart'; import 'package:star_lock/tools/baseGetXController.dart';
import 'package:star_lock/tools/commonDataManage.dart';
import 'volumeAuthorizationLock_state.dart'; import 'volumeAuthorizationLock_state.dart';
class VolumeAuthorizationLockLogic extends BaseGetXController { class VolumeAuthorizationLockLogic extends BaseGetXController {
final state = VolumeAuthorizationLockState(); final VolumeAuthorizationLockState state = VolumeAuthorizationLockState();
} //
Future<void> addAuthorizedAdminRequest() async {
String getFailureDateTime = '0';
String getEffectiveDateTime = '0';
if (state.selectWidgetType.value == '1') {
getFailureDateTime =
state.failureDateTime.value.millisecondsSinceEpoch.toString();
getEffectiveDateTime =
state.effectiveDateTime.value.millisecondsSinceEpoch.toString();
}
if (state.lockIdList.isEmpty) {
showToast('请选择锁'.tr);
return;
}
final KeyDetailEntity entity = await ApiRepository.to.addAuthorizedAdmin(
createUser: state.isCreateUser.value ? '1' : '0',
endDate: getFailureDateTime,
isRemoteUnlock: '0',
keyGroupIdList: <dynamic>[],
lockIdList: state.lockIdList.value,
name: state.keyNameController.text,
startDate: getEffectiveDateTime,
userid: state.emailOrPhoneController.text,
countryCode: state.countryCode.value,
usernameType: '1',
isOnlyManageSelf: state.onlyManageYouCreatesUser.value == true ? 1 : 2,
);
if (entity.errorCode!.codeIsSuccessful) {
state.isSendSuccess.value = true;
} else {
EasyLoading.showToast('${entity.errorMsg}', duration: 2000.milliseconds);
if (entity.errorCode == 425) {
//
state.isCreateUser.value = true;
addAuthorizedAdminRequest();
}
}
}
}

View File

@ -1,19 +1,16 @@
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_contact_picker/flutter_native_contact_picker.dart'; import 'package:flutter_native_contact_picker/flutter_native_contact_picker.dart';
// import 'package:flutter_pickers/pickers.dart';
// import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/app_settings/app_colors.dart'; import 'package:star_lock/app_settings/app_colors.dart';
import 'package:star_lock/network/api_repository.dart'; import 'package:star_lock/main/lockDetail/authorizedAdmin/volumeAuthorizationLock/volumeAuthorizationLock_state.dart';
import 'package:star_lock/tools/baseGetXController.dart';
import 'package:star_lock/tools/pickers/pickers.dart'; import 'package:star_lock/tools/pickers/pickers.dart';
import 'package:star_lock/tools/pickers/time_picker/model/date_mode.dart'; import 'package:star_lock/tools/pickers/time_picker/model/date_mode.dart';
import 'package:star_lock/tools/pickers/time_picker/model/pduration.dart'; import 'package:star_lock/tools/pickers/time_picker/model/pduration.dart';
import 'package:star_lock/tools/showTipView.dart';
import '../../../../appRouters.dart'; import '../../../../appRouters.dart';
import '../../../../tools/commonItem.dart'; import '../../../../tools/commonItem.dart';
@ -22,10 +19,9 @@ import '../../../../translations/trans_lib.dart';
import 'volumeAuthorizationLock_logic.dart'; import 'volumeAuthorizationLock_logic.dart';
class VolumeAuthorizationLockPage extends StatefulWidget { class VolumeAuthorizationLockPage extends StatefulWidget {
final String type; const VolumeAuthorizationLockPage({required this.type, Key? key})
const VolumeAuthorizationLockPage({Key? key, required this.type})
: super(key: key); : super(key: key);
final String type;
@override @override
State<VolumeAuthorizationLockPage> createState() => State<VolumeAuthorizationLockPage> createState() =>
@ -33,53 +29,23 @@ class VolumeAuthorizationLockPage extends StatefulWidget {
} }
// //
class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPage> { class _VolumeAuthorizationLockPageState
final logic = Get.put(VolumeAuthorizationLockLogic()); extends State<VolumeAuthorizationLockPage> {
final state = Get.find<VolumeAuthorizationLockLogic>().state; final VolumeAuthorizationLockLogic logic =
Get.put(VolumeAuthorizationLockLogic());
final FlutterContactPicker _contactPicker = FlutterContactPicker(); final VolumeAuthorizationLockState state =
final TextEditingController _emailOrPhoneController = Get.find<VolumeAuthorizationLockLogic>().state;
TextEditingController(); ///
final TextEditingController _keyNameController =
TextEditingController(); //
late Contact _contact;
late List _lockIdList;
late bool _isSendSuccess;
late bool _isCreateUser; //
late bool _isRemoteUnlock; //
var _selectEffectiveDate = ''; //
var _selectFailureDate = ''; //
late DateTime _effectiveDateTime;
late DateTime _failureDateTime;
String countryName = '中国';
String countryCode = '86';
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
state.selectWidgetType.value = widget.type;
return SingleChildScrollView( return SingleChildScrollView(
child: indexChangeWidget(), child: Obx(indexChangeWidget),
); );
} }
@override
void initState() {
super.initState();
_lockIdList = [];
_isRemoteUnlock = false;
_isSendSuccess = false;
_isCreateUser = false;
DateTime dateTime = DateTime.now();
_effectiveDateTime = dateTime;
_failureDateTime = dateTime;
_selectEffectiveDate =
'${dateTime.year}-${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}'; //
_selectFailureDate =
'${dateTime.year}-${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}'; //
}
Widget indexChangeWidget() { Widget indexChangeWidget() {
if (_isSendSuccess) { if (state.isSendSuccess.value) {
return sendElectronicKeySucceed(); return sendElectronicKeySucceed();
} else { } else {
switch (int.parse(widget.type)) { switch (int.parse(widget.type)) {
@ -87,7 +53,7 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
{ {
// //
return Column( return Column(
children: [ children: <Widget>[
keyInfoWidget(), keyInfoWidget(),
remoteUnlockingWidget(), remoteUnlockingWidget(),
SizedBox( SizedBox(
@ -100,7 +66,7 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
default: default:
// //
return Column( return Column(
children: [ children: <Widget>[
keyInfoWidget(), keyInfoWidget(),
keyTimeWidget(), keyTimeWidget(),
remoteUnlockingWidget(), remoteUnlockingWidget(),
@ -117,47 +83,47 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
// widget // widget
Widget keyInfoWidget() { Widget keyInfoWidget() {
return Column( return Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.accountNumber!.tr, leftTitel: TranslationLoader.lanKeys!.accountNumber!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: getTFWidget( rightWidget: getTFWidget(
true, true,
TranslationLoader.lanKeys!.pleaseEnterNumberOrEmail!.tr, TranslationLoader.lanKeys!.pleaseEnterNumberOrEmail!.tr,
_emailOrPhoneController)), state.emailOrPhoneController)),
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.countryAndRegion!.tr, leftTitel: TranslationLoader.lanKeys!.countryAndRegion!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
isHaveDirection: true, isHaveDirection: true,
rightWidget: Text( rightWidget: Text(
'$countryName +$countryCode', '${state.countryName.value} +${state.countryCode.value}',
textAlign: TextAlign.end, textAlign: TextAlign.end,
style: style:
TextStyle(fontSize: 22.sp, color: AppColors.darkGrayTextColor), TextStyle(fontSize: 22.sp, color: AppColors.darkGrayTextColor),
), ),
action: () async { action: () async {
var result = await Navigator.pushNamed( final Object? result = await Navigator.pushNamed(
context, Routers.selectCountryRegionPage); context, Routers.selectCountryRegionPage);
if (result != null) { if (result != null) {
result as Map<String, dynamic>; result as Map<String, dynamic>;
countryCode = result['code']; state.countryCode.value = result['code'];
countryName = result['countryName']; state.countryName.value = result['countryName'];
setState(() {}); // setState(() {});
} }
}, },
), ),
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.name!.tr, leftTitel: TranslationLoader.lanKeys!.name!.tr,
rightTitle: "", rightTitle: '',
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: getTFWidget( rightWidget: getTFWidget(
false, false,
TranslationLoader.lanKeys!.pleaseEnter!.tr, TranslationLoader.lanKeys!.pleaseEnter!.tr,
_keyNameController)), state.keyNameController)),
Container(height: 10.h), Container(height: 10.h),
], ],
); );
@ -166,36 +132,42 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
// //
Widget keyTimeWidget() { Widget keyTimeWidget() {
return Column( return Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.effectiveTime!.tr, leftTitel: TranslationLoader.lanKeys!.effectiveTime!.tr,
rightTitle: _selectEffectiveDate, rightTitle: state.selectEffectiveDate.value,
isHaveLine: true, isHaveLine: true,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
PDuration selectDate = PDuration.parse(_effectiveDateTime); final PDuration selectDate =
PDuration.parse(state.effectiveDateTime.value);
Pickers.showDatePicker(context, Pickers.showDatePicker(context,
selectDate: selectDate, mode: DateMode.YMDHM, onConfirm: (p) { selectDate: selectDate,
setState(() { mode: DateMode.YMDHM, onConfirm: (PDuration p) {
_selectEffectiveDate = // setState(() {
'${p.year}-${intToStr(p.month!)}-${intToStr(p.day!)} ${intToStr(p.hour!)}:${intToStr(p.minute!)}'; state.selectEffectiveDate.value =
_effectiveDateTime = DateTime.parse(_selectEffectiveDate); '${p.year}-${intToStr(p.month!)}-${intToStr(p.day!)} ${intToStr(p.hour!)}:${intToStr(p.minute!)}';
}); state.effectiveDateTime.value =
DateTime.parse(state.selectEffectiveDate.value);
// });
}); });
}), }),
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.failureTime!.tr, leftTitel: TranslationLoader.lanKeys!.failureTime!.tr,
rightTitle: _selectFailureDate, rightTitle: state.selectFailureDate.value,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
PDuration selectDate = PDuration.parse(_failureDateTime); final PDuration selectDate =
PDuration.parse(state.failureDateTime.value);
Pickers.showDatePicker(context, Pickers.showDatePicker(context,
selectDate: selectDate, mode: DateMode.YMDHM, onConfirm: (p) { selectDate: selectDate,
setState(() { mode: DateMode.YMDHM, onConfirm: (PDuration p) {
_selectFailureDate = // setState(() {
'${p.year}-${intToStr(p.month!)}-${intToStr(p.day!)} ${intToStr(p.hour!)}:${intToStr(p.minute!)}'; state.selectFailureDate.value =
_failureDateTime = DateTime.parse(_selectFailureDate); '${p.year}-${intToStr(p.month!)}-${intToStr(p.day!)} ${intToStr(p.hour!)}:${intToStr(p.minute!)}';
}); state.failureDateTime.value =
DateTime.parse(state.selectFailureDate.value);
// });
}); });
}), }),
Container(height: 10.h), Container(height: 10.h),
@ -206,33 +178,41 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
// //
Widget remoteUnlockingWidget() { Widget remoteUnlockingWidget() {
return Column( return Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.lock!.tr, leftTitel: TranslationLoader.lanKeys!.lock!.tr,
rightTitle: _lockIdList.isEmpty rightTitle: state.lockIdList.isEmpty
? TranslationLoader.lanKeys!.pleaseSelect!.tr ? TranslationLoader.lanKeys!.pleaseSelect!.tr
: _lockIdList.length.toString(), : state.lockIdList.length.toString(),
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
Navigator.pushNamed(context, Routers.massSendLockGroupListPage, arguments: { Navigator.pushNamed(context, Routers.massSendLockGroupListPage,
"keyLimits":"1" arguments: <String, String>{'keyLimits': '1'})
}).then((value) { .then((Object? value) {
//ID列表 //ID列表
if (value != null) { if (value is Map<String, dynamic> &&
value as Map<String, dynamic>; value['selectLockIdList'] is List) {
_lockIdList = value['selectLockIdList']; state.lockIdList.clear();
value['selectLockIdList'].forEach((element) {
state.lockIdList.add(element);
});
setState(() {}); setState(() {});
} }
}); });
}), }),
Container(height: 10.h), Container(height: 10.h),
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.remoteUnlockingAllowed!.tr, leftTitel: '仅管理自己创建的用户',
rightTitle: "", rightTitle: '',
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: SizedBox(width: 60.w, height: 50.h, child: _switch()), isTipsImg: true,
action: () {}), tipsImgAction: () {
ShowTipView().showSureAlertDialog('授权管理员只能查看和管理自己下发的钥匙、密码等权限');
},
rightWidget: SizedBox(
width: 60.w,
height: 50.h,
child: _onlyManageYouCreatesUserSwitch())),
Container(height: 10.h), Container(height: 10.h),
], ],
); );
@ -240,14 +220,14 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
Widget keyBottomWidget() { Widget keyBottomWidget() {
return Column( return Column(
children: [ children: <Widget>[
SubmitBtn( SubmitBtn(
btnName: TranslationLoader.lanKeys!.sure!.tr, btnName: TranslationLoader.lanKeys!.sure!.tr,
borderRadius: 20.w, borderRadius: 20.w,
margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 30.w), margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 30.w),
padding: EdgeInsets.only(top: 25.w, bottom: 25.w), padding: EdgeInsets.only(top: 25.w, bottom: 25.w),
onClick: () { onClick: () {
addAuthorizedAdminRequest(); logic.addAuthorizedAdminRequest();
}), }),
], ],
); );
@ -260,7 +240,7 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
height: 50.h, height: 50.h,
width: 300.w, width: 300.w,
child: Row( child: Row(
children: [ children: <Widget>[
Expanded( Expanded(
child: TextField( child: TextField(
controller: editController, controller: editController,
@ -294,89 +274,51 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
SizedBox( SizedBox(
width: 10.w, width: 10.w,
), ),
isHaveBtn if (isHaveBtn)
? Container( Container(
width: 30.w, width: 30.w,
height: 30.w, height: 30.w,
decoration: const BoxDecoration( decoration: const BoxDecoration(
color: Colors.white, color: Colors.white,
image: DecorationImage( image: DecorationImage(
image: AssetImage('images/icon_addressBook.png'), image: AssetImage('images/icon_addressBook.png'),
fit: BoxFit.fill), fit: BoxFit.fill),
), ),
alignment: Alignment.center, alignment: Alignment.center,
child: InkWell( child: InkWell(
onTap: () async { onTap: () async {
Contact? currentContact = final Contact? currentContact =
await _contactPicker.selectContact(); await state.contactPicker.selectContact();
setState(() { // setState(() {
if (currentContact!.phoneNumbers!.isNotEmpty) { if (currentContact!.phoneNumbers!.isNotEmpty) {
_emailOrPhoneController.text = currentContact state.emailOrPhoneController.text = currentContact
.phoneNumbers![0] .phoneNumbers![0]
.replaceAll(RegExp(r"\s+\b|\b\s"), ""); .replaceAll(RegExp(r'\s+\b|\b\s'), '');
} }
if (currentContact.fullName!.isNotEmpty) { if (currentContact.fullName!.isNotEmpty) {
_keyNameController.text = currentContact.fullName!; state.keyNameController.text = currentContact.fullName!;
} }
}); // });
}, },
), ),
) )
: Container() else
Container()
], ],
), ),
); );
} }
//
Future<void> addAuthorizedAdminRequest() async {
String getFailureDateTime = '0';
String getEffectiveDateTime = '0';
if (widget.type == '1') {
getFailureDateTime = _failureDateTime.millisecondsSinceEpoch.toString();
getEffectiveDateTime =
_effectiveDateTime.millisecondsSinceEpoch.toString();
}
if (_lockIdList.isEmpty) {
logic.showToast("请选择锁".tr);
return;
}
var entity = await ApiRepository.to.addAuthorizedAdmin(
createUser: _isCreateUser ? "1" : "0",
endDate: getFailureDateTime,
isRemoteUnlock: _isRemoteUnlock == true ? '1' : '2',
keyGroupIdList: [],
lockIdList: _lockIdList,
name: _keyNameController.text,
startDate: getEffectiveDateTime,
userid: _emailOrPhoneController.text,
countryCode: countryCode,
usernameType: '1',
);
if (entity.errorCode!.codeIsSuccessful) {
_isSendSuccess = true;
setState(() {});
} else {
EasyLoading.showToast('${entity.errorMsg}', duration: 2000.milliseconds);
if (entity.errorCode == 425) {
//
_isCreateUser = true;
addAuthorizedAdminRequest();
}
}
}
// //
Widget sendElectronicKeySucceed() { Widget sendElectronicKeySucceed() {
return Column( return Column(
children: [ children: <Widget>[
Container( Container(
height: 250.h, height: 250.h,
width: 1.sw, width: 1.sw,
color: Colors.white, color: Colors.white,
child: Column( child: Column(
children: [ children: <Widget>[
SizedBox( SizedBox(
height: 30.h, height: 30.h,
), ),
@ -390,9 +332,9 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Text( Text(
"发送成功", '发送成功',
style: TextStyle( style: TextStyle(
fontSize: 26.sp, fontSize: 26.sp,
color: Colors.black, color: Colors.black,
@ -409,51 +351,30 @@ class _VolumeAuthorizationLockPageState extends State<VolumeAuthorizationLockPag
SubmitBtn( SubmitBtn(
btnName: '完成'.tr, btnName: '完成'.tr,
onClick: () { onClick: () {
_isSendSuccess = false; state.isSendSuccess.value = false;
Navigator.pop(context, true); Navigator.pop(context, true);
}), }),
SizedBox(
height: 10.h,
),
OutLineBtn(
btnName: '邮件通知',
onClick: () {
Navigator.pushNamed(context, Routers.sendEmailNotificationPage);
},
),
SizedBox(
height: 10.h,
),
OutLineBtn(
btnName: '微信通知',
onClick: () {},
),
SizedBox(
height: 10.h,
),
OutLineBtn(
btnName: '标记为已入住',
onClick: () {},
),
], ],
); );
} }
CupertinoSwitch _switch() { //
CupertinoSwitch _onlyManageYouCreatesUserSwitch() {
return CupertinoSwitch( return CupertinoSwitch(
activeColor: CupertinoColors.activeBlue, activeColor: CupertinoColors.activeBlue,
trackColor: CupertinoColors.systemGrey5, trackColor: CupertinoColors.systemGrey5,
thumbColor: CupertinoColors.white, thumbColor: CupertinoColors.white,
value: _isRemoteUnlock, value: state.onlyManageYouCreatesUser.value,
onChanged: (value) { onChanged: (bool value) {
setState(() { setState(() {
_isRemoteUnlock = !_isRemoteUnlock; state.onlyManageYouCreatesUser.value =
!state.onlyManageYouCreatesUser.value;
}); });
}, },
); );
} }
String intToStr(int v) { String intToStr(int v) {
return (v < 10) ? "0$v" : "$v"; return (v < 10) ? '0$v' : '$v';
} }
} }

View File

@ -1,5 +1,26 @@
import 'package:flutter/material.dart';
import 'package:flutter_native_contact_picker/flutter_native_contact_picker.dart';
import 'package:get/get.dart';
class VolumeAuthorizationLockState {
class VolumeAuthorizationLockState{ final FlutterContactPicker contactPicker = FlutterContactPicker();
final TextEditingController emailOrPhoneController =
} TextEditingController(); ///
final TextEditingController keyNameController =
TextEditingController(); //
late Contact contact;
RxList<int> lockIdList = <int>[].obs;
RxBool isSendSuccess = false.obs;
RxBool isCreateUser = false.obs; //
RxBool sRemoteUnlock = false.obs; //
RxBool onlyManageYouCreatesUser = false.obs; //
RxString selectEffectiveDate =
'${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day} ${DateTime.now().hour}:${DateTime.now().minute}'
.obs; //
RxString selectFailureDate = ''.obs; //
Rx<DateTime> effectiveDateTime = DateTime.now().obs;
Rx<DateTime> failureDateTime = DateTime.now().obs;
RxString countryName = '中国'.obs;
RxString countryCode = '86'.obs;
RxString selectWidgetType = '0'.obs;
}

View File

@ -147,7 +147,7 @@ class AddICCardLogic extends BaseGetXController{
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: (){
Get.close(1); Get.close(1);
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
// var publicKey = await Storage.getStringList(saveBluePublicKey); // var publicKey = await Storage.getStringList(saveBluePublicKey);
@ -193,7 +193,7 @@ class AddICCardLogic extends BaseGetXController{
// //
Future<void> senderCancelAddCardCommand() async { Future<void> senderCancelAddCardCommand() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -100,7 +100,7 @@ class CardDetailLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);
List<int> signKeyDataList = changeStringListToIntList(signKey!); List<int> signKeyDataList = changeStringListToIntList(signKey!);

View File

@ -229,7 +229,7 @@ class CardListLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: (){
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
// var publicKey = await Storage.getStringList(saveBluePublicKey); // var publicKey = await Storage.getStringList(saveBluePublicKey);
// List<int> publicKeyDataList = changeStringListToIntList(publicKey!); // List<int> publicKeyDataList = changeStringListToIntList(publicKey!);

View File

@ -105,7 +105,7 @@ class OtherTypeKeyChangeDateLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
@ -257,7 +257,7 @@ class OtherTypeKeyChangeDateLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
// var publicKey = await Storage.getStringList(saveBluePublicKey); // var publicKey = await Storage.getStringList(saveBluePublicKey);
// List<int> publicKeyDataList = changeStringListToIntList(publicKey!); // List<int> publicKeyDataList = changeStringListToIntList(publicKey!);
@ -313,7 +313,7 @@ class OtherTypeKeyChangeDateLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);

View File

@ -107,7 +107,7 @@ class OtherTypeKeyChangeValidityDateLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
@ -259,7 +259,7 @@ class OtherTypeKeyChangeValidityDateLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
// var publicKey = await Storage.getStringList(saveBluePublicKey); // var publicKey = await Storage.getStringList(saveBluePublicKey);
// List<int> publicKeyDataList = changeStringListToIntList(publicKey!); // List<int> publicKeyDataList = changeStringListToIntList(publicKey!);
@ -315,7 +315,7 @@ class OtherTypeKeyChangeValidityDateLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);

View File

@ -1,7 +1,9 @@
import 'package:date_format/date_format.dart'; import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInHolidays/checkingInAddHolidays/checkingInAddHolidays_state.dart';
import '../../../../../app_settings/app_colors.dart'; import '../../../../../app_settings/app_colors.dart';
import '../../../../../tools/commonItem.dart'; import '../../../../../tools/commonItem.dart';
@ -20,8 +22,10 @@ class CheckingInAddHolidaysPage extends StatefulWidget {
} }
class _CheckingInAddHolidaysPageState extends State<CheckingInAddHolidaysPage> { class _CheckingInAddHolidaysPageState extends State<CheckingInAddHolidaysPage> {
final logic = Get.put(CheckingInAddHolidaysLogic()); final CheckingInAddHolidaysLogic logic =
final state = Get.find<CheckingInAddHolidaysLogic>().state; Get.put(CheckingInAddHolidaysLogic());
final CheckingInAddHolidaysState state =
Get.find<CheckingInAddHolidaysLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -32,27 +36,31 @@ class _CheckingInAddHolidaysPageState extends State<CheckingInAddHolidaysPage> {
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor), backgroundColor: AppColors.mainColor),
body: Column( body: Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.name!.tr, leftTitel: TranslationLoader.lanKeys!.name!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
setHeight: false,
rightWidget: getTFWidget( rightWidget: getTFWidget(
"(${TranslationLoader.lanKeys!.mustFillIn!.tr})")), '(${TranslationLoader.lanKeys!.mustFillIn!.tr})')),
Obx(() => CommonItem( Obx(() => CommonItem(
leftTitel: TranslationLoader.lanKeys!.startDate!.tr, leftTitel: TranslationLoader.lanKeys!.startDate!.tr,
rightTitle: state.beginDate.value.isEmpty ? "(${TranslationLoader.lanKeys!.mustFillIn!.tr})" : state.beginDate.value, rightTitle: state.beginDate.value.isEmpty
? '(${TranslationLoader.lanKeys!.mustFillIn!.tr})'
: state.beginDate.value,
isHaveLine: true, isHaveLine: true,
isHaveDirection: false, isHaveDirection: false,
action: () async { action: () async {
await showDialog( await showDialog(
context: context, context: context,
builder: (context) { builder: (BuildContext context) {
return ShowCalendar( return ShowCalendar(
datePickerMode: DatePickerMode.day, datePickerMode: DatePickerMode.day,
selectAction: (dateTime) { selectAction: (DateTime dateTime) {
String beginDate = formatDate(dateTime, [yyyy,'-',mm,'-',dd]); final String beginDate = formatDate(
dateTime, <String>[yyyy, '-', mm, '-', dd]);
state.beginDate.value = beginDate; state.beginDate.value = beginDate;
Get.back(); Get.back();
// Navigator.of(context).pop(true); // Navigator.of(context).pop(true);
@ -61,17 +69,20 @@ class _CheckingInAddHolidaysPageState extends State<CheckingInAddHolidaysPage> {
})), })),
Obx(() => CommonItem( Obx(() => CommonItem(
leftTitel: TranslationLoader.lanKeys!.endDate!.tr, leftTitel: TranslationLoader.lanKeys!.endDate!.tr,
rightTitle: state.endDate.value.isEmpty ? "(${TranslationLoader.lanKeys!.mustFillIn!.tr})" : state.endDate.value, rightTitle: state.endDate.value.isEmpty
? '(${TranslationLoader.lanKeys!.mustFillIn!.tr})'
: state.endDate.value,
isHaveLine: true, isHaveLine: true,
isHaveDirection: false, isHaveDirection: false,
action: () async { action: () async {
await showDialog( await showDialog(
context: context, context: context,
builder: (context) { builder: (BuildContext context) {
return ShowCalendar( return ShowCalendar(
datePickerMode: DatePickerMode.day, datePickerMode: DatePickerMode.day,
selectAction: (dateTime) { selectAction: (DateTime dateTime) {
String endDate = formatDate(dateTime, [yyyy,'-',mm,'-',dd]); final String endDate = formatDate(
dateTime, <String>[yyyy, '-', mm, '-', dd]);
state.endDate.value = endDate; state.endDate.value = endDate;
Get.back(); Get.back();
}); });
@ -85,11 +96,12 @@ class _CheckingInAddHolidaysPageState extends State<CheckingInAddHolidaysPage> {
action: () async { action: () async {
await showDialog( await showDialog(
context: context, context: context,
builder: (context) { builder: (BuildContext context) {
return ShowCalendar( return ShowCalendar(
datePickerMode: DatePickerMode.day, datePickerMode: DatePickerMode.day,
selectAction: (dateTime) { selectAction: (DateTime dateTime) {
String makeUpWorkDate = formatDate(dateTime, [yyyy,'-',mm,'-',dd]); final String makeUpWorkDate = formatDate(
dateTime, <String>[yyyy, '-', mm, '-', dd]);
state.makeUpWorkDate.value = makeUpWorkDate; state.makeUpWorkDate.value = makeUpWorkDate;
Get.back(); Get.back();
}); });
@ -112,30 +124,26 @@ class _CheckingInAddHolidaysPageState extends State<CheckingInAddHolidaysPage> {
} }
Widget getTFWidget(String tfStr) { Widget getTFWidget(String tfStr) {
return Container( return Expanded(
height: 50.h, child: TextField(
width: 300.w, //
// color: Colors.red, maxLines: 2,
child: Row( minLines: 1,
children: [ controller: state.staffNameController,
Expanded( autofocus: false,
child: TextField( textAlign: TextAlign.end,
// decoration: InputDecoration(
maxLines: 1, //
controller: state.staffNameController, contentPadding: const EdgeInsets.only(bottom: 3),
autofocus: false, hintText: tfStr,
textAlign: TextAlign.end, hintStyle: TextStyle(
decoration: InputDecoration( fontSize: 22.sp, color: AppColors.darkGrayTextColor, height: 1),
// //线
contentPadding: const EdgeInsets.only(top: 12.0, bottom: 8.0), border: InputBorder.none,
hintText: tfStr, isCollapsed: true,
hintStyle: TextStyle( ),
fontSize: 22.sp, color: AppColors.darkGrayTextColor), inputFormatters: <TextInputFormatter>[
//线 LengthLimitingTextInputFormatter(30),
border: InputBorder.none,
),
),
),
], ],
), ),
); );
@ -145,7 +153,7 @@ class _CheckingInAddHolidaysPageState extends State<CheckingInAddHolidaysPage> {
return GestureDetector( return GestureDetector(
onTap: () {}, onTap: () {},
child: Row( child: Row(
children: [ children: <Widget>[
Image.asset( Image.asset(
'images/icon_round_unSelect.png', 'images/icon_round_unSelect.png',
width: 40.w, width: 40.w,

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInHolidays/checkingInSetHolidays/checkingInSetHolidays_state.dart';
import 'package:star_lock/tools/noData.dart'; import 'package:star_lock/tools/noData.dart';
import 'package:star_lock/tools/pickers/pickers.dart'; import 'package:star_lock/tools/pickers/pickers.dart';
import 'package:star_lock/tools/pickers/style/picker_style.dart'; import 'package:star_lock/tools/pickers/style/picker_style.dart';
@ -25,8 +26,10 @@ class CheckingInSetHolidaysPage extends StatefulWidget {
} }
class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> { class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
final logic = Get.put(CheckingInSetHolidaysLogic()); final CheckingInSetHolidaysLogic logic =
final state = Get.find<CheckingInSetHolidaysLogic>().state; Get.put(CheckingInSetHolidaysLogic());
final CheckingInSetHolidaysState state =
Get.find<CheckingInSetHolidaysLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -37,12 +40,14 @@ class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
titleWidget: titleWidget(), titleWidget: titleWidget(),
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor, backgroundColor: AppColors.mainColor,
actionsList: [ actionsList: <Widget>[
GestureDetector( GestureDetector(
onTap: () async { onTap: () async {
var data = await Get.toNamed( final dynamic data = await Get.toNamed(
Routers.checkingInAddHolidaysPage, Routers.checkingInAddHolidaysPage,
arguments: {"companyId": state.companyId.value}); arguments: <String, String>{
'companyId': state.companyId.value
});
if (data != null) { if (data != null) {
logic.editStaffLoadData(); logic.editStaffLoadData();
} }
@ -58,12 +63,12 @@ class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
], ],
), ),
body: Obx(() { body: Obx(() {
return state.holidaysListData.value!.isNotEmpty return state.holidaysListData.isNotEmpty
? ListView.builder( ? ListView.builder(
itemCount: state.holidaysListData.value!.length, itemCount: state.holidaysListData.length,
itemBuilder: (c, index) { itemBuilder: (BuildContext c, int index) {
HolidaysMonthListData holidaysMonthListData = final HolidaysMonthListData holidaysMonthListData =
state.holidaysListData.value![index]; state.holidaysListData[index];
return _checkingInListMouthItem(holidaysMonthListData); return _checkingInListMouthItem(holidaysMonthListData);
}) })
: NoData(); : NoData();
@ -71,34 +76,44 @@ class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
} }
Widget _checkingInListMouthItem(HolidaysMonthListData holidaysMonthListData) { Widget _checkingInListMouthItem(HolidaysMonthListData holidaysMonthListData) {
final double width = Get.width - 20.w * 2;
final double l = width * 0.2;
final double r = width * 0.8;
return GestureDetector( return GestureDetector(
child: Container( child: Container(
height: 140.h * holidaysMonthListData.listItem!.length + 20.w, decoration: BoxDecoration(
padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 20.w), gradient: LinearGradient(
colors: <Color>[
colorWithMonth(int.parse(
holidaysMonthListData.listItem![0].month.toString())),
Colors.white
],
stops: const <double>[0.2, 0.2],
),
),
margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 20.w),
child: Row( child: Row(
children: [ children: <Widget>[
Container( Container(
color: colorWithMonth(int.parse( color: colorWithMonth(int.parse(
holidaysMonthListData.listItem![0].month.toString())), holidaysMonthListData.listItem![0].month.toString())),
width: 100.w, width: l,
height: 140.h * holidaysMonthListData.listItem!.length,
child: Center( child: Center(
child: Text( child: Text(
"${holidaysMonthListData.listItem![0].month}\n${TranslationLoader.lanKeys!.month!.tr}", '${holidaysMonthListData.listItem![0].month}\n${TranslationLoader.lanKeys!.month!.tr}',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle(fontSize: 28.sp, color: Colors.white), style: TextStyle(fontSize: 28.sp, color: Colors.white),
))), ))),
SizedBox( SizedBox(
height: 140.h * holidaysMonthListData.listItem!.length, width: r,
width: 1.sw - 100.w - 20.w * 2,
child: ListView.builder( child: ListView.builder(
shrinkWrap: true, shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(), physics: const NeverScrollableScrollPhysics(),
itemCount: holidaysMonthListData.listItem!.length, itemCount: holidaysMonthListData.listItem!.length,
itemBuilder: (c, index) { itemBuilder: (BuildContext c, int index) {
ListItem listItem = holidaysMonthListData.listItem![index]; final ListItem listItem =
holidaysMonthListData.listItem![index];
return _checkingInListItem( return _checkingInListItem(
index,
listItem.vacationName, listItem.vacationName,
DateTool().dateToYMDString( DateTool().dateToYMDString(
listItem.vacationStartDate.toString()), listItem.vacationStartDate.toString()),
@ -107,10 +122,10 @@ class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
listItem.fillClassDate!.isNotEmpty listItem.fillClassDate!.isNotEmpty
? DateTool().dateToYMDString( ? DateTool().dateToYMDString(
listItem.fillClassDate.toString()) listItem.fillClassDate.toString())
: "", () async { : '', () async {
var data = await Get.toNamed( final dynamic data = await Get.toNamed(
Routers.checkingInDeletHolidaysPage, Routers.checkingInDeletHolidaysPage,
arguments: {"listItem": listItem}); arguments: <String, ListItem>{'listItem': listItem});
if (data != null) { if (data != null) {
logic.editStaffLoadData(); logic.editStaffLoadData();
} }
@ -123,83 +138,66 @@ class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
); );
} }
Widget _checkingInListItem( Widget _checkingInListItem(String? lockTypeTitle, String? vacationStartDate,
int index, String? vacationEndDate, String? makeUpClass, Function() action) {
String? lockTypeTitle,
String? vacationStartDate,
String? vacationEndDate,
String? makeUpClass,
Function() action) {
return GestureDetector( return GestureDetector(
onTap: action, onTap: action,
child: Column( child: Container(
children: [ padding:
Container( EdgeInsets.only(left: 20.w, right: 20.w, top: 10.h, bottom: 10.h),
color: Colors.white, decoration: BoxDecoration(
height: 140.h, border: Border(
padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 10.h), bottom: BorderSide(
child: Row( color: AppColors.mainBackgroundColor, width: 1.h, //
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
lockTypeTitle!,
style: TextStyle(fontSize: 24.sp),
),
],
),
SizedBox(height: 10.h),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
"${TranslationLoader.lanKeys!.libertyDay!.tr}:$vacationStartDate - $vacationEndDate",
style: TextStyle(fontSize: 20.sp),
),
],
),
SizedBox(height: 5.h),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
"${TranslationLoader.lanKeys!.coverDate!.tr}:$makeUpClass",
style: TextStyle(fontSize: 20.sp),
),
],
),
],
),
),
SizedBox(width: 20.h),
],
), ),
), ),
Container(color: AppColors.mainBackgroundColor, height: 1.h) ),
], child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
Characters(lockTypeTitle!).join('\u{200B}'),
style: TextStyle(fontSize: 24.sp),
),
SizedBox(height: 10.h),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'${TranslationLoader.lanKeys!.libertyDay!.tr}:$vacationStartDate - $vacationEndDate',
style: TextStyle(fontSize: 20.sp),
),
],
),
SizedBox(height: 5.h),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'${TranslationLoader.lanKeys!.coverDate!.tr}:$makeUpClass',
style: TextStyle(fontSize: 20.sp),
),
],
),
],
),
), ),
); );
} }
Widget titleWidget() { Widget titleWidget() {
return GestureDetector( return GestureDetector(
onTap: () { onTap: showListType,
showListType();
},
child: Obx(() => Container( child: Obx(() => Container(
width: 300.w, width: 300.w,
height: 50.h, height: 50.h,
color: AppColors.mainColor, color: AppColors.mainColor,
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Text( Text(
"${state.selectYear.value}${TranslationLoader.lanKeys!.year!.tr}", '${state.selectYear.value}${TranslationLoader.lanKeys!.year!.tr}',
style: TextStyle(color: Colors.white, fontSize: 26.sp), style: TextStyle(color: Colors.white, fontSize: 26.sp),
), ),
SizedBox( SizedBox(
@ -226,9 +224,7 @@ class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
// //
pickerStyle: PickerStyle( pickerStyle: PickerStyle(
cancelButton: GestureDetector( cancelButton: GestureDetector(
onTap: () { onTap: Get.back,
Get.back();
},
child: Container( child: Container(
alignment: Alignment.center, alignment: Alignment.center,
padding: const EdgeInsets.only(left: 22, right: 12), padding: const EdgeInsets.only(left: 22, right: 12),
@ -237,9 +233,7 @@ class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
), ),
), ),
commitButton: GestureDetector( commitButton: GestureDetector(
onTap: () { onTap: Get.back,
Get.back();
},
child: Container( child: Container(
alignment: Alignment.center, alignment: Alignment.center,
padding: const EdgeInsets.only(left: 22, right: 12), padding: const EdgeInsets.only(left: 22, right: 12),
@ -252,7 +246,7 @@ class _CheckingInSetHolidaysPageState extends State<CheckingInSetHolidaysPage> {
selectDate: PDuration(year: 2023), selectDate: PDuration(year: 2023),
minDate: PDuration(year: 1900), minDate: PDuration(year: 1900),
maxDate: PDuration(year: 2100), maxDate: PDuration(year: 2100),
onConfirm: (p) { onConfirm: (PDuration p) {
state.selectYear.value = p.year!; state.selectYear.value = p.year!;
logic.editStaffLoadData(); logic.editStaffLoadData();
}, },

View File

@ -3,6 +3,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInList/checkingInListMonth_entity.dart'; import 'package:star_lock/main/lockDetail/checkingIn/checkingInList/checkingInListMonth_entity.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInList/checkingInList_state.dart';
import 'package:star_lock/main/lockMian/entity/lockListInfo_entity.dart';
import '../../../../appRouters.dart'; import '../../../../appRouters.dart';
import '../../../../app_settings/app_colors.dart'; import '../../../../app_settings/app_colors.dart';
@ -23,8 +25,8 @@ class CheckingInListPage extends StatefulWidget {
} }
class _CheckingInListPageState extends State<CheckingInListPage> { class _CheckingInListPageState extends State<CheckingInListPage> {
final logic = Get.put(CheckingInListLogic()); final CheckingInListLogic logic = Get.put(CheckingInListLogic());
final state = Get.find<CheckingInListLogic>().state; final CheckingInListState state = Get.find<CheckingInListLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -35,26 +37,34 @@ class _CheckingInListPageState extends State<CheckingInListPage> {
titleWidget: titleWidget(), titleWidget: titleWidget(),
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor, backgroundColor: AppColors.mainColor,
actionsList: [ actionsList: <Widget>[
(state.getKeyInfosData.value.keyRight == 1) ? if (state.getKeyInfosData.value.keyRight == 1)
GestureDetector( GestureDetector(
onTap: () async { onTap: () async {
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode =
if(isDemoMode == false){ await Storage.getBool(ifIsDemoModeOrNot);
Get.toNamed(Routers.checkingInSetPage, arguments: { if (isDemoMode == false) {
"getKeyInfosData": state.getKeyInfosData.value, Get.toNamed(Routers.checkingInSetPage,
}); arguments: <String, LockListInfoItemEntity>{
}else{ 'getKeyInfosData': state.getKeyInfosData.value,
// Get.toNamed(Routers.selectLockTypePage); });
logic.showToast("演示模式"); } else {
} // Get.toNamed(Routers.selectLockTypePage);
}, logic.showToast('演示模式');
child: Image.asset('images/main/icon_lockDetail_checkIn_set.png', width: 36.w, height: 36.w,)) : Container(), }
},
child: Image.asset(
'images/main/icon_lockDetail_checkIn_set.png',
width: 36.w,
height: 36.w,
))
else
Container(),
SizedBox(width: 30.w), SizedBox(width: 30.w),
], ],
), ),
body: Column( body: Column(
children: [ children: <Widget>[
topInfo(), topInfo(),
SizedBox(height: 10.h), SizedBox(height: 10.h),
middleDayInfo(), middleDayInfo(),
@ -70,7 +80,7 @@ class _CheckingInListPageState extends State<CheckingInListPage> {
// height: 280.h, // height: 280.h,
color: Colors.white, color: Colors.white,
child: Column( child: Column(
children: [ children: <Widget>[
SizedBox(height: 30.h), SizedBox(height: 30.h),
Obx(() => Container( Obx(() => Container(
width: 110.w, width: 110.w,
@ -80,32 +90,38 @@ class _CheckingInListPageState extends State<CheckingInListPage> {
color: AppColors.mainColor, color: AppColors.mainColor,
borderRadius: BorderRadius.circular(60.w), borderRadius: BorderRadius.circular(60.w),
), ),
child: Image.asset(getTopImg(), width: 120.w, height: 120.w) child: Image.asset(getTopImg(), width: 120.w, height: 120.w))),
)),
SizedBox(height: 10.h), SizedBox(height: 10.h),
Obx(() => Text(getTopTitle(), style: TextStyle(color: Colors.black, fontSize: 24.sp))), Obx(() => Text(getTopTitle(),
style: TextStyle(color: Colors.black, fontSize: 24.sp))),
SizedBox(height: 30.h), SizedBox(height: 30.h),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: <Widget>[
// SizedBox(width: 30.w,), // SizedBox(width: 30.w,),
Row( Row(
children: [ children: <Widget>[
SizedBox(width: 20.w,), SizedBox(
width: 20.w,
),
GestureDetector( GestureDetector(
onTap: () async { onTap: () async {
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode =
if(isDemoMode == false){ await Storage.getBool(ifIsDemoModeOrNot);
if (isDemoMode == false) {
setState(() { setState(() {
state.isDay.value = true; state.isDay.value = true;
DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(state.checkListDateTimestamp.value); final DateTime dateTime =
String beginDate = formatDate(dateTime, [mm,'-',dd]); DateTime.fromMillisecondsSinceEpoch(
state.checkListDateTimestamp.value);
final String beginDate =
formatDate(dateTime, <String>[mm, '-', dd]);
state.checkListDate.value = beginDate; state.checkListDate.value = beginDate;
logic.loadDataByType(); logic.loadDataByType();
}); });
}else{ } else {
// Get.toNamed(Routers.selectLockTypePage); // Get.toNamed(Routers.selectLockTypePage);
logic.showToast("演示模式"); logic.showToast('演示模式');
} }
}, },
child: Container( child: Container(
@ -113,37 +129,47 @@ class _CheckingInListPageState extends State<CheckingInListPage> {
// height: 100.h, // height: 100.h,
color: Colors.white, color: Colors.white,
child: Obx(() => Column( child: Obx(() => Column(
mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [ children: <Widget>[
Text(TranslationLoader.lanKeys!.dailyCharts!.tr, style: TextStyle(color: state.isDay.value ? AppColors.mainColor : Colors.black, fontSize: 22.sp)), Text(TranslationLoader.lanKeys!.dailyCharts!.tr,
SizedBox(height: 10.h), style: TextStyle(
Visibility( color: state.isDay.value
visible: state.isDay.value, ? AppColors.mainColor
child: Container( : Colors.black,
width: 20.w, fontSize: 22.sp)),
height: 2.h, SizedBox(height: 10.h),
color: state.isDay.value ? AppColors.mainColor : Colors.black Visibility(
), visible: state.isDay.value,
) child: Container(
], width: 20.w,
)), height: 2.h,
color: state.isDay.value
? AppColors.mainColor
: Colors.black),
)
],
)),
), ),
), ),
// SizedBox(width: 20.w,), // SizedBox(width: 20.w,),
GestureDetector( GestureDetector(
onTap: () async { onTap: () async {
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode =
if(isDemoMode == false){ await Storage.getBool(ifIsDemoModeOrNot);
if (isDemoMode == false) {
setState(() { setState(() {
state.isDay.value = false; state.isDay.value = false;
DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(state.checkListDateTimestamp.value); final DateTime dateTime =
String beginDate = formatDate(dateTime, [mm]); DateTime.fromMillisecondsSinceEpoch(
state.checkListDateTimestamp.value);
final String beginDate =
formatDate(dateTime, <String>[mm]);
state.checkListDate.value = beginDate; state.checkListDate.value = beginDate;
logic.loadDataByType(); logic.loadDataByType();
}); });
}else{ } else {
// Get.toNamed(Routers.selectLockTypePage); // Get.toNamed(Routers.selectLockTypePage);
logic.showToast("演示模式"); logic.showToast('演示模式');
} }
}, },
child: Container( child: Container(
@ -151,49 +177,76 @@ class _CheckingInListPageState extends State<CheckingInListPage> {
// height: 100.h, // height: 100.h,
color: Colors.white, color: Colors.white,
child: Obx(() => Column( child: Obx(() => Column(
mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [ children: <Widget>[
Text(TranslationLoader.lanKeys!.monthlyLeaderboard!.tr, style: TextStyle(color: !state.isDay.value ? AppColors.mainColor : Colors.black, fontSize: 22.sp)), Text(
SizedBox(height: 10.h), TranslationLoader
Visibility( .lanKeys!.monthlyLeaderboard!.tr,
visible: !state.isDay.value, style: TextStyle(
child: Container(width: 20.w, height: 2.h, color: !state.isDay.value ? AppColors.mainColor : Colors.black)) color: !state.isDay.value
], ? AppColors.mainColor
)), : Colors.black,
fontSize: 22.sp)),
SizedBox(height: 10.h),
Visibility(
visible: !state.isDay.value,
child: Container(
width: 20.w,
height: 2.h,
color: !state.isDay.value
? AppColors.mainColor
: Colors.black))
],
)),
), ),
), ),
], ],
), ),
GestureDetector( GestureDetector(
onTap: () async { onTap: () async {
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode =
if(isDemoMode == false){ await Storage.getBool(ifIsDemoModeOrNot);
if (isDemoMode == false) {
await showDialog( await showDialog(
context: Get.context!, context: Get.context!,
builder: (context) { builder: (BuildContext context) {
return ShowCalendar( return ShowCalendar(
datePickerMode: DatePickerMode.day, datePickerMode: DatePickerMode.day,
selectAction: (dateTime) { selectAction: (DateTime dateTime) {
setState(() { setState(() {
state.checkListDateTimestamp.value = dateTime.millisecondsSinceEpoch; state.checkListDateTimestamp.value =
String beginDate = formatDate(dateTime, state.isDay.value ? [mm,'-',dd] : [mm]); dateTime.millisecondsSinceEpoch;
final String beginDate = formatDate(
dateTime,
state.isDay.value
? <String>[mm, '-', dd]
: <String>[mm]);
state.checkListDate.value = beginDate; state.checkListDate.value = beginDate;
logic.loadDataByType(); logic.loadDataByType();
Get.back(); Get.back();
}); });
}); });
}); });
}else{ } else {
// Get.toNamed(Routers.selectLockTypePage); // Get.toNamed(Routers.selectLockTypePage);
logic.showToast("演示模式"); logic.showToast('演示模式');
} }
}, },
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Text(state.checkListDate.value, style: TextStyle(color: Colors.black, fontSize: 22.sp),), Text(
Image.asset('images/icon_grayPullDown.png', width: 50.w, height: 30.w,), state.checkListDate.value,
SizedBox(width: 10.w,), style: TextStyle(color: Colors.black, fontSize: 22.sp),
),
Image.asset(
'images/icon_grayPullDown.png',
width: 50.w,
height: 30.w,
),
SizedBox(
width: 10.w,
),
], ],
), ),
) )
@ -207,131 +260,174 @@ class _CheckingInListPageState extends State<CheckingInListPage> {
Widget middleDayInfo() { Widget middleDayInfo() {
return Obx(() => Visibility( return Obx(() => Visibility(
visible: state.isDay.value, visible: state.isDay.value,
child: Container( child: Container(
height: 80.h, height: 80.h,
color: Colors.white, color: Colors.white,
margin: EdgeInsets.only(left: 15.h, right: 15.h, bottom: 10.h), margin: EdgeInsets.only(left: 15.h, right: 15.h, bottom: 10.h),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [ children: <Widget>[
SizedBox(height: 5.h), Column(
Text(state.lateTimes.value, style: TextStyle(color: Colors.black, fontSize: 20.sp)), mainAxisAlignment: MainAxisAlignment.spaceAround,
Text(TranslationLoader.lanKeys!.beLate!.tr, style: TextStyle(color: Colors.black, fontSize: 22.sp)), children: <Widget>[
SizedBox(height: 5.h), SizedBox(height: 5.h),
Text(state.lateTimes.value,
style: TextStyle(color: Colors.black, fontSize: 20.sp)),
Text(TranslationLoader.lanKeys!.beLate!.tr,
style: TextStyle(color: Colors.black, fontSize: 22.sp)),
SizedBox(height: 5.h),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
SizedBox(height: 5.h),
Text(state.earlyTimes.value,
style: TextStyle(color: Colors.black, fontSize: 20.sp)),
Text(TranslationLoader.lanKeys!.leaveEarly!.tr,
style: TextStyle(color: Colors.black, fontSize: 22.sp)),
SizedBox(height: 5.h),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
SizedBox(height: 5.h),
Text(state.noPunchTimes.value,
style: TextStyle(color: Colors.black, fontSize: 20.sp)),
Text(TranslationLoader.lanKeys!.noCardPunched!.tr,
style: TextStyle(color: Colors.black, fontSize: 22.sp)),
SizedBox(height: 5.h),
],
),
], ],
), ),
Column( ),
mainAxisAlignment: MainAxisAlignment.spaceAround, ));
children: [
SizedBox(height: 5.h),
Text(state.earlyTimes.value, style: TextStyle(color: Colors.black, fontSize: 20.sp)),
Text(TranslationLoader.lanKeys!.leaveEarly!.tr, style: TextStyle(color: Colors.black, fontSize: 22.sp)),
SizedBox(height: 5.h),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(height: 5.h),
Text(state.noPunchTimes.value, style: TextStyle(color: Colors.black, fontSize: 20.sp)),
Text(TranslationLoader.lanKeys!.noCardPunched!.tr, style: TextStyle(color: Colors.black, fontSize: 22.sp)),
SizedBox(height: 5.h),
],
),
],
),
),
));
} }
Widget getBottomList(){ Widget getBottomList() {
if((state.isDay.value == true && (state.listType.value == "1")) || (state.isDay.value == true && (state.listType.value == "2"))){ if ((state.isDay.value == true && (state.listType.value == '1')) ||
(state.isDay.value == true && (state.listType.value == '2'))) {
return bottomDayList(); return bottomDayList();
}else{ } else {
return bottomMonthList(); return bottomMonthList();
} }
} }
Widget bottomDayList() { Widget bottomDayList() {
return Obx(() => state.checkingInDayListData.value.isNotEmpty ? ListView.separated( return Obx(() => state.checkingInDayListData.isNotEmpty
itemCount: state.checkingInDayListData.value.length, ? ListView.separated(
itemBuilder: (c, index) { itemCount: state.checkingInDayListData.length,
AttendanceRecordDayList attendanceRecordList= state.checkingInDayListData.value[index]; itemBuilder: (BuildContext c, int index) {
return _checkingInListItem(index, attendanceRecordList.headurl, attendanceRecordList.staffName, () { final AttendanceRecordDayList attendanceRecordList =
Get.toNamed(Routers.checkingInDetailPage, arguments: { state.checkingInDayListData[index];
// "getKeyInfosData": state.getKeyInfosData.value, return _checkingInListItem(
"companyId": state.companyId.value, index,
"staffId": attendanceRecordList.staffId, attendanceRecordList.headurl,
"staffName": attendanceRecordList.staffName, attendanceRecordList.staffName,
attendanceRecordList.attendanceType, () {
Get.toNamed(Routers.checkingInDetailPage,
arguments: <String, Object?>{
// "getKeyInfosData": state.getKeyInfosData.value,
'companyId': state.companyId.value,
'staffId': attendanceRecordList.staffId,
'staffName': attendanceRecordList.staffName,
});
}); });
}); },
}, separatorBuilder: (BuildContext context, int index) {
separatorBuilder: (context, index) { return const Divider(height: 1, color: AppColors.greyLineColor);
return const Divider(height: 1, color: AppColors.greyLineColor); },
}, )
) : NoData(noDataHeight: 1.sh - ScreenUtil().statusBarHeight*2 - 64.h - 280.h - 90.h,)); : NoData(
noDataHeight:
1.sh - ScreenUtil().statusBarHeight * 2 - 64.h - 280.h - 90.h,
));
} }
Widget bottomMonthList() { Widget bottomMonthList() {
return Obx(() => state.checkingInMonthListData.value.isNotEmpty ? ListView.separated( return Obx(() => state.checkingInMonthListData.isNotEmpty
itemCount: state.checkingInMonthListData.value.length, ? ListView.separated(
itemBuilder: (c, index) { itemCount: state.checkingInMonthListData.length,
AttendanceRecordMonthList attendanceRecordList= state.checkingInMonthListData.value[index]; itemBuilder: (BuildContext c, int index) {
return _checkingInListItem(index, attendanceRecordList.headurl, attendanceRecordList.staffName, () { final AttendanceRecordMonthList attendanceRecordList =
Get.toNamed(Routers.checkingInDetailPage, arguments: { state.checkingInMonthListData[index];
"companyId": state.companyId.value, return _checkingInListItem(
"staffId": attendanceRecordList.staffId, index,
"staffName": attendanceRecordList.staffName, attendanceRecordList.headurl,
}); attendanceRecordList.staffName,
}); attendanceRecordList.attendanceType, () {
}, Get.toNamed(Routers.checkingInDetailPage,
separatorBuilder: (context, index) { arguments: <String, Object?>{
return const Divider(height: 1, color: AppColors.greyLineColor); 'companyId': state.companyId.value,
}, 'staffId': attendanceRecordList.staffId,
) : NoData(noDataHeight: 1.sh - - ScreenUtil().statusBarHeight - 280.h - 90.h,)); 'staffName': attendanceRecordList.staffName,
});
});
},
separatorBuilder: (BuildContext context, int index) {
return const Divider(height: 1, color: AppColors.greyLineColor);
},
)
: NoData(
noDataHeight: 1.sh - -ScreenUtil().statusBarHeight - 280.h - 90.h,
));
} }
Widget _checkingInListItem(int index, String? headUrl, String? name, Function() action) { Widget _checkingInListItem(
int index, String? headUrl, String? name, int? type, Function() action) {
return GestureDetector( return GestureDetector(
onTap: action, onTap: action,
child: Container( child: Container(
// height: 80.h, // height: 80.h,
padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 10.h, bottom: 10.h), padding:
EdgeInsets.only(left: 20.w, right: 20.w, top: 10.h, bottom: 10.h),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(10.w), borderRadius: BorderRadius.circular(10.w),
), ),
child: Row( child: Row(
children: [ children: <Widget>[
SizedBox(width: 20.w,), SizedBox(
Text("${index+1}", style: TextStyle(fontSize: 20.sp),), width: 20.w,
SizedBox(width: 20.w,), ),
Image.asset('images/controls_user.png', width: 60.w, height: 60.w,), Text(
// Container( '${index + 1}',
// width: 60.h, style: TextStyle(fontSize: 20.sp),
// height: 60.h, ),
// decoration: BoxDecoration( SizedBox(
// color: AppColors.mainColor, width: 20.w,
// border: Border.all(width: 1, color: AppColors.mainColor), ),
// borderRadius: BorderRadius.circular(30.h), if (headUrl == null || headUrl == '')
// ), Image.asset(
// padding: EdgeInsets.all(10.w), getTypeIcon(type ?? 0),
// child: Image.asset( width: 60.w,
// 'images/controls_user.png', height: 60.w,
// width: 30.w, )
// height: 30.w, else
// color: Colors.white, ClipRRect(
// )), borderRadius: BorderRadius.circular(100.w),
child: Image.network(
headUrl,
width: 60.w,
height: 60.w,
),
),
SizedBox(width: 20.w), SizedBox(width: 20.w),
Expanded( Expanded(
child: Text(name!, style: TextStyle(fontSize: 24.sp),), child: Text(
name!,
style: TextStyle(fontSize: 24.sp),
),
), ),
SizedBox(width: 20.h), SizedBox(width: 20.h),
Image.asset("images/icon_right_grey.png", width: 21.w, height: 21.w,), Image.asset(
'images/icon_right_grey.png',
width: 21.w,
height: 21.w,
),
SizedBox(width: 20.h), SizedBox(width: 20.h),
], ],
), ),
@ -339,35 +435,71 @@ class _CheckingInListPageState extends State<CheckingInListPage> {
); );
} }
// 1APP 2 3 4
String getTypeIcon(int type) {
String title = 'images/controls_user.png';
switch (type) {
case 1:
//
title = 'images/controls_user.png';
break;
case 2:
//
title = 'images/icon_password.png';
break;
case 3:
// ic卡
title = 'images/icon_card.png';
break;
case 4:
//
title = 'images/icon_fingerprint.png';
break;
default:
break;
}
return title;
}
Widget titleWidget() { Widget titleWidget() {
return GestureDetector( return GestureDetector(
onTap: () async { onTap: () async {
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode = await Storage.getBool(ifIsDemoModeOrNot);
if(isDemoMode == false){ if (isDemoMode == false) {
showListType(); showListType();
}else{ } else {
// Get.toNamed(Routers.selectLockTypePage); // Get.toNamed(Routers.selectLockTypePage);
logic.showToast("演示模式"); logic.showToast('演示模式');
} }
}, },
child: Obx(() => Container( child: Obx(() => Container(
// width: 200.w, // width: 200.w,
// height: 60.h, // height: 60.h,
color: AppColors.mainColor, color: AppColors.mainColor,
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Text(state.listTypeStr.value, style: TextStyle(color: Colors.white, fontSize: 26.sp),), Text(
SizedBox(width: 5.w,), state.listTypeStr.value,
Image.asset('images/main/icon_lockDetail_checkIn_topTitle.png', width: 22.w, height: 16.w, fit: BoxFit.fill,) style: TextStyle(color: Colors.white, fontSize: 26.sp),
], ),
), SizedBox(
)), width: 5.w,
),
Image.asset(
'images/main/icon_lockDetail_checkIn_topTitle.png',
width: 22.w,
height: 16.w,
fit: BoxFit.fill,
)
],
),
)),
); );
} }
void showListType() { void showListType() {
var list = [ final List<String> list = <String>[
TranslationLoader.lanKeys!.earlyArrivalList!.tr, TranslationLoader.lanKeys!.earlyArrivalList!.tr,
TranslationLoader.lanKeys!.lateList!.tr, TranslationLoader.lanKeys!.lateList!.tr,
TranslationLoader.lanKeys!.hardWorkingList!.tr TranslationLoader.lanKeys!.hardWorkingList!.tr
@ -385,39 +517,39 @@ class _CheckingInListPageState extends State<CheckingInListPage> {
//adapter: PickerAdapter(), //adapter: PickerAdapter(),
data: list, data: list,
// //
clickCallBack: (int index, var str) { clickCallBack: (int index, Object str) {
setState(() { setState(() {
state.listTypeStr.value = str.toString(); state.listTypeStr.value = str.toString();
state.isDay.value = true; state.isDay.value = true;
if(index == 0){ if (index == 0) {
state.listType.value = "1"; state.listType.value = '1';
}else if(index == 1){ } else if (index == 1) {
state.listType.value = "2"; state.listType.value = '2';
}else if(index == 2){ } else if (index == 2) {
state.listType.value = "3"; state.listType.value = '3';
} }
logic.loadDataByType(); logic.loadDataByType();
}); });
}); });
} }
String getTopImg(){ String getTopImg() {
if(state.listType.value == "1"){ if (state.listType.value == '1') {
return "images/main/icon_lockDetail_checkInRanking_zd.png"; return 'images/main/icon_lockDetail_checkInRanking_zd.png';
}else if(state.listType.value == "2"){ } else if (state.listType.value == '2') {
return "images/main/icon_lockDetail_checkInRanking_cd.png"; return 'images/main/icon_lockDetail_checkInRanking_cd.png';
}else{ } else {
return "images/main/icon_lockDetail_checkInRanking_qf.png"; return 'images/main/icon_lockDetail_checkInRanking_qf.png';
} }
} }
String getTopTitle(){ String getTopTitle() {
if(state.listType.value == "1"){ if (state.listType.value == '1') {
return "无考勤记录"; return '无考勤记录';
}else if(state.listType.value == "2"){ } else if (state.listType.value == '2') {
return "大家干劲十足"; return '大家干劲十足';
}else{ } else {
return "工作时长未出炉"; return '工作时长未出炉';
} }
} }
} }

View File

@ -1,7 +1,9 @@
import 'dart:async'; import 'dart:async';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/login/login/entity/LoginEntity.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInSet/checkingInSet_entity.dart';
import 'package:star_lock/main/lockDetail/lockSet/lockSet/checkingInInfoData_entity.dart';
import '../../../../network/api_repository.dart'; import '../../../../network/api_repository.dart';
import '../../../../tools/baseGetXController.dart'; import '../../../../tools/baseGetXController.dart';
@ -9,96 +11,94 @@ import '../../../../tools/dateTool.dart';
import '../../../../tools/eventBusEventManage.dart'; import '../../../../tools/eventBusEventManage.dart';
import 'checkingInSet_state.dart'; import 'checkingInSet_state.dart';
class CheckingInSetLogic extends BaseGetXController{ class CheckingInSetLogic extends BaseGetXController {
CheckingInSetState state = CheckingInSetState(); CheckingInSetState state = CheckingInSetState();
// //
void openCheckingInData() async{ Future<void> openCheckingInData() async {
var entity = await ApiRepository.to.openCheckingInData( final CheckingInInfoDataEntity entity = await ApiRepository.to.openCheckingInData(
lockId:state.getKeyInfosData.value.lockId.toString(), lockId: state.getKeyInfosData.value.lockId.toString(),
); );
if(entity.errorCode!.codeIsSuccessful){ if (entity.errorCode!.codeIsSuccessful) {
state.companyId.value = entity.data!.companyId.toString(); state.companyId.value = entity.data!.companyId.toString();
getCheckInSetInfoData(); getCheckInSetInfoData();
} }
} }
// //
void getCheckInSetInfoData() async{ Future<void> getCheckInSetInfoData() async {
var entity = await ApiRepository.to.getCheckInSetInfoData( final CheckingInSetEntity entity = await ApiRepository.to.getCheckInSetInfoData(
companyId: state.companyId.value, companyId: state.companyId.value,
); );
if(entity.errorCode!.codeIsSuccessful){ if (entity.errorCode!.codeIsSuccessful) {
state.checkingInSetInfo.value = entity.data!; state.checkingInSetInfo.value = entity.data!;
state.beginTime.value = DateTool().dateToHNString(state.checkingInSetInfo.value.workStartTime.toString()); state.beginTime.value = DateTool().dateToHNString(
state.endTime.value = DateTool().dateToHNString(state.checkingInSetInfo.value.workEndTime.toString()); state.checkingInSetInfo.value.workStartTime.toString());
state.beginTimeTimestamp.value = state.checkingInSetInfo.value.workStartTime.toString(); state.endTime.value = DateTool()
state.endTimeTimestamp.value = state.checkingInSetInfo.value.workEndTime.toString(); .dateToHNString(state.checkingInSetInfo.value.workEndTime.toString());
state.beginTimeTimestamp.value =
state.checkingInSetInfo.value.workStartTime.toString();
state.endTimeTimestamp.value =
state.checkingInSetInfo.value.workEndTime.toString();
state.weekDays.value = state.checkingInSetInfo.value.workDay!; state.weekDays.value = state.checkingInSetInfo.value.workDay!;
state.weekDaysStr.value = state.weekDays.value.join(","); state.weekDaysStr.value = state.weekDays.join(',');
state.isCustom.value = (state.checkingInSetInfo.value.attendanceType! == 0) ? true : false; state.isCustom.value = state.checkingInSetInfo.value.attendanceType! == 0;
state.staffNumber.value = state.checkingInSetInfo.value.staffNum!.toString(); state.staffNumber.value =
state.checkingInSetInfo.value.staffNum!.toString();
state.companyName.value = state.checkingInSetInfo.value.companyName!; state.companyName.value = state.checkingInSetInfo.value.companyName!;
state.changeNameController.text = state.companyName.value; state.changeNameController.text = state.companyName.value;
} }
} }
// //
void editCheckInSetInfoData() async{ Future<void> editCheckInSetInfoData() async {
var entity = await ApiRepository.to.editCheckInSetInfoData( final LoginEntity entity = await ApiRepository.to.editCheckInSetInfoData(
attendanceType: state.checkingInSetInfo.value.attendanceType.toString(), attendanceType: state.checkingInSetInfo.value.attendanceType.toString(),
companyId: state.checkingInSetInfo.value.companyId.toString(), companyId: state.checkingInSetInfo.value.companyId.toString(),
type: "1", type: '1',
companyName: state.changeNameController.text, companyName: state.changeNameController.text,
workEndTime: state.checkingInSetInfo.value.workEndTime.toString(), workEndTime: state.checkingInSetInfo.value.workEndTime.toString(),
workStartTime: state.checkingInSetInfo.value.workStartTime.toString(), workStartTime: state.checkingInSetInfo.value.workStartTime.toString(),
workDay:state.checkingInSetInfo.value.workDay!, workDay: state.checkingInSetInfo.value.workDay!,
); );
if(entity.errorCode!.codeIsSuccessful){ if (entity.errorCode!.codeIsSuccessful) {
state.companyName.value = state.changeNameController.text; state.companyName.value = state.changeNameController.text;
showToast("修改成功"); showToast('修改成功');
} }
} }
// //
void deletCompanyData() async{ Future<void> deletCompanyData() async {
var entity = await ApiRepository.to.deletCompanyData( final CheckingInInfoDataEntity entity = await ApiRepository.to.deletCompanyData(
companyId:state.checkingInSetInfo.value.companyId!, companyId: state.checkingInSetInfo.value.companyId!,
); );
if(entity.errorCode!.codeIsSuccessful){ if (entity.errorCode!.codeIsSuccessful) {
eventBus.fire(LockSetChangeSetRefreshLockDetailWithType(0, "0")); eventBus.fire(LockSetChangeSetRefreshLockDetailWithType(0, '0'));
Get.close(2); Get.close(2);
} }
} }
late StreamSubscription _teamEvent; late StreamSubscription _teamEvent;
void _initLoadDataAction() { void _initLoadDataAction() {
_teamEvent = eventBus.on<RefreshCheckInSetDataEvent>().listen((event) { _teamEvent = eventBus.on<RefreshCheckInSetDataEvent>().listen((RefreshCheckInSetDataEvent event) {
getCheckInSetInfoData(); getCheckInSetInfoData();
}); });
} }
@override @override
void onReady() { void onReady() {
// TODO: implement onReady
super.onReady(); super.onReady();
_initLoadDataAction(); _initLoadDataAction();
openCheckingInData(); openCheckingInData();
} }
@override
void onInit() {
// TODO: implement onInit
super.onInit();
}
@override @override
void onClose() { void onClose() {
// TODO: implement onClose
_teamEvent.cancel(); _teamEvent.cancel();
} }
} }

View File

@ -4,6 +4,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/app_settings/app_colors.dart'; import 'package:star_lock/app_settings/app_colors.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInSet/checkingInSet_state.dart';
import '../../../../appRouters.dart'; import '../../../../appRouters.dart';
import '../../../../tools/commonItem.dart'; import '../../../../tools/commonItem.dart';
@ -22,8 +23,8 @@ class CheckingInSetPage extends StatefulWidget {
} }
class _CheckingInSetPageState extends State<CheckingInSetPage> { class _CheckingInSetPageState extends State<CheckingInSetPage> {
final logic = Get.put(CheckingInSetLogic()); final CheckingInSetLogic logic = Get.put(CheckingInSetLogic());
final state = Get.find<CheckingInSetLogic>().state; final CheckingInSetState state = Get.find<CheckingInSetLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -31,17 +32,17 @@ class _CheckingInSetPageState extends State<CheckingInSetPage> {
backgroundColor: AppColors.mainBackgroundColor, backgroundColor: AppColors.mainBackgroundColor,
appBar: TitleAppBar( appBar: TitleAppBar(
barTitle: barTitle:
"${TranslationLoader.lanKeys!.checkingIn!.tr}${TranslationLoader.lanKeys!.set!.tr}", '${TranslationLoader.lanKeys!.checkingIn!.tr}${TranslationLoader.lanKeys!.set!.tr}',
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor), backgroundColor: AppColors.mainColor),
body: Column( body: Column(
children: [ children: <Widget>[
Obx(() => CommonItem( Obx(() => CommonItem(
leftTitel: leftTitel:
"公司名称".tr, '公司名称'.tr,
// rightTitle: state.companyName.value ?? "", rightTitle: state.companyName.value ?? '',
isHaveRightWidget: true, // isHaveRightWidget: true,
rightWidget: getTFWidget(), // rightWidget: getTFWidget(),
isHaveLine: true, isHaveLine: true,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
@ -53,61 +54,55 @@ class _CheckingInSetPageState extends State<CheckingInSetPage> {
isHaveLine: true, isHaveLine: true,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
Get.toNamed(Routers.checkingInStaffManagePage, arguments: { Get.toNamed(Routers.checkingInStaffManagePage, arguments: <String, Object>{
"getKeyInfosData": state.getKeyInfosData.value, 'getKeyInfosData': state.getKeyInfosData.value,
"companyId": state.companyId.value 'companyId': state.companyId.value
}); });
})), })),
Obx(() => CommonItem( Obx(() => CommonItem(
leftTitel: leftTitel:
"${TranslationLoader.lanKeys!.work!.tr}${TranslationLoader.lanKeys!.time!.tr}", "${TranslationLoader.lanKeys!.work!.tr}${TranslationLoader.lanKeys!.time!.tr}",
rightTitle: (state.beginTime.value.isNotEmpty) ? "${state.beginTime.value} - ${state.endTime.value}" : "", rightTitle: (state.beginTime.value.isNotEmpty) ? '${state.beginTime.value} - ${state.endTime.value}' : '',
isHaveLine: true, isHaveLine: true,
isHaveDirection: true, isHaveDirection: true,
action: () async { action: () async {
var data = await Get.toNamed(Routers.checkingInSetWorkTimePage, arguments: { var data = await Get.toNamed(Routers.checkingInSetWorkTimePage, arguments: <String, Object>{
// "getKeyInfosData": state.getKeyInfosData.value, // "getKeyInfosData": state.getKeyInfosData.value,
"companyId": state.companyId.value, 'companyId': state.companyId.value,
"pushType": "2", 'pushType': '2',
"checkingInSetInfo": state.checkingInSetInfo.value, 'checkingInSetInfo': state.checkingInSetInfo.value,
}); });
if(data != null) { if(data != null) {
setState(() { setState(logic.getCheckInSetInfoData);
// state.beginTime.value = data["beginTime"];
// state.endTime.value = data["endTime"];
// state.beginTimeTimestamp.value = data["beginTimeTimestamp"];
// state.endTimeTimestamp.value = data["endTimeTimestamp"];
logic.getCheckInSetInfoData();
});
} }
})), })),
Obx(() => CommonItem( Obx(() => CommonItem(
leftTitel: leftTitel:
"${TranslationLoader.lanKeys!.workday!.tr}${TranslationLoader.lanKeys!.set!.tr}", "${TranslationLoader.lanKeys!.workday!.tr}${TranslationLoader.lanKeys!.set!.tr}",
rightTitle: state.isCustom.value == true ? state.weekDaysStr.value : (state.weekDaysStr.value.length == 5 ? "单休" : "双休"), rightTitle: state.isCustom.value == true ? state.weekDaysStr.value : (state.weekDaysStr.value.length == 5 ? '单休' : '双休'),
isHaveLine: true, isHaveLine: true,
isHaveDirection: true, isHaveDirection: true,
action: () async { action: () async {
var data = await Get.toNamed(Routers.checkingInSetWorkdaySet, arguments: { var data = await Get.toNamed(Routers.checkingInSetWorkdaySet, arguments: <String, Object>{
"getKeyInfosData": state.getKeyInfosData.value, 'getKeyInfosData': state.getKeyInfosData.value,
"companyId": state.companyId.value, 'companyId': state.companyId.value,
"pushType": "2", 'pushType': '2',
"checkingInSetInfo": state.checkingInSetInfo.value, 'checkingInSetInfo': state.checkingInSetInfo.value,
}); });
if(data != null) { if(data != null) {
state.isCustom.value = data["attendanceType"]; state.isCustom.value = data['attendanceType'];
state.weekDays.value = data["weekDays"]; state.weekDays.value = data['weekDays'];
state.weekDaysStr.value = state.weekDays.value.join(","); state.weekDaysStr.value = state.weekDays.join(',');
} }
})), })),
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.holidays!.tr, leftTitel: TranslationLoader.lanKeys!.holidays!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: false, isHaveLine: false,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
Get.toNamed(Routers.checkingInSetHolidaysPage, arguments: { Get.toNamed(Routers.checkingInSetHolidaysPage, arguments: <String, String>{
"companyId": state.companyId.value 'companyId': state.companyId.value
}); });
}), }),
SizedBox( SizedBox(
@ -117,16 +112,14 @@ class _CheckingInSetPageState extends State<CheckingInSetPage> {
visible: state.getKeyInfosData.value.isLockOwner == 1, visible: state.getKeyInfosData.value.isLockOwner == 1,
child: SubmitBtn( child: SubmitBtn(
btnName: btnName:
"${TranslationLoader.lanKeys!.delete!.tr} ${TranslationLoader.lanKeys!.company!.tr}", '${TranslationLoader.lanKeys!.delete!.tr} ${TranslationLoader.lanKeys!.company!.tr}',
borderRadius: 20.w, borderRadius: 20.w,
fontSize: 32.sp, fontSize: 32.sp,
isDelete: true, isDelete: true,
margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w), margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w),
padding: EdgeInsets.only(top: 20.w, bottom: 20.w), padding: EdgeInsets.only(top: 20.w, bottom: 20.w),
onClick: () { onClick: () {
ShowTipView().showIosTipWithContentDialog("是否删除?".tr, () { ShowTipView().showIosTipWithContentDialog('是否删除?'.tr, logic.deletCompanyData);
logic.deletCompanyData();
});
// showDeletCompanyAlertDialog(context); // showDeletCompanyAlertDialog(context);
}), }),
), ),
@ -140,12 +133,19 @@ class _CheckingInSetPageState extends State<CheckingInSetPage> {
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
return ShowTFView( return ShowTFView(
title: "修改公司名字".tr, title: '修改公司名字'.tr,
tipTitle: "", tipTitle: '',
controller: state.changeNameController, controller: state.changeNameController,
inputFormatters: <TextInputFormatter>[
LengthLimitingTextInputFormatter(30),
],
sureClick: () { sureClick: () {
if(state.changeNameController.text.isEmpty){ if(state.changeNameController.text.isEmpty){
logic.showToast("请输入公司名字".tr); logic.showToast('请输入公司名字'.tr);
return;
}
if(state.changeNameController.text.length <6){
logic.showToast('公司名字长度不能小于 6 '.tr);
return; return;
} }
Get.back(); Get.back();
@ -159,7 +159,7 @@ class _CheckingInSetPageState extends State<CheckingInSetPage> {
// //
Widget getTFWidget() { Widget getTFWidget() {
state.nameController.text = state.companyName.value ?? ""; state.nameController.text = state.companyName.value ?? '';
return Container( return Container(
// color: Colors.red, // color: Colors.red,
height: 65.h, height: 65.h,
@ -168,7 +168,7 @@ class _CheckingInSetPageState extends State<CheckingInSetPage> {
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Expanded( Expanded(
child: TextField( child: TextField(
// //

View File

@ -6,28 +6,28 @@ import '../../../lockMian/entity/lockListInfo_entity.dart';
import 'checkingInSet_entity.dart'; import 'checkingInSet_entity.dart';
class CheckingInSetState{ class CheckingInSetState{
final getKeyInfosData = LockListInfoItemEntity().obs; CheckingInSetState() {
final companyId = "".obs; Map map = Get.arguments;
getKeyInfosData.value = map['getKeyInfosData'];
}
final Rx<LockListInfoItemEntity> getKeyInfosData = LockListInfoItemEntity().obs;
final RxString companyId = ''.obs;
var isCustom = false.obs; RxBool isCustom = false.obs;
var weekDays = <int>[].obs;// RxList<int> weekDays = <int>[].obs;//
var weekDaysStr = "".obs;// RxString weekDaysStr = ''.obs;//
var beginTime = "".obs;// RxString beginTime = ''.obs;//
var endTime = "".obs;// RxString endTime = ''.obs;//
var beginTimeTimestamp = "".obs;// RxString beginTimeTimestamp = ''.obs;//
var endTimeTimestamp = "".obs;// RxString endTimeTimestamp = ''.obs;//
var staffNumber = "".obs;// RxString staffNumber = ''.obs;//
var companyName = "".obs;// RxString companyName = ''.obs;//
final TextEditingController changeNameController = TextEditingController(); final TextEditingController changeNameController = TextEditingController();
final TextEditingController nameController = TextEditingController(); final TextEditingController nameController = TextEditingController();
final checkingInSetInfo = CheckingInSetInfo().obs; final Rx<CheckingInSetInfo> checkingInSetInfo = CheckingInSetInfo().obs;
CheckingInSetState() {
Map map = Get.arguments;
getKeyInfosData.value = map["getKeyInfosData"];
}
} }

View File

@ -1,9 +1,9 @@
import 'dart:async'; import 'dart:async';
import 'dart:ffi';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/app_settings/app_settings.dart'; import 'package:star_lock/login/login/entity/LoginEntity.dart';
import 'package:star_lock/main/lockDetail/passwordKey/passwordKey_perpetual/passwordKeyEntity.dart';
import 'package:star_lock/tools/baseGetXController.dart'; import 'package:star_lock/tools/baseGetXController.dart';
import '../../../../../network/api_repository.dart'; import '../../../../../network/api_repository.dart';
import '../../../../../tools/eventBusEventManage.dart'; import '../../../../../tools/eventBusEventManage.dart';
@ -23,30 +23,30 @@ class CheckingInAddStaffLogic extends BaseGetXController {
// eventBus // eventBus
_getNumberEvent = eventBus _getNumberEvent = eventBus
.on<ChickInAddStaffCardAndFingerprintBlockNumberEvent>() .on<ChickInAddStaffCardAndFingerprintBlockNumberEvent>()
.listen((event) { .listen((ChickInAddStaffCardAndFingerprintBlockNumberEvent event) {
state.attendanceWayNumber.value = event.number; state.attendanceWayNumber.value = event.number;
isCanClickAction(); isCanClickAction();
}); });
} }
// //
void addStaffLoadData() async { Future<void> addStaffLoadData() async {
var usernameType = "1"; String usernameType = '1';
if (state.appUnHaveAccount.value && state.staffAccount.contains("@")) { if (state.appUnHaveAccount.value && state.staffAccount.contains('@')) {
usernameType = "2"; usernameType = '2';
} }
// app且没有钥匙时attendanceWayNumber // app且没有钥匙时attendanceWayNumber
if (state.appUnHaveAccount.value && if (state.appUnHaveAccount.value &&
state.selectPrintingMethodType.value == "1") { state.selectPrintingMethodType.value == '1') {
state.attendanceWayNumber.value = state.staffAccountController.text; state.attendanceWayNumber.value = state.staffAccountController.text;
} }
var entity = await ApiRepository.to.addStaffData( final LoginEntity entity = await ApiRepository.to.addStaffData(
attendanceType: state.selectPrintingMethodType.value, attendanceType: state.selectPrintingMethodType.value,
attendanceWay: state.attendanceWayNumber.value, attendanceWay: state.attendanceWayNumber.value,
companyId: state.companyId.value, companyId: state.companyId.value,
have: state.appUnHaveAccount.value ? "2" : "1", have: state.appUnHaveAccount.value ? '2' : '1',
staffName: state.staffNameController.text, staffName: state.staffNameController.text,
countryCode: state.countryCode.value, countryCode: state.countryCode.value,
usernameType: usernameType, usernameType: usernameType,
@ -54,7 +54,7 @@ class CheckingInAddStaffLogic extends BaseGetXController {
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
eventBus.fire(RefreshCheckInSetDataEvent()); eventBus.fire(RefreshCheckInSetDataEvent());
eventBus.fire(RefreshCheckInListEvent()); eventBus.fire(RefreshCheckInListEvent());
Get.back(result: "addScuess"); Get.back(result: 'addScuess');
} else if (entity.errorCode! == 425) { } else if (entity.errorCode! == 425) {
showToast(entity.errorMsg!); showToast(entity.errorMsg!);
} }
@ -62,30 +62,35 @@ class CheckingInAddStaffLogic extends BaseGetXController {
// - 1APP234 // - 1APP234
// attendanceWay分别为用户名 // attendanceWay分别为用户名
void addStaffSelectKey(KeyClickCallback kyClickCallback) async { Future<void> addStaffSelectKey(KeyClickCallback kyClickCallback) async {
var entity = await ApiRepository.to.addStaffSelectKeyData( final CheckingInAddStaffSelectKeyEntity entity =
await ApiRepository.to.addStaffSelectKeyData(
companyId: state.companyId.value, companyId: state.companyId.value,
type: state.selectPrintingMethodType.value, type: state.selectPrintingMethodType.value,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
state.keyEntity.value = entity.data!; state.keyEntity.value = entity.data!;
kyClickCallback(state.keyEntity.value); kyClickCallback(state.keyEntity);
} }
} }
// //
void editStaffLoadData() async { Future<void> editStaffLoadData() async {
var usernameType = "1"; String usernameType = '1';
if (state.appUnHaveAccount.value && state.staffAccount.contains("@")) { if (state.appUnHaveAccount.value && state.staffAccount.contains('@')) {
usernameType = "2"; usernameType = '2';
}
// app且没有钥匙时attendanceWayNumber
if (state.appUnHaveAccount.value &&
state.selectPrintingMethodType.value == '1') {
state.attendanceWayNumber.value = state.staffAccountController.text;
} }
final LoginEntity entity = await ApiRepository.to.editStaffData(
var entity = await ApiRepository.to.editStaffData(
attendanceType: state.selectPrintingMethodType.value, attendanceType: state.selectPrintingMethodType.value,
attendanceWay: state.attendanceWayNumber.value, attendanceWay: state.attendanceWayNumber.value,
staffId: state.staffListItemData.value.staffId.toString(), staffId: state.staffListItemData.value.staffId.toString(),
have: state.appUnHaveAccount.value ? "2" : "1", have: state.appUnHaveAccount.value ? '2' : '1',
staffName: state.staffNameController.text, staffName: state.staffNameController.text,
countryCode: state.countryCode.value, countryCode: state.countryCode.value,
usernameType: usernameType, usernameType: usernameType,
@ -99,13 +104,13 @@ class CheckingInAddStaffLogic extends BaseGetXController {
} }
// //
void getKeyboardPwdRequest() async { Future<void> getKeyboardPwdRequest() async {
if (state.staffNameController.text.isEmpty) { if (state.staffNameController.text.isEmpty) {
showToast("请输入姓名"); showToast('请输入姓名');
return; return;
} }
var entity = await ApiRepository.to.getPasswordKey( final PasswordKeyEntity entity = await ApiRepository.to.getPasswordKey(
endDate: "0", endDate: '0',
keyboardPwdName: state.staffNameController.text, keyboardPwdName: state.staffNameController.text,
keyboardPwdType: 2.toString(), keyboardPwdType: 2.toString(),
lockId: state.getKeyInfosData.value.lockId.toString(), lockId: state.getKeyInfosData.value.lockId.toString(),
@ -136,7 +141,7 @@ class CheckingInAddStaffLogic extends BaseGetXController {
// //
void isCanClickAction() { void isCanClickAction() {
if (state.selectPrintingMethodType.value == "1" && if (state.selectPrintingMethodType.value == '1' &&
state.appUnHaveAccount.value) { state.appUnHaveAccount.value) {
// //
state.isCanClick.value = state.isCanClick.value =
@ -149,23 +154,15 @@ class CheckingInAddStaffLogic extends BaseGetXController {
@override @override
void onReady() { void onReady() {
// TODO: implement onReady
super.onReady(); super.onReady();
_initLoadDataAction(); _initLoadDataAction();
changeInput(state.staffNameController); changeInput(state.staffNameController);
} }
@override
void onInit() {
super.onInit();
}
@override @override
void onClose() { void onClose() {
// TODO: implement onClose
super.onClose(); super.onClose();
_getNumberEvent!.cancel(); _getNumberEvent!.cancel();
} }
} }

View File

@ -1,7 +1,11 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInStaff/checkingInSetAddStaff/checkingInAddStaffSelectKey_entity.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInStaff/checkingInSetAddStaff/checkingInAddStaff_state.dart';
import 'package:star_lock/tools/commonDataManage.dart';
import '../../../../../appRouters.dart'; import '../../../../../appRouters.dart';
import '../../../../../app_settings/app_colors.dart'; import '../../../../../app_settings/app_colors.dart';
@ -20,8 +24,9 @@ class CheckingInAddStaffPage extends StatefulWidget {
} }
class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> { class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
final logic = Get.put(CheckingInAddStaffLogic()); final CheckingInAddStaffLogic logic = Get.put(CheckingInAddStaffLogic());
final state = Get.find<CheckingInAddStaffLogic>().state; final CheckingInAddStaffState state =
Get.find<CheckingInAddStaffLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -33,15 +38,15 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor), backgroundColor: AppColors.mainColor),
body: Column( body: Column(
children: [ children: <Widget>[
// //
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.name!.tr, leftTitel: TranslationLoader.lanKeys!.name!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: getTFWidget( rightWidget: getTFWidget(
"${TranslationLoader.lanKeys!.pleaseEnter!.tr}${TranslationLoader.lanKeys!.name!.tr}", '${TranslationLoader.lanKeys!.pleaseEnter!.tr}${TranslationLoader.lanKeys!.name!.tr}',
state.staffNameController)), state.staffNameController)),
// //
Obx(() => CommonItem( Obx(() => CommonItem(
@ -50,35 +55,45 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
isHaveLine: false, isHaveLine: false,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
var list = ["APP", "密码".tr, "".tr, "指纹".tr]; final List<String> list = <String>[
if(state.getKeyInfosData.value.lockName!.contains("T9A")){ 'APP',
list.add("人脸".tr); '密码'.tr,
''.tr,
'指纹'.tr
];
// if (state.getKeyInfosData.value.lockName!.contains('T9A')) {
if (CommonDataManage().currentKeyInfo.lockFeature?.d3Face ==
1) {
list.add('人脸'.tr);
} }
_showSelectClockInType(list, list, "1", "选择钥匙".tr); _showSelectClockInType(list, list, list, '1', '选择钥匙'.tr);
})), })),
SizedBox(height: 10.h), SizedBox(height: 10.h),
//App //App
Obx(() => CommonItem( Obx(() => CommonItem(
leftTitel: addStaffGetIfHaveKey(), leftTitel: addStaffGetIfHaveKey(),
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: Row( rightWidget: Row(
children: [ children: <Widget>[
whetherTheEmployeeHasAKeyWidget("".tr, state.appUnHaveAccount.value, () { whetherTheEmployeeHasAKeyWidget(
''.tr, state.appUnHaveAccount.value, () {
setState(() { setState(() {
state.appUnHaveAccount.value = true; state.appUnHaveAccount.value = true;
state.attendanceWayNumber.value = ""; state.attendanceWayNumber.value = '';
logic.isCanClickAction(); logic.isCanClickAction();
}); });
}), }),
SizedBox( SizedBox(
width: 30.w, width: 30.w,
), ),
whetherTheEmployeeHasAKeyWidget("".tr, !state.appUnHaveAccount.value, () { whetherTheEmployeeHasAKeyWidget(
''.tr, !state.appUnHaveAccount.value, () {
setState(() { setState(() {
state.appUnHaveAccount.value = false; state.appUnHaveAccount.value = false;
state.attendanceWayNumber.value = ""; state.attendanceWayNumber.value = '';
logic.isCanClickAction(); logic.isCanClickAction();
}); });
}), }),
@ -86,12 +101,13 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
))), ))),
// App时且没有钥匙的时候 // App时且没有钥匙的时候
Obx(() => Visibility( Obx(() => Visibility(
visible: (state.appUnHaveAccount.value && state.selectPrintingMethodType.value == "1") ? true : false, visible: state.appUnHaveAccount.value &&
state.selectPrintingMethodType.value == '1',
child: Column( child: Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: TranslationLoader.lanKeys!.accountNumber!.tr, leftTitel: TranslationLoader.lanKeys!.accountNumber!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: getTFWidget( rightWidget: getTFWidget(
@ -100,7 +116,7 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
CommonItem( CommonItem(
leftTitel: leftTitel:
TranslationLoader.lanKeys!.countryAndRegion!.tr, TranslationLoader.lanKeys!.countryAndRegion!.tr,
rightTitle: "", rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: true, isHaveRightWidget: true,
isHaveDirection: true, isHaveDirection: true,
@ -112,7 +128,7 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
color: AppColors.darkGrayTextColor), color: AppColors.darkGrayTextColor),
), ),
action: () async { action: () async {
var result = await Navigator.pushNamed( final Object? result = await Navigator.pushNamed(
context, Routers.selectCountryRegionPage); context, Routers.selectCountryRegionPage);
if (result != null) { if (result != null) {
result as Map<String, dynamic>; result as Map<String, dynamic>;
@ -127,77 +143,88 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
)), )),
// //
Obx(() => Visibility( Obx(() => Visibility(
visible: (state.selectPrintingMethodType.value != "1" && state.appUnHaveAccount.value) ? true : false, visible: state.selectPrintingMethodType.value != '1' &&
state.appUnHaveAccount.value,
child: CommonItem( child: CommonItem(
leftTitel: addStaffGetKeyType(), leftTitel: addStaffGetKeyType(),
isHaveLine: false, isHaveLine: false,
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: Row( rightWidget: Row(
children: [ children: <Widget>[
Obx(() => Text(state.attendanceWayNumber.value, style: TextStyle(fontSize: 24.sp))), Obx(() => Text(state.attendanceWayNumber.value,
style: TextStyle(fontSize: 24.sp))),
SizedBox(width: 30.w), SizedBox(width: 30.w),
GestureDetector( GestureDetector(
onTap: () async { onTap: () async {
switch (int.parse(state.selectPrintingMethodType.value)) { switch (int.parse(
state.selectPrintingMethodType.value)) {
case 2: case 2:
// //
logic.getKeyboardPwdRequest(); logic.getKeyboardPwdRequest();
break; break;
case 3: case 3:
// //
if (state.staffNameController.text.isEmpty) { if (state.staffNameController.text.isEmpty) {
logic.showToast("请输入姓名".tr); logic.showToast('请输入姓名'.tr);
return; return;
} }
var data = await Get.toNamed( final dynamic data = await Get.toNamed(
Routers.addCardPage, Routers.addCardPage,
arguments: { arguments: <String, Object?>{
"lockId": state.getKeyInfosData.value.lockId, 'lockId':
"fromType": 2, // 1 2 state.getKeyInfosData.value.lockId,
"fromTypeTwoStaffName": state.staffNameController.text 'fromType': 2, // 1 2
'fromTypeTwoStaffName':
state.staffNameController.text
}); });
if (data != null) { if (data != null) {}
}
break; break;
case 4: case 4:
// //
if (state.staffNameController.text.isEmpty) { if (state.staffNameController.text.isEmpty) {
logic.showToast("请输入姓名".tr); logic.showToast('请输入姓名'.tr);
return; return;
} }
var data = await Get.toNamed( final data = await Get.toNamed(
Routers.addFingerprintTypePage, Routers.addFingerprintTypePage,
arguments: { arguments: <String, Object?>{
"lockId": state.getKeyInfosData.value.lockId, 'lockId':
"fromType": 2, // 1 2 state.getKeyInfosData.value.lockId,
"fromTypeTwoStaffName": state.staffNameController.text 'fromType': 2, // 1 2
'fromTypeTwoStaffName':
state.staffNameController.text
}); });
if (data != null) { if (data != null) {}
}
break; break;
case 5: case 5:
Get.toNamed(Routers.addFaceTypePage, arguments: { Get.toNamed(Routers.addFaceTypePage,
"lockId": state.getKeyInfosData.value.lockId, arguments: <String, Object?>{
"fromType": 2, // 1 2 'lockId':
"fromTypeTwoStaffName": state.staffNameController.text state.getKeyInfosData.value.lockId,
}); 'fromType': 2, // 1 2
'fromTypeTwoStaffName':
state.staffNameController.text
});
break; break;
} }
}, },
child: Container( child: Container(
height: 40.h, height: 40.h,
padding: EdgeInsets.only(left: 25.w, right: 25.w, top: 2.h), padding: EdgeInsets.only(
left: 25.w,
right: 25.w,
),
decoration: BoxDecoration( decoration: BoxDecoration(
color: AppColors.mainColor, color: AppColors.mainColor,
borderRadius: BorderRadius.circular(20.h), borderRadius: BorderRadius.circular(20.h),
), ),
child: Text(addStaffSelectKeyType(), textAlign: TextAlign.center, child: Center(
style: TextStyle(color: Colors.white, fontSize: 22.sp) child: Text(addStaffSelectKeyType(),
style: TextStyle(
color: Colors.white, fontSize: 22.sp)),
), ),
), ),
), ),
@ -205,25 +232,49 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
)), )),
)), )),
// //
Obx(() => Visibility( Obx(() {
visible: !state.appUnHaveAccount.value, final bool isPass = state.selectPrintingMethodType.value == '2';
child: CommonItem( String attendanceWayNumber = state.attendanceWayNumber.value;
leftTitel: addStaffGetKeyType(), final String attendanceWayName = state.attendanceWayName.value;
rightTitle: state.attendanceWayNumber.value, if (isPass) {
isHaveLine: false, attendanceWayNumber = showPass(attendanceWayNumber);
isHaveDirection: true, }
action: () { String rightTitle = attendanceWayNumber;
logic.addStaffSelectKey((v) { if (attendanceWayName.trim() != '') {
var showList = []; rightTitle = '$attendanceWayName - ' + rightTitle;
List numberList = []; }
for (var element in v) { return Visibility(
showList.add("${element.staffName}-${element.attendanceWay}"); visible: !state.appUnHaveAccount.value,
numberList.add(element.attendanceWay); child: CommonItem(
leftTitel: addStaffGetKeyType(),
rightTitle: rightTitle,
isHaveLine: false,
isHaveDirection: true,
action: () {
logic.addStaffSelectKey(
(List<CheckingInAddStaffKeyEntity> v) {
final List<String> showList = <String>[];
final List<String> nameList = <String>[];
final List<String> numberList = <String>[];
for (final CheckingInAddStaffKeyEntity element in v) {
final bool isPass =
state.selectPrintingMethodType.value == '2';
String attendanceWay = element.attendanceWay ?? '';
if (isPass) {
attendanceWay = showPass(attendanceWay);
} }
_showSelectClockInType(showList, numberList, "2", addStaffSelectKeySelectClockInType()); final String text =
}); '${element.staffName} - $attendanceWay';
}), showList.add(text);
)), numberList.add(element.attendanceWay ?? '');
nameList.add(element.staffName ?? '');
}
_showSelectClockInType(showList, numberList, nameList,
'2', addStaffSelectKeySelectClockInType());
});
}),
);
}),
SizedBox(height: 50.w), SizedBox(height: 50.w),
Obx(() => SubmitBtn( Obx(() => SubmitBtn(
btnName: TranslationLoader.lanKeys!.sure!.tr, btnName: TranslationLoader.lanKeys!.sure!.tr,
@ -231,25 +282,38 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 30.w), margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 30.w),
padding: EdgeInsets.only(top: 25.w, bottom: 25.w), padding: EdgeInsets.only(top: 25.w, bottom: 25.w),
isDisabled: state.isCanClick.value, isDisabled: state.isCanClick.value,
onClick: state.isCanClick.value ? (){ onClick: state.isCanClick.value
if (state.isAdd.value == "2") { ? () {
logic.editStaffLoadData(); if (state.isAdd.value == '2') {
} else { logic.editStaffLoadData();
logic.addStaffLoadData(); } else {
} logic.addStaffLoadData();
}: null)) }
}
: null))
], ],
), ),
); );
} }
//
String showPass(String text) {
final int length = text.length;
if (length > 4) {
return text.substring(0, length - 4) + '****';
} else if (length > 00) {
return '****';
}
return '';
}
Widget getTFWidget(String tfStr, TextEditingController tf) { Widget getTFWidget(String tfStr, TextEditingController tf) {
return SizedBox( return SizedBox(
// height: 50.h, // height: 50.h,
width: 300.w, width: 300.w,
// color: Colors.red, // color: Colors.red,
child: Row( child: Row(
children: [ children: <Widget>[
Expanded( Expanded(
child: TextField( child: TextField(
// //
@ -258,11 +322,12 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
FilteringTextInputFormatter.deny('\n'), FilteringTextInputFormatter.deny('\n'),
// LengthLimitingTextInputFormatter(30), // LengthLimitingTextInputFormatter(30),
], ],
style: TextStyle(fontSize: 22.sp, color: AppColors.darkGrayTextColor), style: TextStyle(
fontSize: 22.sp, color: AppColors.darkGrayTextColor),
controller: tf, controller: tf,
autofocus: false, autofocus: false,
textAlign: TextAlign.end, textAlign: TextAlign.end,
onChanged: (v) { onChanged: (String v) {
logic.changeInput(tf); logic.changeInput(tf);
}, },
decoration: InputDecoration( decoration: InputDecoration(
@ -270,10 +335,18 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
// contentPadding: const EdgeInsets.only(top: 12.0, bottom: 8.0), // contentPadding: const EdgeInsets.only(top: 12.0, bottom: 8.0),
hintText: tfStr, hintText: tfStr,
hintStyle: TextStyle(fontSize: 22.sp), hintStyle: TextStyle(fontSize: 22.sp),
focusedBorder: const OutlineInputBorder(borderSide: BorderSide(width: 0, color: Colors.transparent)), focusedBorder: const OutlineInputBorder(
disabledBorder: const OutlineInputBorder(borderSide: BorderSide(width: 0, color: Colors.transparent)), borderSide:
enabledBorder: const OutlineInputBorder(borderSide: BorderSide(width: 0, color: Colors.transparent)), BorderSide(width: 0, color: Colors.transparent)),
border: const OutlineInputBorder(borderSide: BorderSide(width: 0, color: Colors.transparent)), disabledBorder: const OutlineInputBorder(
borderSide:
BorderSide(width: 0, color: Colors.transparent)),
enabledBorder: const OutlineInputBorder(
borderSide:
BorderSide(width: 0, color: Colors.transparent)),
border: const OutlineInputBorder(
borderSide:
BorderSide(width: 0, color: Colors.transparent)),
contentPadding: const EdgeInsets.symmetric(vertical: 0), contentPadding: const EdgeInsets.symmetric(vertical: 0),
), ),
), ),
@ -284,7 +357,8 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
} }
// type 1 2 // type 1 2
void _showSelectClockInType(List showList, List numberList, String showBottomSheetToolType, String title) { void _showSelectClockInType(List<String> showList, List<String> numberList,
List<String> nameList, String showBottomSheetToolType, String title) {
ShowBottomSheetTool().showSingleRowPicker( ShowBottomSheetTool().showSingleRowPicker(
// //
context, context,
@ -298,13 +372,15 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
//adapter: PickerAdapter(), //adapter: PickerAdapter(),
data: showList, data: showList,
// //
clickCallBack: (int index, var str) { clickCallBack: (int index, Object str) {
setState(() { setState(() {
if (showBottomSheetToolType == "1") { if (showBottomSheetToolType == '1') {
state.selectPrintingMethodType.value = (index + 1).toString(); state.selectPrintingMethodType.value = (index + 1).toString();
state.selectPrintingMethodStr.value = str.toString(); state.selectPrintingMethodStr.value = str.toString();
state.attendanceWayNumber.value = ""; state.attendanceWayName.value = '';
state.attendanceWayNumber.value = '';
} else { } else {
state.attendanceWayName.value = nameList[index].toString();
state.attendanceWayNumber.value = numberList[index].toString(); state.attendanceWayNumber.value = numberList[index].toString();
} }
logic.isCanClickAction(); logic.isCanClickAction();
@ -312,16 +388,17 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
}); });
} }
Widget whetherTheEmployeeHasAKeyWidget(String title, bool appUnHaveAccount, Function() action) { Widget whetherTheEmployeeHasAKeyWidget(
String title, bool appUnHaveAccount, Function() action) {
return GestureDetector( return GestureDetector(
onTap: action, onTap: action,
child: Container( child: Container(
// width: 80.w, // width: 80.w,
height: 65.w, height: 65.w,
padding: EdgeInsets.only(left:10.w, right: 10.w), padding: EdgeInsets.only(left: 10.w, right: 10.w),
// color: Colors.red, // color: Colors.red,
child: Row( child: Row(
children: [ children: <Widget>[
Image.asset( Image.asset(
appUnHaveAccount appUnHaveAccount
? 'images/icon_round_select.png' ? 'images/icon_round_select.png'
@ -345,7 +422,7 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
} }
String addStaffGetIfHaveKey() { String addStaffGetIfHaveKey() {
String title = ""; String title = '';
switch (int.parse(state.selectPrintingMethodType.value)) { switch (int.parse(state.selectPrintingMethodType.value)) {
case 1: case 1:
title = TranslationLoader.lanKeys!.whetherTheEmployeeHasAKey!.tr; title = TranslationLoader.lanKeys!.whetherTheEmployeeHasAKey!.tr;
@ -360,14 +437,14 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
title = TranslationLoader.lanKeys!.whetherTheEmployeeHasFingerprint!.tr; title = TranslationLoader.lanKeys!.whetherTheEmployeeHasFingerprint!.tr;
break; break;
case 4: case 4:
title = "员工是否有人脸".tr; title = '员工是否有人脸'.tr;
break; break;
} }
return title; return title;
} }
String addStaffGetKeyType() { String addStaffGetKeyType() {
String title = ""; String title = '';
switch (int.parse(state.selectPrintingMethodType.value)) { switch (int.parse(state.selectPrintingMethodType.value)) {
case 1: case 1:
title = TranslationLoader.lanKeys!.accountNumber!.tr; title = TranslationLoader.lanKeys!.accountNumber!.tr;
@ -389,7 +466,7 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
} }
String addStaffSelectKeyType() { String addStaffSelectKeyType() {
String title = ""; String title = '';
switch (int.parse(state.selectPrintingMethodType.value)) { switch (int.parse(state.selectPrintingMethodType.value)) {
case 1: case 1:
title = TranslationLoader.lanKeys!.getKey!.tr; title = TranslationLoader.lanKeys!.getKey!.tr;
@ -404,32 +481,31 @@ class _CheckingInAddStaffPageState extends State<CheckingInAddStaffPage> {
title = TranslationLoader.lanKeys!.getFingerprint!.tr; title = TranslationLoader.lanKeys!.getFingerprint!.tr;
break; break;
case 5: case 5:
title = "获取人脸".tr; title = '获取人脸'.tr;
break; break;
} }
return title; return title;
} }
String addStaffSelectKeySelectClockInType() { String addStaffSelectKeySelectClockInType() {
String title = ""; String title = '';
switch (int.parse(state.selectPrintingMethodType.value)) { switch (int.parse(state.selectPrintingMethodType.value)) {
case 1: case 1:
title = "选择钥匙".tr; title = '选择钥匙'.tr;
break; break;
case 2: case 2:
title = "选择密码".tr; title = '选择密码'.tr;
break; break;
case 3: case 3:
title = "选择卡".tr; title = '选择卡'.tr;
break; break;
case 4: case 4:
title = "选择指纹".tr; title = '选择指纹'.tr;
break; break;
case 5: case 5:
title = "选择人脸".tr; title = '选择人脸'.tr;
break; break;
} }
return title; return title;
} }
} }

View File

@ -6,59 +6,34 @@ import '../checkingInSetStaffList/checkingInStaffList_entity.dart';
import 'checkingInAddStaffSelectKey_entity.dart'; import 'checkingInAddStaffSelectKey_entity.dart';
class CheckingInAddStaffState { class CheckingInAddStaffState {
final getKeyInfosData = LockListInfoItemEntity().obs;
final companyId = "".obs;
final staffListItemData = CheckingInAddStaffListItemEntity().obs;
final TextEditingController staffNameController = TextEditingController();
final TextEditingController staffAccountController = TextEditingController();
final selectPrintingMethodType = "1".obs; // 1APP 2 3 4 5
final selectPrintingMethodStr = "APP".obs; //
final countryName = "中国".tr.obs;
final countryCode = "86".obs;
final appUnHaveAccount = true.obs; //
final keyEntity = <CheckingInAddStaffKeyEntity>[].obs; //
final isAdd = "1".obs; // 1 2
final attendanceWayNumber = "".obs;
final isCanClick = false.obs;
var staffName = ''.obs;
var staffAccount = ''.obs;
bool get staffNameIsNotEmpty => staffName.value.isNotEmpty;
bool get staffAccountIsNotEmpty => staffAccount.value.isNotEmpty;
bool get attendanceWayNumberIsNotEmpty =>
attendanceWayNumber.value.isNotEmpty;
CheckingInAddStaffState() { CheckingInAddStaffState() {
Map map = Get.arguments; final Map<dynamic, dynamic> map = Get.arguments;
getKeyInfosData.value = map["getKeyInfosData"]; getKeyInfosData.value = map['getKeyInfosData'];
companyId.value = map["companyId"]; companyId.value = map['companyId'];
isAdd.value = map["isAdd"]; isAdd.value = map['isAdd'];
if (isAdd.value == "2") { if (isAdd.value == '2') {
staffListItemData.value = map["staffListItem"]; staffListItemData.value = map['staffListItem'];
staffNameController.text = staffListItemData.value.staffName!; staffNameController.text = staffListItemData.value.staffName!;
selectPrintingMethodType.value = selectPrintingMethodType.value =
staffListItemData.value.attendanceType.toString(); staffListItemData.value.attendanceType.toString();
switch (staffListItemData.value.attendanceType) { switch (staffListItemData.value.attendanceType) {
case 1: case 1:
selectPrintingMethodStr.value = "APP"; selectPrintingMethodStr.value = 'APP';
break; break;
case 2: case 2:
selectPrintingMethodStr.value = "密码".tr; selectPrintingMethodStr.value = '密码'.tr;
break; break;
case 3: case 3:
selectPrintingMethodStr.value = "".tr; selectPrintingMethodStr.value = ''.tr;
break; break;
case 4: case 4:
selectPrintingMethodStr.value = "指纹".tr; selectPrintingMethodStr.value = '指纹'.tr;
break;
case 5:
selectPrintingMethodStr.value = '人脸'.tr;
break; break;
} }
@ -70,4 +45,37 @@ class CheckingInAddStaffState {
} }
} }
} }
final Rx<LockListInfoItemEntity> getKeyInfosData =
LockListInfoItemEntity().obs;
final RxString companyId = ''.obs;
final Rx<CheckingInAddStaffListItemEntity> staffListItemData =
CheckingInAddStaffListItemEntity().obs;
final TextEditingController staffNameController = TextEditingController();
final TextEditingController staffAccountController = TextEditingController();
final RxString selectPrintingMethodType =
'1'.obs; // 1APP 2 3 4 5
final RxString selectPrintingMethodStr = 'APP'.obs; //
final RxString countryName = '中国'.tr.obs;
final RxString countryCode = '86'.obs;
final RxBool appUnHaveAccount = true.obs; //
final RxList<CheckingInAddStaffKeyEntity> keyEntity =
<CheckingInAddStaffKeyEntity>[].obs; //
final RxString isAdd = '1'.obs; // 1 2
final RxString attendanceWayName = ''.obs;
final RxString attendanceWayNumber = ''.obs;
final RxBool isCanClick = false.obs;
RxString staffName = ''.obs;
RxString staffAccount = ''.obs;
bool get staffNameIsNotEmpty => staffName.value.isNotEmpty;
bool get staffAccountIsNotEmpty => staffAccount.value.isNotEmpty;
bool get attendanceWayNumberIsNotEmpty =>
attendanceWayNumber.value.isNotEmpty;
} }

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/checkingIn/checkingInStaff/checkingInSetStaffList/checkingInStaffList_state.dart';
import 'package:star_lock/tools/showTipView.dart'; import 'package:star_lock/tools/showTipView.dart';
import '../../../../../appRouters.dart'; import '../../../../../appRouters.dart';
@ -23,8 +24,10 @@ class CheckingInStaffListPage extends StatefulWidget {
} }
class _CheckingInStaffListPageState extends State<CheckingInStaffListPage> { class _CheckingInStaffListPageState extends State<CheckingInStaffListPage> {
final logic = Get.put(CheckingInStaffManageLogic()); final CheckingInStaffManageLogic logic =
final state = Get.find<CheckingInStaffManageLogic>().state; Get.put(CheckingInStaffManageLogic());
final CheckingInStaffManageState state =
Get.find<CheckingInStaffManageLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -34,15 +37,17 @@ class _CheckingInStaffListPageState extends State<CheckingInStaffListPage> {
barTitle: TranslationLoader.lanKeys!.staff!.tr, barTitle: TranslationLoader.lanKeys!.staff!.tr,
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor, backgroundColor: AppColors.mainColor,
actionsList: [ actionsList: <Widget>[
GestureDetector( GestureDetector(
onTap: () async { onTap: () async {
var data = await Get.toNamed(Routers.checkingInAddStaffPage, arguments: { final dynamic data = await Get.toNamed(
"getKeyInfosData": state.getKeyInfosData.value, Routers.checkingInAddStaffPage,
"companyId": state.companyId.value, arguments: <String, Object>{
"isAdd": "1", 'getKeyInfosData': state.getKeyInfosData.value,
}); 'companyId': state.companyId.value,
if(data != null) { 'isAdd': '1',
});
if (data != null) {
logic.getStaffList(); logic.getStaffList();
} }
}, },
@ -58,65 +63,76 @@ class _CheckingInStaffListPageState extends State<CheckingInStaffListPage> {
), ),
body: Container( body: Container(
color: Colors.white, color: Colors.white,
child: Obx(() => state.staffListData.value.isNotEmpty ? child: Obx(() => state.staffListData.isNotEmpty
SlidableAutoCloseBehavior( ? SlidableAutoCloseBehavior(
child: ListView.separated( child: ListView.separated(
itemCount: state.staffListData.value.length, itemCount: state.staffListData.length,
itemBuilder: (c, index) { itemBuilder: (BuildContext c, int index) {
CheckingInAddStaffListItemEntity staffListItem = state.staffListData[index]; final CheckingInAddStaffListItemEntity staffListItem =
return Slidable( state.staffListData[index];
key:ValueKey(staffListItem.staffId), return Slidable(
endActionPane: ActionPane( key: ValueKey<int?>(staffListItem.staffId),
extentRatio: 0.2, endActionPane: ActionPane(
motion: const ScrollMotion(), extentRatio: 0.2,
children: [ motion: const ScrollMotion(),
SlidableAction( children: <Widget>[
onPressed: (BuildContext context){ SlidableAction(
// 1APP 2 3 4 5 onPressed: (BuildContext context) {
if(staffListItem.attendanceType == 1){ // 1APP 2 3 4 5
ShowTipView().showDeleteAdministratorIsHaveAllDataDialog('同时删除员工钥匙'.tr, (isAllData) { if (staffListItem.attendanceType == 1) {
logic.deletStaff(staffListItem.staffId!, (isAllData ? 1 : 0)); ShowTipView()
}); .showDeleteAdministratorIsHaveAllDataDialog(
}else{ '同时删除员工钥匙'.tr, (bool isAllData) {
ShowTipView().showIosTipWithContentDialog("确定要删除员工吗?".tr, () { logic.deletStaff(staffListItem.staffId!,
logic.deletStaff(staffListItem.staffId!, 0); (isAllData ? 1 : 0));
}); });
// showIosTipViewDialog(staffListItem.staffId!, context); } else {
} ShowTipView().showIosTipWithContentDialog(
}, '确定要删除员工吗?'.tr, () {
backgroundColor: Colors.red, logic.deletStaff(staffListItem.staffId!, 0);
foregroundColor: Colors.white, });
label: '删除'.tr, // showIosTipViewDialog(staffListItem.staffId!, context);
padding: EdgeInsets.only(left: 5.w, right: 5.w), }
), },
], backgroundColor: Colors.red,
foregroundColor: Colors.white,
label: '删除'.tr,
padding: EdgeInsets.only(left: 5.w, right: 5.w),
),
],
),
child: _checkingInStaffManageItem(staffListItem, () {
Get.toNamed(Routers.checkingInStaffDetailPage,
arguments: <String, Object>{
'staffListItem': staffListItem,
'getKeyInfosData': state.getKeyInfosData.value,
'companyId': state.companyId.value,
});
}),
);
// return _checkingInStaffManageItem(staffListItem, () {
// Get.toNamed(Routers.checkingInStaffDetailPage, arguments: {
// "staffListItem": staffListItem,
// "getKeyInfosData": state.getKeyInfosData.value,
// "companyId": state.companyId.value,
// });
// });
},
separatorBuilder: (BuildContext context, int index) {
return Divider(
height: 1.h,
indent: 20.w,
color: AppColors.greyLineColor);
},
), ),
child: _checkingInStaffManageItem(staffListItem, () { )
Get.toNamed(Routers.checkingInStaffDetailPage, arguments: { : NoData()),
"staffListItem": staffListItem,
"getKeyInfosData": state.getKeyInfosData.value,
"companyId": state.companyId.value,
});
}),
);
// return _checkingInStaffManageItem(staffListItem, () {
// Get.toNamed(Routers.checkingInStaffDetailPage, arguments: {
// "staffListItem": staffListItem,
// "getKeyInfosData": state.getKeyInfosData.value,
// "companyId": state.companyId.value,
// });
// });
},
separatorBuilder: (context, index) {
return Divider(height: 1.h, indent: 20.w, color: AppColors.greyLineColor);
},
),
) : NoData()),
)); ));
} }
Widget _checkingInStaffManageItem(CheckingInAddStaffListItemEntity staffListItem, Function() action) { Widget _checkingInStaffManageItem(
CheckingInAddStaffListItemEntity staffListItem, Function() action) {
return GestureDetector( return GestureDetector(
onTap: action, onTap: action,
child: Container( child: Container(
@ -125,35 +141,53 @@ class _CheckingInStaffListPageState extends State<CheckingInStaffListPage> {
color: Colors.white, color: Colors.white,
margin: EdgeInsets.only(right: 10.w, top: 10.h, bottom: 10.h), margin: EdgeInsets.only(right: 10.w, top: 10.h, bottom: 10.h),
child: Row( child: Row(
children: [ children: <Widget>[
SizedBox(width: 20.w,), SizedBox(
// CustomNetworkImage(url: staffListItem.headurl!, width: 40.w , height: 40.w), width: 20.w,
Image.asset(getTypeIcon(staffListItem.attendanceType!), width: 60.w, height: 60.w), ),
SizedBox(width: 20.w,), if (staffListItem.headurl == null || staffListItem.headurl == '')
Image.asset(
getTypeIcon(staffListItem.attendanceType!),
width: 60.w,
height: 60.w,
)
else
ClipRRect(
borderRadius: BorderRadius.circular(100.w),
child: Image.network(
staffListItem.headurl!,
width: 60.w,
height: 60.w,
),
),
SizedBox(
width: 20.w,
),
Column( Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: <Widget>[
SizedBox( SizedBox(
width: 1.sw - 20.w - 60.w - 20.w - 30.w, width: 1.sw - 20.w - 60.w - 20.w - 30.w,
child: Text(staffListItem.staffName!, child: Text(staffListItem.staffName!,
// maxLines: 1, // maxLines: 1,
// overflow: TextOverflow.ellipsis, // overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 24.sp) style: TextStyle(fontSize: 24.sp))),
)
),
Visibility( Visibility(
visible: staffListItem.cardStatus == 1 ? true : false, visible: staffListItem.cardStatus == 1,
child: SizedBox(height: 5.h,) child: SizedBox(
), height: 5.h,
)),
Visibility( Visibility(
visible: staffListItem.cardStatus == 1 ? true : false, visible: staffListItem.cardStatus == 1,
child: Container( child: Container(
padding: EdgeInsets.only(right: 5.w, left: 5.w), padding: EdgeInsets.only(right: 5.w, left: 5.w),
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.w), borderRadius: BorderRadius.circular(5.w),
color: AppColors.openPassageModeColor, color: AppColors.openPassageModeColor,
), ),
child: Text("打卡方式无效".tr, style: TextStyle(fontSize: 18.sp, color: AppColors.appBarIconColor)), child: Text('打卡方式无效'.tr,
style: TextStyle(
fontSize: 18.sp, color: AppColors.appBarIconColor)),
), ),
), ),
], ],
@ -169,19 +203,19 @@ class _CheckingInStaffListPageState extends State<CheckingInStaffListPage> {
String title = 'images/controls_user.png'; String title = 'images/controls_user.png';
switch (type) { switch (type) {
case 1: case 1:
// //
title = 'images/controls_user.png'; title = 'images/controls_user.png';
break; break;
case 2: case 2:
// //
title = 'images/icon_password.png'; title = 'images/icon_password.png';
break; break;
case 3: case 3:
// ic卡 // ic卡
title = 'images/icon_card.png'; title = 'images/icon_card.png';
break; break;
case 4: case 4:
// //
title = 'images/icon_fingerprint.png'; title = 'images/icon_fingerprint.png';
break; break;
default: default:
@ -190,23 +224,22 @@ class _CheckingInStaffListPageState extends State<CheckingInStaffListPage> {
return title; return title;
} }
// void showIosTipViewDialog(int staffId, BuildContext context) { // void showIosTipViewDialog(int staffId, BuildContext context) {
// showDialog( // showDialog(
// context: context, // context: context,
// builder: (BuildContext context) { // builder: (BuildContext context) {
// return ShowIosTipView( // return ShowIosTipView(
// title: "提示", // title: "提示",
// tipTitle: "确定要删除员工吗?", // tipTitle: "确定要删除员工吗?",
// sureClick: () async { // sureClick: () async {
// Get.back(); // Get.back();
// logic.deletStaff(staffId, 0); // logic.deletStaff(staffId, 0);
// }, // },
// cancelClick: () { // cancelClick: () {
// Get.back(); // Get.back();
// }, // },
// ); // );
// }, // },
// ); // );
// } // }
} }

View File

@ -106,7 +106,7 @@ class DoorLockLogLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState connectionStateState) async { (BluetoothConnectionState connectionStateState) async {
if (connectionStateState == BluetoothConnectionState.connected) { if (connectionStateState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);

View File

@ -25,17 +25,17 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
// //
Future<void> modifyKeyNameRequest() async { Future<void> modifyKeyNameRequest() async {
if (state.changeNameController.text.isEmpty) { if (state.changeNameController.text.isEmpty) {
showToast("请输入钥匙名称".tr); showToast('请输入钥匙名称'.tr);
return; return;
} }
KeyOperationRecordEntity entity = await ApiRepository.to final KeyOperationRecordEntity entity = await ApiRepository.to
.modifyKeyNameForAdmin(state.itemData.value.keyId.toString(), .modifyKeyNameForAdmin(state.itemData.value.keyId.toString(),
state.changeNameController.text, ''); state.changeNameController.text, '');
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
state.itemData.value.keyName = state.changeNameController.text; state.itemData.value.keyName = state.changeNameController.text;
state.keyName.value = state.itemData.value.keyName!; state.keyName.value = state.itemData.value.keyName!;
Get.back(); Get.back();
showToast("修改成功".tr, something: () { showToast('修改成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
}); });
@ -44,19 +44,21 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
// updateType 1: 2: // updateType 1: 2:
Future<void> updateKeyDateRequest(int updateType) async { Future<void> updateKeyDateRequest(int updateType) async {
KeyOperationRecordEntity entity = await ApiRepository.to.updateKeyDate( final KeyOperationRecordEntity entity = await ApiRepository.to
keyId: state.itemData.value.keyId.toString(), .updateKeyDate(
lockId: state.itemData.value.lockId.toString(), keyId: state.itemData.value.keyId.toString(),
endDate: state.endDate.value.toString(), lockId: state.itemData.value.lockId.toString(),
startDate: state.starDate.value.toString(), endDate: state.endDate.value.toString(),
weekDays: state.itemData.value.weekDays!, startDate: state.starDate.value.toString(),
keyType: state.itemData.value.keyType!, weekDays: state.itemData.value.weekDays!,
startTime: int.parse(state.starTime.value), keyType: state.itemData.value.keyType!,
endTime: int.parse(state.endTime.value), startTime: int.parse(state.starTime.value),
isOnlyManageSelf: state.onlyManageYouCreatesUser.value == true ? 1 : 0, endTime: int.parse(state.endTime.value),
remoteEnable: state.isRemoteUnlock.value == true ? 1 : 2); isOnlyManageSelf:
state.onlyManageYouCreatesUser.value == true ? 1 : 0,
remoteEnable: state.isRemoteUnlock.value == true ? 1 : 2);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
showToast("修改成功".tr, something: () { showToast('修改成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
}); });
@ -65,11 +67,12 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
// //
Future<void> deleteKeyRequest(int includeUnderlings) async { Future<void> deleteKeyRequest(int includeUnderlings) async {
ElectronicKeyListEntity entity = await ApiRepository.to.deleteElectronicKey( final ElectronicKeyListEntity entity = await ApiRepository.to
keyId: state.itemData.value.keyId.toString(), .deleteElectronicKey(
includeUnderlings: includeUnderlings); keyId: state.itemData.value.keyId.toString(),
includeUnderlings: includeUnderlings);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
showToast("删除成功".tr, something: () { showToast('删除成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
Get.back(); Get.back();
@ -79,11 +82,12 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
// //
Future<void> setAdministrator() async { Future<void> setAdministrator() async {
ElectronicKeyListEntity entity = await ApiRepository.to.setAdministrator( final ElectronicKeyListEntity entity =
await ApiRepository.to.setAdministrator(
keyId: state.itemData.value.keyId.toString(), keyId: state.itemData.value.keyId.toString(),
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
showToast("设置成功".tr, something: () { showToast('设置成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
Get.back(); Get.back();
@ -93,11 +97,12 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
// //
Future<void> cancelAdministrator() async { Future<void> cancelAdministrator() async {
ElectronicKeyListEntity entity = await ApiRepository.to.cancelAdministrator( final ElectronicKeyListEntity entity =
await ApiRepository.to.cancelAdministrator(
keyId: state.itemData.value.keyId.toString(), keyId: state.itemData.value.keyId.toString(),
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
showToast("设置成功".tr, something: () { showToast('设置成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
Get.back(); Get.back();
@ -107,11 +112,11 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
// //
Future<void> freezeKey(int includeUnderlings) async { Future<void> freezeKey(int includeUnderlings) async {
ElectronicKeyListEntity entity = await ApiRepository.to.freezeKey( final ElectronicKeyListEntity entity = await ApiRepository.to.freezeKey(
keyId: state.itemData.value.keyId.toString(), keyId: state.itemData.value.keyId.toString(),
includeUnderlings: includeUnderlings); includeUnderlings: includeUnderlings);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
showToast("设置成功".tr, something: () { showToast('设置成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
Get.back(); Get.back();
@ -121,11 +126,11 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
// //
Future<void> cancelFreeze(int includeUnderlings) async { Future<void> cancelFreeze(int includeUnderlings) async {
ElectronicKeyListEntity entity = await ApiRepository.to.cancelFreeze( final ElectronicKeyListEntity entity = await ApiRepository.to.cancelFreeze(
keyId: state.itemData.value.keyId.toString(), keyId: state.itemData.value.keyId.toString(),
includeUnderlings: includeUnderlings); includeUnderlings: includeUnderlings);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
showToast("设置成功".tr, something: () { showToast('设置成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
Get.back(); Get.back();
@ -137,14 +142,15 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
Future<void> checkRealNameStatus(int realNameAuthStatus) async { Future<void> checkRealNameStatus(int realNameAuthStatus) async {
// //
if (realNameAuthStatus == 1) { if (realNameAuthStatus == 1) {
AdvancedFunctionRecordEntity entity = await ApiRepository.to.keyCheckFace( final AdvancedFunctionRecordEntity entity =
await ApiRepository.to.keyCheckFace(
lockId: CommonDataManage().currentKeyInfo.lockId ?? 0, lockId: CommonDataManage().currentKeyInfo.lockId ?? 0,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
if (state.getRealName.value.isEmpty || if (state.getRealName.value.isEmpty ||
state.getIDCardNumber.value.isEmpty) { state.getIDCardNumber.value.isEmpty) {
ShowCupertinoAlertView() ShowCupertinoAlertView().showOpenAuthWithIDCardInfoAlert(
.showOpenAuthWithIDCardInfoAlert((idCard, realName) { (String? idCard, String? realName) {
state.getIDCardNumber.value = idCard ?? ''; state.getIDCardNumber.value = idCard ?? '';
state.getRealName.value = realName ?? ''; state.getRealName.value = realName ?? '';
updateRealNameInfoWithAuthStatus(realNameAuthStatus); updateRealNameInfoWithAuthStatus(realNameAuthStatus);
@ -158,7 +164,7 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
titleStr: '实名认证为付费功能,请购买后再使用'.tr, titleStr: '实名认证为付费功能,请购买后再使用'.tr,
sureClick: () { sureClick: () {
Get.toNamed(Routers.advancedFeaturesWebPage, Get.toNamed(Routers.advancedFeaturesWebPage,
arguments: {'isShop': false}); arguments: <String, bool>{'isShop': false});
}); });
} else if (entity.errorCode == 433) { } else if (entity.errorCode == 433) {
// //
@ -171,16 +177,17 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
//-- //--
Future<void> updateRealNameInfoWithAuthStatus(int realNameAuthStatus) async { Future<void> updateRealNameInfoWithAuthStatus(int realNameAuthStatus) async {
KeyOperationRecordEntity entity = await ApiRepository.to.updateRealNameInfo( final KeyOperationRecordEntity entity = await ApiRepository.to
lockId: state.itemData.value.lockId ?? 0, .updateRealNameInfo(
keyId: state.itemData.value.keyId ?? 0, lockId: state.itemData.value.lockId ?? 0,
uid: state.itemData.value.uid ?? 0, keyId: state.itemData.value.keyId ?? 0,
faceAuthentication: realNameAuthStatus, uid: state.itemData.value.uid ?? 0,
realName: state.getRealName.value, faceAuthentication: realNameAuthStatus,
idCardNumber: state.getIDCardNumber.value); realName: state.getRealName.value,
idCardNumber: state.getIDCardNumber.value);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
state.isRealNameAuth.value = !state.isRealNameAuth.value; state.isRealNameAuth.value = !state.isRealNameAuth.value;
showToast("修改成功".tr, something: () { showToast('修改成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
}); });
@ -192,25 +199,26 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
switch (alertEnum) { switch (alertEnum) {
case ShowAlertEnum.realName: case ShowAlertEnum.realName:
if (state.changeRealNameController.text.isEmpty) { if (state.changeRealNameController.text.isEmpty) {
showToast("请输入真实姓名".tr); showToast('请输入真实姓名'.tr);
return; return;
} }
break; break;
case ShowAlertEnum.idCardNumber: case ShowAlertEnum.idCardNumber:
if (state.changeIDCardController.text.isEmpty) { if (state.changeIDCardController.text.isEmpty) {
showToast("请输入身份证号".tr); showToast('请输入身份证号'.tr);
return; return;
} }
break; break;
default: default:
} }
KeyOperationRecordEntity entity = await ApiRepository.to.updateRealNameInfo( final KeyOperationRecordEntity entity = await ApiRepository.to
lockId: state.itemData.value.lockId ?? 0, .updateRealNameInfo(
keyId: state.itemData.value.keyId ?? 0, lockId: state.itemData.value.lockId ?? 0,
uid: state.itemData.value.uid ?? 0, keyId: state.itemData.value.keyId ?? 0,
faceAuthentication: state.isRealNameAuth.value ? 1 : 2, uid: state.itemData.value.uid ?? 0,
realName: state.changeRealNameController.text, faceAuthentication: state.isRealNameAuth.value ? 1 : 2,
idCardNumber: state.changeIDCardController.text); realName: state.changeRealNameController.text,
idCardNumber: state.changeIDCardController.text);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
if (alertEnum == ShowAlertEnum.realName) { if (alertEnum == ShowAlertEnum.realName) {
state.itemData.value.userIdCard!.realName = state.itemData.value.userIdCard!.realName =
@ -222,7 +230,7 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
state.getIDCardNumber.value = state.getIDCardNumber.value =
state.itemData.value.userIdCard!.idCardNumber!; state.itemData.value.userIdCard!.idCardNumber!;
} }
showToast("修改成功".tr, something: () { showToast('修改成功'.tr, something: () {
eventBus.fire(ElectronicKeyListRefreshUI()); eventBus.fire(ElectronicKeyListRefreshUI());
eventBus.fire(AuthorizedAdminPageRefreshUI()); eventBus.fire(AuthorizedAdminPageRefreshUI());
}); });
@ -232,44 +240,56 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
String getKeyTypeShowDateTime() { String getKeyTypeShowDateTime() {
String useDateStr = ''; String useDateStr = '';
if (state.keyType.value == 1) { if (state.keyType.value == 1) {
useDateStr = "永久".tr; useDateStr = '永久'.tr;
} else if (state.keyType.value == 2) { } else if (state.keyType.value == 2) {
useDateStr = useDateStr =
"${DateTool().dateToYMDHNString(state.starDate.value)}\n${DateTool().dateToYMDHNString(state.endDate.value)}"; '${DateTool().dateToYMDHNString(state.starDate.value)}\n${DateTool().dateToYMDHNString(state.endDate.value)}';
} else if (state.keyType.value == 3) { } else if (state.keyType.value == 3) {
useDateStr = "单次".tr; useDateStr = '单次'.tr;
} else if (state.keyType.value == 4) { } else if (state.keyType.value == 4) {
useDateStr = useDateStr =
"${DateTool().dateToYMDString(state.starDate.value)}\n${DateTool().dateToYMDString(state.endDate.value)}"; '${DateTool().dateToYMDString(state.starDate.value)}\n${DateTool().dateToYMDString(state.endDate.value)}';
} }
return useDateStr; return useDateStr;
} }
Future openModalBottomSheet(BuildContext context) async { Future<void> openModalBottomSheet(BuildContext context) async {
var textList = <String>[]; List<String> textList = <String>[];
if (state.itemData.value.keyRight == 1) { final bool isAdminKey = state.itemData.value.keyRight == 1;
final bool isLockOwner = CommonDataManage().currentKeyInfo.isLockOwner == 1;
if (isAdminKey) {
// //
textList = [ textList = <String>[
state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen ? '取消冻结'.tr : "冻结".tr, if (state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen)
"取消授权".tr '取消冻结'.tr
else
'冻结'.tr,
if (isLockOwner) '取消授权'.tr
]; ];
} else if (CommonDataManage().currentKeyInfo.isLockOwner == 1) { } else if (isLockOwner) {
// //
if (state.keyType.value == 1 || state.keyType.value == 2) { if (state.keyType.value == 1 || state.keyType.value == 2) {
textList = [ textList = <String>[
state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen ? '取消冻结'.tr : "冻结".tr, if (state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen)
state.itemData.value.keyRight == 1 ? '取消授权'.tr : '授权'.tr '取消冻结'.tr
else
'冻结'.tr,
if (state.itemData.value.keyRight == 1) '取消授权'.tr else '授权'.tr
]; ];
} else if (state.keyType.value == 4) { } else if (state.keyType.value == 4) {
textList = [ textList = <String>[
state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen if (state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen)
? '取消冻结'.tr '取消冻结'.tr
: "冻结".tr else
'冻结'.tr
]; ];
} }
}else{ } else {
textList = [ textList = <String>[
state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen ? '取消冻结'.tr : "冻结".tr, if (state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen)
'取消冻结'.tr
else
'冻结'.tr,
]; ];
} }
showModalBottomSheet( showModalBottomSheet(
@ -280,20 +300,21 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
return AlertBottomWidget( return AlertBottomWidget(
topTitle: '', topTitle: '',
items: textList, items: textList,
chooseCallback: (value) { chooseCallback: (int value) {
int index = value; final int index = value;
if (index == 0) { if (index == 0) {
if (state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen) { if (state.itemData.value.keyStatus ==
XSConstantMacro.keyStatusFrozen) {
// //
if (state.itemData.value.keyRight == 1) { if (state.itemData.value.keyRight == 1) {
// //
ShowTipView().showDeleteAdministratorIsHaveAllDataDialog( ShowTipView().showDeleteAdministratorIsHaveAllDataDialog(
'同时解冻其发送的钥匙'.tr, (isAllData) { '同时解冻其发送的钥匙'.tr, (bool isAllData) {
cancelFreeze(isAllData ? 1 : 0); cancelFreeze(isAllData ? 1 : 0);
}); });
} else { } else {
ShowTipView() ShowTipView()
.showIosTipWithContentDialog("取消冻结会在用户APP连网后生效".tr, () { .showIosTipWithContentDialog('取消冻结会在用户APP连网后生效'.tr, () {
cancelFreeze(0); cancelFreeze(0);
}); });
} }
@ -301,12 +322,12 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
if (state.itemData.value.keyRight == 1) { if (state.itemData.value.keyRight == 1) {
// //
ShowTipView().showDeleteAdministratorIsHaveAllDataDialog( ShowTipView().showDeleteAdministratorIsHaveAllDataDialog(
'同时冻结其发送的钥匙'.tr, (isAllData) { '同时冻结其发送的钥匙'.tr, (bool isAllData) {
freezeKey(isAllData ? 1 : 0); freezeKey(isAllData ? 1 : 0);
}); });
} else { } else {
ShowTipView() ShowTipView()
.showIosTipWithContentDialog("冻结会在用户APP连网后生效".tr, () { .showIosTipWithContentDialog('冻结会在用户APP连网后生效'.tr, () {
freezeKey(0); freezeKey(0);
}); });
} }
@ -315,15 +336,11 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
// / // /
if (state.itemData.value.keyRight == 1) { if (state.itemData.value.keyRight == 1) {
// //
ShowTipView() ShowTipView().showIosTipWithContentDialog(
.showIosTipWithContentDialog("取消授权会在用户APP连网后生效".tr, () { '取消授权会在用户APP连网后生效'.tr, cancelAdministrator);
cancelAdministrator();
});
} else { } else {
ShowTipView().showIosTipWithContentDialog( ShowTipView().showIosTipWithContentDialog(
"授权用户拥有管理员的大部分权限,比如发送钥匙、发送密码".tr, () { '授权用户拥有管理员的大部分权限,比如发送钥匙、发送密码'.tr, setAdministrator);
setAdministrator();
});
} }
} }
}, },
@ -331,16 +348,16 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
}); });
} }
deletKeyLogic() { void deletKeyLogic() {
if (state.itemData.value.keyRight == 1) { if (state.itemData.value.keyRight == 1) {
// //
ShowTipView().showDeleteAdministratorIsHaveAllDataDialog( ShowTipView().showDeleteAdministratorIsHaveAllDataDialog(
'同时删除其发送的所有钥匙,钥匙删除后不能恢复'.tr, (isAllData) { '同时删除其发送的所有钥匙,钥匙删除后不能恢复'.tr, (bool isAllData) {
deleteKeyRequest(isAllData ? 1 : 0); deleteKeyRequest(isAllData ? 1 : 0);
}); });
} else { } else {
// //
ShowTipView().showIosTipWithContentDialog("删除钥匙会在用户APP连网后生效".tr, () { ShowTipView().showIosTipWithContentDialog('删除钥匙会在用户APP连网后生效'.tr, () {
deleteKeyRequest(0); deleteKeyRequest(0);
}); });
} }
@ -363,16 +380,17 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
return currentController; return currentController;
} }
noModificationAllowedDuringFreeze() { void noModificationAllowedDuringFreeze() {
if (state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen) { if (state.itemData.value.keyStatus == XSConstantMacro.keyStatusFrozen) {
showToast("冻结状态下不允许修改钥匙权限".tr); showToast('冻结状态下不允许修改钥匙权限'.tr);
return; return;
} }
} }
// //
Future<void> keyCheckFace() async { Future<void> keyCheckFace() async {
AdvancedFunctionRecordEntity entity = await ApiRepository.to.keyCheckFace( final AdvancedFunctionRecordEntity entity =
await ApiRepository.to.keyCheckFace(
lockId: CommonDataManage().currentKeyInfo.lockId ?? 0, lockId: CommonDataManage().currentKeyInfo.lockId ?? 0,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
@ -385,7 +403,7 @@ class ElectronicKeyDetailLogic extends BaseGetXController {
titleStr: '实名认证为付费功能,请购买后再使用'.tr, titleStr: '实名认证为付费功能,请购买后再使用'.tr,
sureClick: () { sureClick: () {
Get.toNamed(Routers.advancedFeaturesWebPage, Get.toNamed(Routers.advancedFeaturesWebPage,
arguments: {'isShop': false}); arguments: <String, bool>{'isShop': false});
}); });
} else if (entity.errorCode == 433) { } else if (entity.errorCode == 433) {
// //

View File

@ -1,4 +1,3 @@
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';

View File

@ -5,6 +5,7 @@ import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/common/XSConstantMacro/XSConstantMacro.dart'; import 'package:star_lock/common/XSConstantMacro/XSConstantMacro.dart';
import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/electronicKeyList_logic.dart'; import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/electronicKeyList_logic.dart';
import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/electronicKeyList_state.dart';
import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/entity/ElectronicKeyListEntity.dart'; import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/entity/ElectronicKeyListEntity.dart';
import 'package:star_lock/tools/noData.dart'; import 'package:star_lock/tools/noData.dart';
import 'package:star_lock/tools/storage.dart'; import 'package:star_lock/tools/storage.dart';
@ -26,8 +27,8 @@ class ElectronicKeyListPage extends StatefulWidget {
} }
class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> { class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
final logic = Get.put(ElectronicKeyListLogic()); final ElectronicKeyListLogic logic = Get.put(ElectronicKeyListLogic());
final state = Get.find<ElectronicKeyListLogic>().state; final ElectronicKeyListState state = Get.find<ElectronicKeyListLogic>().state;
@override @override
void initState() { void initState() {
@ -38,7 +39,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
Future<void> mockRequest() async { Future<void> mockRequest() async {
// //
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); bool? isDemoMode = await Storage.getBool(ifIsDemoModeOrNot);
if (isDemoMode == false) { if (isDemoMode == false) {
logic.mockNetworkDataRequest().then((ElectronicKeyListEntity value) { logic.mockNetworkDataRequest().then((ElectronicKeyListEntity value) {
setState(() {}); setState(() {});
@ -54,7 +55,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
barTitle: TranslationLoader.lanKeys!.electronicKey!.tr, barTitle: TranslationLoader.lanKeys!.electronicKey!.tr,
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor, backgroundColor: AppColors.mainColor,
actionsList: [ actionsList: <Widget>[
TextButton( TextButton(
child: Text( child: Text(
TranslationLoader.lanKeys!.reset!.tr, TranslationLoader.lanKeys!.reset!.tr,
@ -62,13 +63,11 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
), ),
onPressed: () async { onPressed: () async {
// //
var isDemoMode = await Storage.getBool(ifIsDemoModeOrNot); final bool? isDemoMode = await Storage.getBool(ifIsDemoModeOrNot);
if (isDemoMode == false) { if (isDemoMode == false) {
ShowTipView().showIosTipWithContentDialog("该锁的电子钥匙都将被删除".tr, (){ ShowTipView().showIosTipWithContentDialog('该锁的电子钥匙都将被删除'.tr, logic.resetElectronicKeyListRequest);
logic.resetElectronicKeyListRequest();
});
} else { } else {
logic.showToast("演示模式".tr); logic.showToast('演示模式'.tr);
} }
}, },
), ),
@ -83,7 +82,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
mockRequest(); mockRequest();
}, },
child: Column( child: Column(
children: [ children: <Widget>[
// _searchWidget(), // _searchWidget(),
KeySearchWidget( KeySearchWidget(
editingController: state.searchController, editingController: state.searchController,
@ -102,7 +101,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
AddBottomWhiteBtn( AddBottomWhiteBtn(
btnName: TranslationLoader.lanKeys!.sendKey!.tr, btnName: TranslationLoader.lanKeys!.sendKey!.tr,
onClick: () { onClick: () {
Navigator.pushNamed(context, Routers.sendElectronicKeyPage).then((val) { Navigator.pushNamed(context, Routers.sendElectronicKeyPage).then((Object? val) {
if (val != null) { if (val != null) {
logic.pageNo = 1; logic.pageNo = 1;
mockRequest(); mockRequest();
@ -130,7 +129,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
child: ListView.separated( child: ListView.separated(
shrinkWrap: true, shrinkWrap: true,
itemCount: state.itemDataList.value.length, itemCount: state.itemDataList.value.length,
itemBuilder: (c, index) { itemBuilder: (BuildContext c, int index) {
ElectronicKeyListItem indexEntity = state.itemDataList.value[index]; ElectronicKeyListItem indexEntity = state.itemDataList.value[index];
String useDateStr = ''; //使 String useDateStr = ''; //使
String keyStatus = ''; // String keyStatus = ''; //
@ -154,7 +153,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
endActionPane: ActionPane( endActionPane: ActionPane(
extentRatio: 0.2, extentRatio: 0.2,
motion: const ScrollMotion(), motion: const ScrollMotion(),
children: [ children: <Widget>[
SlidableAction( SlidableAction(
onPressed: (BuildContext context) { onPressed: (BuildContext context) {
logic.deletKeyLogic(indexEntity); logic.deletKeyLogic(indexEntity);
@ -175,9 +174,9 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
indexEntity.remoteEnable == 1 ? true : false, () { indexEntity.remoteEnable == 1 ? true : false, () {
Navigator.pushNamed( Navigator.pushNamed(
context, Routers.electronicKeyDetailPage, context, Routers.electronicKeyDetailPage,
arguments: { arguments: <String, ElectronicKeyListItem>{
"itemData": indexEntity, 'itemData': indexEntity,
}).then((val) { }).then((Object? val) {
if (val != null) { if (val != null) {
logic.mockNetworkDataRequest(); logic.mockNetworkDataRequest();
setState(() {}); setState(() {});
@ -214,7 +213,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
useDateStr = '${sendDateStr.toLocal().toString().substring(0, 16)} ${"永久".tr}'; useDateStr = '${sendDateStr.toLocal().toString().substring(0, 16)} ${"永久".tr}';
} else if (indexEntity.keyType == XSConstantMacro.keyTypeOnce) { } else if (indexEntity.keyType == XSConstantMacro.keyTypeOnce) {
// //
useDateStr = "单次".tr; useDateStr = '单次'.tr;
useDateStr = '${sendDateStr.toLocal().toString().substring(0, 16)} ${"单次".tr}'; useDateStr = '${sendDateStr.toLocal().toString().substring(0, 16)} ${"单次".tr}';
} else if (indexEntity.keyType == XSConstantMacro.keyTypeLoop) { } else if (indexEntity.keyType == XSConstantMacro.keyTypeLoop) {
// //
@ -232,7 +231,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
color: Colors.white, color: Colors.white,
height: 90.h, height: 90.h,
child: Row( child: Row(
children: [ children: <Widget>[
SizedBox(width: 30.w), SizedBox(width: 30.w),
Image.asset( Image.asset(
avatarURL, avatarURL,
@ -243,14 +242,14 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
Expanded( Expanded(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Row( Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween, // mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: <Widget>[
SizedBox( SizedBox(
width: 1.sw - 110.w - 34.w - 60.w, width: 1.sw - 110.w - 34.w - 60.w,
child: Row( child: Row(
children: [ children: <Widget>[
Flexible( Flexible(
child: Text(receiveUser, child: Text(receiveUser,
maxLines: 1, maxLines: 1,
@ -290,7 +289,7 @@ class _ElectronicKeyListPageState extends State<ElectronicKeyListPage> {
SizedBox(height: 10.h), SizedBox(height: 10.h),
Row( Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: <Widget>[
Text( Text(
useDate, useDate,
style: TextStyle( style: TextStyle(

View File

@ -125,7 +125,7 @@ class _MassSendElectronicKeyPageState extends State<MassSendElectronicKeyPage> {
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Text( Text(
"发送成功".tr, '发送成功'.tr,
style: TextStyle( style: TextStyle(
fontSize: 26.sp, fontSize: 26.sp,
color: Colors.black, color: Colors.black,
@ -201,9 +201,10 @@ class _MassSendElectronicKeyPageState extends State<MassSendElectronicKeyPage> {
: state.lockIdList.length.toString(), : state.lockIdList.length.toString(),
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
Navigator.pushNamed(context, Routers.massSendLockGroupListPage, arguments:{ Navigator.pushNamed(context, Routers.massSendLockGroupListPage,
"keyLimits":"2", arguments: {
}).then((value) { 'keyLimits': '2',
}).then((Object? value) {
//ID列表 //ID列表
if (value != null) { if (value != null) {
value as Map<String, dynamic>; value as Map<String, dynamic>;

View File

@ -6,27 +6,26 @@ import 'package:star_lock/main/lockDetail/electronicKey/massSendElectronicKey/ma
typedef _CallBack = void Function(int selectIndex, String selectLockId); typedef _CallBack = void Function(int selectIndex, String selectLockId);
class massSendLockGroupCell extends StatelessWidget { class massSendLockGroupCell extends StatelessWidget {
massSendLockGroupCell(int index,
{required this.currentIndex,
required this.lockListByGroup,
required this.selectLockAction,
required this.isVip,
Key? key})
: super(key: key);
final int currentIndex; final int currentIndex;
List lockListByGroup; List lockListByGroup;
final _CallBack selectLockAction; final _CallBack selectLockAction;
bool isVip; bool isVip;
massSendLockGroupCell(int index,
{Key? key,
required this.currentIndex,
required this.lockListByGroup,
required this.selectLockAction,
required this.isVip})
: super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ListView.separated( return ListView.separated(
physics: const NeverScrollableScrollPhysics(), physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true, shrinkWrap: true,
itemCount: lockListByGroup.length, itemCount: lockListByGroup.length,
itemBuilder: (_, itemIndex) { itemBuilder: (_, int itemIndex) {
LockListItem itemData = lockListByGroup[itemIndex]; final LockListItem itemData = lockListByGroup[itemIndex];
return _itemBuilder(itemData, itemIndex); return _itemBuilder(itemData, itemIndex);
}, },
separatorBuilder: (BuildContext context, int index) { separatorBuilder: (BuildContext context, int index) {
@ -68,8 +67,8 @@ class massSendLockGroupCell extends StatelessWidget {
)), )),
Image.asset( Image.asset(
itemData.isChecked itemData.isChecked
? "images/icon_round_select.png" ? 'images/icon_round_select.png'
: "images/icon_round_unSelect.png", : 'images/icon_round_unSelect.png',
width: 30.w, width: 30.w,
height: 30.w, height: 30.w,
color: !isVip ? Colors.grey : AppColors.mainColor, color: !isVip ? Colors.grey : AppColors.mainColor,

View File

@ -9,7 +9,7 @@ class MassSendLockGroupListLogic extends BaseGetXController {
// //
Future<void> mockNetworkDataRequest() async { Future<void> mockNetworkDataRequest() async {
MassSendLockGroupListEntity entity = final MassSendLockGroupListEntity entity =
await ApiRepository.to.lockGroupList(state.keyLimits); await ApiRepository.to.lockGroupList(state.keyLimits);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
if (entity.data != null) { if (entity.data != null) {

View File

@ -1,11 +1,11 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/appRouters.dart';
import 'package:star_lock/app_settings/app_colors.dart'; import 'package:star_lock/app_settings/app_colors.dart';
import 'package:star_lock/main/lockDetail/electronicKey/massSendElectronicKey/massSendLockGroupList/massSendLockGroupCell.dart'; import 'package:star_lock/main/lockDetail/electronicKey/massSendElectronicKey/massSendLockGroupList/massSendLockGroupCell.dart';
import 'package:star_lock/main/lockDetail/electronicKey/massSendElectronicKey/massSendLockGroupList/massSendLockGroupListEntity.dart'; import 'package:star_lock/main/lockDetail/electronicKey/massSendElectronicKey/massSendLockGroupList/massSendLockGroupListEntity.dart';
import 'package:star_lock/main/lockDetail/electronicKey/massSendElectronicKey/massSendLockGroupList/massSendLockGroupList_logic.dart'; import 'package:star_lock/main/lockDetail/electronicKey/massSendElectronicKey/massSendLockGroupList/massSendLockGroupList_logic.dart';
import 'package:star_lock/main/lockDetail/electronicKey/massSendElectronicKey/massSendLockGroupList/massSendLockGroupList_state.dart';
import 'package:star_lock/tools/ExpandedListView.dart'; import 'package:star_lock/tools/ExpandedListView.dart';
import 'package:star_lock/tools/showCupertinoAlertView.dart'; import 'package:star_lock/tools/showCupertinoAlertView.dart';
import 'package:star_lock/tools/submitBtn.dart'; import 'package:star_lock/tools/submitBtn.dart';
@ -21,8 +21,10 @@ class MassSendLockGroupListPage extends StatefulWidget {
} }
class _MassSendLockGroupListPageState extends State<MassSendLockGroupListPage> { class _MassSendLockGroupListPageState extends State<MassSendLockGroupListPage> {
final logic = Get.put(MassSendLockGroupListLogic()); final MassSendLockGroupListLogic logic =
final state = Get.find<MassSendLockGroupListLogic>().state; Get.put(MassSendLockGroupListLogic());
final MassSendLockGroupListState state =
Get.find<MassSendLockGroupListLogic>().state;
@override @override
initState() { initState() {
@ -77,7 +79,7 @@ class _MassSendLockGroupListPageState extends State<MassSendLockGroupListPage> {
child: SubmitBtn( child: SubmitBtn(
btnName: '确定'.tr, btnName: '确定'.tr,
onClick: () { onClick: () {
Map<String, dynamic> resultMap = {}; final Map<String, dynamic> resultMap = {};
resultMap['selectLockIdList'] = resultMap['selectLockIdList'] =
state.selectLockIdList.value; state.selectLockIdList.value;
Navigator.pop(context, resultMap); Navigator.pop(context, resultMap);
@ -94,12 +96,12 @@ class _MassSendLockGroupListPageState extends State<MassSendLockGroupListPage> {
Widget _buildListView(BuildContext context, List itemList) { Widget _buildListView(BuildContext context, List itemList) {
return ListView.separated( return ListView.separated(
itemCount: itemList.length, itemCount: itemList.length,
itemBuilder: (context, index) { itemBuilder: (BuildContext context, int index) {
GroupListItem itemData = itemList[index]; final GroupListItem itemData = itemList[index];
return _buildLockExpandedList(context, index, itemData); return _buildLockExpandedList(context, index, itemData);
}, },
shrinkWrap: true, shrinkWrap: true,
separatorBuilder: (context, index) { separatorBuilder: (BuildContext context, index) {
return const Divider( return const Divider(
height: 1, height: 1,
color: AppColors.greyLineColor, color: AppColors.greyLineColor,

View File

@ -6,6 +6,7 @@ import 'package:star_lock/common/XSConstantMacro/XSConstantMacro.dart';
import 'package:star_lock/main/lockDetail/electronicKey/sendElectronicKey/sendElectronicKey/view/sendElectronicKeyView_state.dart'; import 'package:star_lock/main/lockDetail/electronicKey/sendElectronicKey/sendElectronicKey/view/sendElectronicKeyView_state.dart';
import 'package:star_lock/mine/valueAddedServices/advancedFunctionRecord/advancedFunctionRecord_entity.dart'; import 'package:star_lock/mine/valueAddedServices/advancedFunctionRecord/advancedFunctionRecord_entity.dart';
import 'package:star_lock/network/api_repository.dart'; import 'package:star_lock/network/api_repository.dart';
import 'package:star_lock/tools/regularExpression.dart';
import 'package:star_lock/tools/showCupertinoAlertView.dart'; import 'package:star_lock/tools/showCupertinoAlertView.dart';
import 'package:star_lock/tools/baseGetXController.dart'; import 'package:star_lock/tools/baseGetXController.dart';
import 'package:star_lock/tools/commonDataManage.dart'; import 'package:star_lock/tools/commonDataManage.dart';
@ -139,7 +140,9 @@ class SendElectronicKeyViewLogic extends BaseGetXController {
var entity = await ApiRepository.to.sendElectronicKey( var entity = await ApiRepository.to.sendElectronicKey(
createUser: state.isCreateUser == true ? "1" : "0", createUser: state.isCreateUser == true ? "1" : "0",
countryCode: state.countryCode, countryCode: state.countryCode,
usernameType: isPhoneNumber(state.emailOrPhoneController.text) == true usernameType: RegularExpression()
.isPhoneNumber(state.emailOrPhoneController.text) ==
true
? '1' ? '1'
: '2', : '2',
endDate: int.parse(endDate), endDate: int.parse(endDate),
@ -184,7 +187,8 @@ class SendElectronicKeyViewLogic extends BaseGetXController {
// //
Future<void> keyCheckFace() async { Future<void> keyCheckFace() async {
AdvancedFunctionRecordEntity entity = await ApiRepository.to.keyCheckFace( final AdvancedFunctionRecordEntity entity =
await ApiRepository.to.keyCheckFace(
lockId: CommonDataManage().currentKeyInfo.lockId ?? 0, lockId: CommonDataManage().currentKeyInfo.lockId ?? 0,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
@ -205,19 +209,6 @@ class SendElectronicKeyViewLogic extends BaseGetXController {
} }
} }
bool isPhoneNumber(String input) {
// 11
final RegExp phoneRegExp = RegExp(r'^\d{11}$');
return phoneRegExp.hasMatch(input);
}
bool isEmail(String input) {
//
final RegExp emailRegExp =
RegExp(r'^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$');
return emailRegExp.hasMatch(input);
}
TextEditingController getCurrentController(int lineIndex) { TextEditingController getCurrentController(int lineIndex) {
TextEditingController currentController = TextEditingController(); TextEditingController currentController = TextEditingController();
switch (lineIndex) { switch (lineIndex) {

View File

@ -186,7 +186,7 @@ class AddFaceLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
Get.close(1); Get.close(1);
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
@ -231,7 +231,7 @@ class AddFaceLogic extends BaseGetXController {
// //
Future<void> senderCancelAddFaceCommand() async { Future<void> senderCancelAddFaceCommand() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -97,7 +97,7 @@ class FaceDetailLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);

View File

@ -256,7 +256,7 @@ class FaceListLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {

View File

@ -185,7 +185,7 @@ class AddFingerprintLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: (){
Get.close(1); Get.close(1);
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
@ -227,7 +227,7 @@ class AddFingerprintLogic extends BaseGetXController {
// //
Future<void> senderCancelAddFingerprintCommand() async { Future<void> senderCancelAddFingerprintCommand() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -98,7 +98,7 @@ class FingerprintDetailLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
// var publicKey = await Storage.getStringList(saveBluePublicKey); // var publicKey = await Storage.getStringList(saveBluePublicKey);
// List<int> publicKeyDataList = changeStringListToIntList(publicKey!); // List<int> publicKeyDataList = changeStringListToIntList(publicKey!);

View File

@ -189,7 +189,7 @@ class FingerprintListLogic extends BaseGetXController{
} }
// //
Future<void> senderQueryingFingerprintStatus() async { Future<void> senderQueryingFingerprintStatus() async {
BlueManage().bludSendData(BlueManage().connectDeviceName,(BluetoothConnectionState state) async { BlueManage().blueSendData(BlueManage().connectDeviceName,(BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.connected) { if (state == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
@ -217,7 +217,7 @@ class FingerprintListLogic extends BaseGetXController{
// () // ()
Future<void> senderCheckingUserInfoCount() async { Future<void> senderCheckingUserInfoCount() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState state) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.connected) { if (state == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
@ -248,7 +248,7 @@ class FingerprintListLogic extends BaseGetXController{
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: (){
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected){ if (deviceConnectionState == BluetoothConnectionState.connected){
// var publicKey = await Storage.getStringList(saveBluePublicKey); // var publicKey = await Storage.getStringList(saveBluePublicKey);
// List<int> publicKeyDataList = changeStringListToIntList(publicKey!); // List<int> publicKeyDataList = changeStringListToIntList(publicKey!);

View File

@ -90,7 +90,7 @@ class IrisDetailLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
// var publicKey = await Storage.getStringList(saveBluePublicKey); // var publicKey = await Storage.getStringList(saveBluePublicKey);

View File

@ -189,7 +189,7 @@ class IrisListLogic extends BaseGetXController {
// //
Future<void> senderQueryingFaceStatus() async { Future<void> senderQueryingFaceStatus() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState state) async { (BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.connected) { if (state == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
@ -218,7 +218,7 @@ class IrisListLogic extends BaseGetXController {
// () // ()
Future<void> senderCheckingUserInfoCount() async { Future<void> senderCheckingUserInfoCount() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState state) async { (BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.connected) { if (state == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
@ -250,7 +250,7 @@ class IrisListLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);

View File

@ -1,4 +1,3 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/scheduler.dart'; import 'package:flutter/scheduler.dart';
@ -7,6 +6,8 @@ import 'package:get/get.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import 'package:star_lock/common/XSConstantMacro/XSConstantMacro.dart'; import 'package:star_lock/common/XSConstantMacro/XSConstantMacro.dart';
import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/entity/ElectronicKeyListEntity.dart';
import 'package:star_lock/main/lockDetail/lockSet/lockTime/getServerDatetime_entity.dart';
import 'package:star_lock/widget/permission/permission_dialog.dart'; import 'package:star_lock/widget/permission/permission_dialog.dart';
@ -35,7 +36,7 @@ class LockDetailLogic extends BaseGetXController {
// //
void initReplySubscription() { void initReplySubscription() {
state.replySubscription = state.replySubscription =
EventBusManager().eventBus!.on<Reply>().listen((reply) async { EventBusManager().eventBus!.on<Reply>().listen((Reply reply) async {
// //
if (reply is OpenDoorReply && state.ifCurrentScreen.value == true) { if (reply is OpenDoorReply && state.ifCurrentScreen.value == true) {
_replyOpenLock(reply); _replyOpenLock(reply);
@ -51,48 +52,52 @@ class LockDetailLogic extends BaseGetXController {
// //
Future<void> _replyOpenLock(Reply reply) async { Future<void> _replyOpenLock(Reply reply) async {
int status = reply.data[6]; final int status = reply.data[6];
switch (status) { switch (status) {
case 0x00: case 0x00:
// //
// _showFullScreenOverlay(Get.context!); // _showFullScreenOverlay(Get.context!);
cancelBlueConnetctToastTimer();
state.iSClosedUnlockSuccessfulPopup.value = true; state.iSClosedUnlockSuccessfulPopup.value = true;
cancelBlueConnetctToastTimer();
state.closedUnlockSuccessfulTimer?.cancel(); state.closedUnlockSuccessfulTimer?.cancel();
// 3 // 3
state.closedUnlockSuccessfulTimer = Timer.periodic(3.seconds, (timer) { state.closedUnlockSuccessfulTimer =
Timer.periodic(3.seconds, (Timer timer) {
state.iSClosedUnlockSuccessfulPopup.value = false; state.iSClosedUnlockSuccessfulPopup.value = false;
timer.cancel(); timer.cancel();
eventBus.fire(RefreshLockDetailInfoDataEvent()); eventBus.fire(RefreshLockDetailInfoDataEvent());
}); });
// //
int power = reply.data[7]; final int power = reply.data[7];
state.electricQuantity.value = power; state.electricQuantity.value = power;
// //
if (state.keyInfos.value.lockFeature!.isSupportBackupBattery == 1) { if (state.keyInfos.value.lockFeature!.isSupportBackupBattery == 1) {
int powerStandby = reply.data[9]; final int powerStandby = reply.data[9];
state.electricQuantityStandby.value = powerStandby; state.electricQuantityStandby.value = powerStandby;
} }
// //
uploadElectricQuantityRequest(); uploadElectricQuantityRequest();
//
getLockRecordLastUploadDataTime(); getLockRecordLastUploadDataTime();
resetOpenDoorState(); resetOpenDoorState();
state.animationController!.stop();
break; break;
case 0x06: case 0x06:
// //
var privateKey = await Storage.getStringList(saveBluePrivateKey); final List<String>? privateKey =
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList =
changeStringListToIntList(privateKey!);
var signKey = await Storage.getStringList(saveBlueSignKey); final List<String>? signKey =
List<int> signKeyDataList = changeStringListToIntList(signKey!); await Storage.getStringList(saveBlueSignKey);
final List<int> signKeyDataList = changeStringListToIntList(signKey!);
var tokenData = reply.data.sublist(2, 6); final List<int> tokenData = reply.data.sublist(2, 6);
var saveStrList = changeIntListToStringList(tokenData); final List<String> saveStrList = changeIntListToStringList(tokenData);
Storage.setStringList(saveBlueToken, saveStrList); Storage.setStringList(saveBlueToken, saveStrList);
IoSenderManage.senderOpenLock( IoSenderManage.senderOpenLock(
@ -110,69 +115,56 @@ class LockDetailLogic extends BaseGetXController {
case 0x16: case 0x16:
// ... // ...
resetOpenDoorState(); resetOpenDoorState();
showToast("正在开锁中...".tr, something: () { showToast('正在开锁中...'.tr, something: () {
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
}); });
break; break;
case 0x0d: case 0x0d:
// //
showToast('钥匙无效'.tr); showToast('钥匙无效'.tr);
// state.animationController!.stop(); openDoorError();
resetOpenDoorState();
cancelBlueConnetctToastTimer();
BlueManage().disconnect();
break; break;
case 0x0b: case 0x0b:
// //
showToast('钥匙过期'.tr); showToast('钥匙过期'.tr);
resetOpenDoorState(); openDoorError();
cancelBlueConnetctToastTimer();
BlueManage().disconnect();
break; break;
case 0x0a: case 0x0a:
// //
showToast("钥匙不存在"); showToast('钥匙不存在');
resetOpenDoorState(); openDoorError();
cancelBlueConnetctToastTimer();
BlueManage().disconnect();
break; break;
case 0x0c: case 0x0c:
// //
showToast("钥匙数量已到上限"); showToast('钥匙数量已到上限');
resetOpenDoorState(); openDoorError();
cancelBlueConnetctToastTimer();
BlueManage().disconnect();
break; break;
case 0x0e: case 0x0e:
// //
showToast("钥匙已存在"); showToast('钥匙已存在');
resetOpenDoorState(); openDoorError();
cancelBlueConnetctToastTimer();
BlueManage().disconnect();
break; break;
case 0x0f: case 0x0f:
// //
showToast("用户已存在"); showToast('用户已存在');
resetOpenDoorState(); openDoorError();
cancelBlueConnetctToastTimer();
BlueManage().disconnect();
break; break;
default: default:
// //
AppLog.log("开锁失败"); AppLog.log('开锁失败');
// state.animationController!.stop(); openDoorError();
resetOpenDoorState();
cancelBlueConnetctToastTimer();
BlueManage().disconnect();
break; break;
} }
} }
//
void openDoorError() {
resetOpenDoorState();
state.animationController!.stop();
cancelBlueConnetctToastTimer();
BlueManage().disconnect();
}
// //
void closeLuckStatus() { void closeLuckStatus() {
state.openLockBtnState.value = 0; state.openLockBtnState.value = 0;
@ -183,11 +175,11 @@ class LockDetailLogic extends BaseGetXController {
// //
Future<void> _replyReferEventRecordTime(Reply reply) async { Future<void> _replyReferEventRecordTime(Reply reply) async {
int status = reply.data[2]; final int status = reply.data[2];
switch (status) { switch (status) {
case 0x00: case 0x00:
// //
int dataLength = (reply.data[5] << 8) + reply.data[6]; final int dataLength = (reply.data[5] << 8) + reply.data[6];
// AppLog.log("dataLength:$dataLength"); // AppLog.log("dataLength:$dataLength");
if (dataLength > 0) { if (dataLength > 0) {
reply.data.removeRange(0, 7); reply.data.removeRange(0, 7);
@ -195,32 +187,32 @@ class LockDetailLogic extends BaseGetXController {
if (reply.data.length < 17) { if (reply.data.length < 17) {
return; return;
} }
var getList = splitList(reply.data, 17); final List<List<int>> getList = splitList(reply.data, 17);
// AppLog.log("getList:$getList"); // AppLog.log("getList:$getList");
var uploadList = []; final List uploadList = [];
for (int i = 0; i < getList.length; i++) { for (int i = 0; i < getList.length; i++) {
var indexList = getList[i]; final List<int> indexList = getList[i];
// AppLog.log("indexList:$indexList"); // AppLog.log("indexList:$indexList");
var indexMap = {}; final Map indexMap = {};
indexMap["type"] = indexList[0].toString(); indexMap['type'] = indexList[0].toString();
int operateDate = 0; int operateDate = 0;
if (indexList[0] == 2) { if (indexList[0] == 2) {
var passwordData = reply.data.sublist(7, 17); final List<int> passwordData = reply.data.sublist(7, 17);
var password = utf8String(passwordData); final String password = utf8String(passwordData);
indexMap["user"] = password.toString(); indexMap['user'] = password.toString();
} else { } else {
int userNo = (indexList[1] * 256) + indexList[2]; final int userNo = (indexList[1] * 256) + indexList[2];
indexMap["user"] = userNo.toString(); indexMap['user'] = userNo.toString();
} }
indexMap["success"] = "1"; indexMap['success'] = '1';
int time = ((0xff & indexList[(3)]) << 24 | final int time = ((0xff & indexList[(3)]) << 24 |
(0xff & indexList[4]) << 16 | (0xff & indexList[4]) << 16 |
(0xff & indexList[5]) << 8 | (0xff & indexList[5]) << 8 |
(0xFF & indexList[6])); (0xFF & indexList[6]));
operateDate = time * 1000; operateDate = time * 1000;
indexMap["date"] = "$operateDate"; indexMap['date'] = '$operateDate';
uploadList.add(indexMap); uploadList.add(indexMap);
if (i == getList.length - 1) { if (i == getList.length - 1) {
@ -253,20 +245,21 @@ class LockDetailLogic extends BaseGetXController {
Future<void> openDoorAction() async { Future<void> openDoorAction() async {
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
resetOpenDoorState(); resetOpenDoorState();
// BlueManage().stopScan(); closeLuckStatus();
BlueManage().disconnect(); BlueManage().disconnect();
}); });
var privateKey = await Storage.getStringList(saveBluePrivateKey); final List<String>? privateKey =
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
var signKey = await Storage.getStringList(saveBlueSignKey); final List<String>? signKey = await Storage.getStringList(saveBlueSignKey);
List<int> signKeyDataList = changeStringListToIntList(signKey!); final List<int> signKeyDataList = changeStringListToIntList(signKey!);
var token = await Storage.getStringList(saveBlueToken); final List<String>? token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); final List<int> getTokenList = changeStringListToIntList(token!);
BlueManage() BlueManage()
.bludSendData(state.keyInfos.value.bluetooth!.bluetoothDeviceName!, .blueSendData(state.keyInfos.value.bluetooth!.bluetoothDeviceName!,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
IoSenderManage.senderOpenLock( IoSenderManage.senderOpenLock(
@ -293,24 +286,28 @@ class LockDetailLogic extends BaseGetXController {
} }
// () // ()
Future<void> senderReferEventRecordTime() async { void senderReferEventRecordTime() {
showBlueConnetctToastTimer( showBlueConnetctToastTimer(
isShowBlueConnetctToast: false, isShowBlueConnetctToast: false,
outTimer: 10,
action: () { action: () {
closeLuckStatus();
BlueManage().disconnect(); BlueManage().disconnect();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState connectionState) async { (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); final List<String>? privateKey =
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList =
changeStringListToIntList(privateKey!);
var token = await Storage.getStringList(saveBlueToken); final List<String>? token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); final List<int> getTokenList = changeStringListToIntList(token!);
var publicKey = await Storage.getStringList(saveBluePublicKey); final List<String>? publicKey =
List<int> getPublicKeyList = changeStringListToIntList(publicKey!); await Storage.getStringList(saveBluePublicKey);
final List<int> getPublicKeyList =
changeStringListToIntList(publicKey!);
IoSenderManage.senderReferEventRecordTimeCommand( IoSenderManage.senderReferEventRecordTimeCommand(
keyID: BlueManage().connectDeviceName, keyID: BlueManage().connectDeviceName,
@ -329,7 +326,8 @@ class LockDetailLogic extends BaseGetXController {
// //
void getServerDatetime() async { void getServerDatetime() async {
var entity = await ApiRepository.to.getServerDatetimeData(); final GetServerDatetimeEntity entity =
await ApiRepository.to.getServerDatetimeData();
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
state.differentialTime = entity.data!.date! ~/ 1000 - state.differentialTime = entity.data!.date! ~/ 1000 -
DateTime.now().millisecondsSinceEpoch ~/ 1000; DateTime.now().millisecondsSinceEpoch ~/ 1000;
@ -344,17 +342,17 @@ class LockDetailLogic extends BaseGetXController {
// token // token
void getLockNetToken() async { void getLockNetToken() async {
LockNetTokenEntity entity = await ApiRepository.to final LockNetTokenEntity entity = await ApiRepository.to
.getLockNetToken(lockId: state.keyInfos.value.lockId.toString()); .getLockNetToken(lockId: state.keyInfos.value.lockId.toString());
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
state.lockNetToken = entity.data!.token!.toString(); state.lockNetToken = entity.data!.token!.toString();
AppLog.log("从服务器获取联网token:${state.lockNetToken}"); AppLog.log('从服务器获取联网token:${state.lockNetToken}');
openDoorAction(); openDoorAction();
} else { } else {
showToast("网络访问失败,请检查网络是否正常".tr, something: () { showToast('网络访问失败,请检查网络是否正常'.tr, something: () {
resetOpenDoorState(); resetOpenDoorState();
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
state.lockNetToken = "0"; state.lockNetToken = '0';
openDoorAction(); openDoorAction();
}); });
} }
@ -362,7 +360,7 @@ class LockDetailLogic extends BaseGetXController {
// //
Future<void> uploadElectricQuantityRequest() async { Future<void> uploadElectricQuantityRequest() async {
KeyOperationRecordEntity entity = await ApiRepository.to final KeyOperationRecordEntity entity = await ApiRepository.to
.uploadElectricQuantity( .uploadElectricQuantity(
electricQuantity: state.electricQuantity.value.toString(), electricQuantity: state.electricQuantity.value.toString(),
electricQuantityStandby: electricQuantityStandby:
@ -371,15 +369,15 @@ class LockDetailLogic extends BaseGetXController {
isUnShowLoading: true); isUnShowLoading: true);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
SchedulerBinding.instance.addPostFrameCallback((_) { SchedulerBinding.instance.addPostFrameCallback((_) {
eventBus.fire(RefreshLockListInfoDataEvent()); eventBus.fire(RefreshLockListInfoDataEvent(isUnShowLoading: true));
}); });
} }
} }
// //
void getLockRecordLastUploadDataTime() async { void getLockRecordLastUploadDataTime() async {
LockOperatingRecordGetLastRecordTimeEntity entity = await ApiRepository.to final LockOperatingRecordGetLastRecordTimeEntity entity =
.getLockRecordLastUploadDataTime( await ApiRepository.to.getLockRecordLastUploadDataTime(
lockId: state.keyInfos.value.lockId.toString()); lockId: state.keyInfos.value.lockId.toString());
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
state.operateDate = entity.data!.operateDate! ~/ 1000; state.operateDate = entity.data!.operateDate! ~/ 1000;
@ -388,14 +386,14 @@ class LockDetailLogic extends BaseGetXController {
} }
// //
void lockRecordUploadData(List list) async { Future<void> lockRecordUploadData(List list) async {
KeyOperationRecordEntity entity = await ApiRepository.to final KeyOperationRecordEntity entity = await ApiRepository.to
.lockRecordUploadData( .lockRecordUploadData(
lockId: state.keyInfos.value.lockId.toString(), records: list); lockId: state.keyInfos.value.lockId.toString(), records: list);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
// mockNetworkDataRequest(); // mockNetworkDataRequest();
AppLog.log( AppLog.log(
"state.keyInfos.value.keyType:${state.keyInfos.value.keyType}"); 'state.keyInfos.value.keyType:${state.keyInfos.value.keyType}');
if (state.keyInfos.value.keyType == XSConstantMacro.keyTypeOnce) { if (state.keyInfos.value.keyType == XSConstantMacro.keyTypeOnce) {
// //
deletKeyData(); deletKeyData();
@ -405,10 +403,11 @@ class LockDetailLogic extends BaseGetXController {
// //
void deletKeyData() async { void deletKeyData() async {
var entity = await ApiRepository.to.deleteElectronicKey( final ElectronicKeyListEntity entity = await ApiRepository.to
keyId: state.keyInfos.value.keyId.toString(), includeUnderlings: 0); .deleteElectronicKey(
keyId: state.keyInfos.value.keyId.toString(), includeUnderlings: 0);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
BlueManage().connectDeviceMacAddress = ""; BlueManage().connectDeviceMacAddress = '';
SchedulerBinding.instance.addPostFrameCallback((_) { SchedulerBinding.instance.addPostFrameCallback((_) {
eventBus.fire(RefreshLockListInfoDataEvent()); eventBus.fire(RefreshLockListInfoDataEvent());
}); });
@ -422,7 +421,7 @@ class LockDetailLogic extends BaseGetXController {
state.lockSetOpenOrCloseCheckInRefreshLockDetailWithAttendanceEvent = state.lockSetOpenOrCloseCheckInRefreshLockDetailWithAttendanceEvent =
eventBus eventBus
.on<LockSetChangeSetRefreshLockDetailWithType>() .on<LockSetChangeSetRefreshLockDetailWithType>()
.listen((event) { .listen((LockSetChangeSetRefreshLockDetailWithType event) {
if (event.type == 0) { if (event.type == 0) {
// 0 // 0
state.isAttendance.value = int.parse(event.setResult); state.isAttendance.value = int.parse(event.setResult);
@ -433,7 +432,7 @@ class LockDetailLogic extends BaseGetXController {
state.isOpenLockNeedOnline.value = int.parse(event.setResult); state.isOpenLockNeedOnline.value = int.parse(event.setResult);
state.keyInfos.value.lockSetting!.appUnlockOnline = state.keyInfos.value.lockSetting!.appUnlockOnline =
int.parse(event.setResult); int.parse(event.setResult);
state.lockNetToken = ""; // token state.lockNetToken = ''; // token
} else if (event.type == 2) { } else if (event.type == 2) {
// 2 // 2
state.isOpenPassageMode.value = int.parse(event.setResult); state.isOpenPassageMode.value = int.parse(event.setResult);
@ -458,7 +457,7 @@ class LockDetailLogic extends BaseGetXController {
} }
String getKeyStatusTextAndShow() { String getKeyStatusTextAndShow() {
String text = ""; String text = '';
if (state.keyInfos.value.keyStatus == if (state.keyInfos.value.keyStatus ==
XSConstantMacro.keyStatusWaitIneffective || XSConstantMacro.keyStatusWaitIneffective ||
state.keyInfos.value.keyStatus == XSConstantMacro.keyStatusFrozen || state.keyInfos.value.keyStatus == XSConstantMacro.keyStatusFrozen ||
@ -469,7 +468,7 @@ class LockDetailLogic extends BaseGetXController {
"${"你的钥匙".tr}${XSConstantMacro.getKeyStatusStr(state.keyInfos.value.keyStatus!)}"; "${"你的钥匙".tr}${XSConstantMacro.getKeyStatusStr(state.keyInfos.value.keyStatus!)}";
} else { } else {
text = state.isOpenPassageMode.value == 1 text = state.isOpenPassageMode.value == 1
? "常开模式启动!长按闭锁".tr ? '常开模式启动!长按闭锁'.tr
: TranslationLoader.lanKeys!.clickUnlockAndHoldDownClose!.tr; : TranslationLoader.lanKeys!.clickUnlockAndHoldDownClose!.tr;
} }
return text; return text;
@ -477,9 +476,9 @@ class LockDetailLogic extends BaseGetXController {
String getCurrentFormattedTime() { String getCurrentFormattedTime() {
// //
DateTime now = DateTime.now(); final DateTime now = DateTime.now();
// //
String formattedTime = DateFormat('MM/dd HH:mm').format(now); final String formattedTime = DateFormat('MM/dd HH:mm').format(now);
return formattedTime; return formattedTime;
} }
@ -498,5 +497,17 @@ class LockDetailLogic extends BaseGetXController {
await PermissionDialog.request(Permission.location); await PermissionDialog.request(Permission.location);
await PermissionDialog.requestBluetooth(); await PermissionDialog.requestBluetooth();
final String connectDeviceName =
state.keyInfos.value.bluetooth!.bluetoothDeviceName!;
if (!BlueManage().isExistScanDevices(connectDeviceName)) {
BlueManage().startScanSingle(
connectDeviceName, 15, (List<ScanResult> p0) => null);
}
}
@override
void onInit() {
super.onInit();
} }
} }

View File

@ -8,6 +8,7 @@ import 'package:intl/intl.dart';
import 'package:star_lock/app_settings/app_colors.dart'; import 'package:star_lock/app_settings/app_colors.dart';
import 'package:star_lock/flavors.dart'; import 'package:star_lock/flavors.dart';
import 'package:star_lock/main/lockDetail/lockDetail/lockDetail_list_page.dart'; import 'package:star_lock/main/lockDetail/lockDetail/lockDetail_list_page.dart';
import 'package:star_lock/main/lockDetail/lockDetail/lockDetail_state.dart';
import 'package:star_lock/tools/aliyunRealNameAuth/aliyunRealNameAuthHandle.dart'; import 'package:star_lock/tools/aliyunRealNameAuth/aliyunRealNameAuthHandle.dart';
import 'package:star_lock/tools/showCupertinoAlertView.dart'; import 'package:star_lock/tools/showCupertinoAlertView.dart';
import 'package:star_lock/tools/showTipView.dart'; import 'package:star_lock/tools/showTipView.dart';
@ -44,8 +45,8 @@ class LockDetailPage extends StatefulWidget {
class _LockDetailPageState extends State<LockDetailPage> class _LockDetailPageState extends State<LockDetailPage>
with TickerProviderStateMixin, RouteAware { with TickerProviderStateMixin, RouteAware {
// with RouteAware // with RouteAware
final logic = Get.put(LockDetailLogic()); final LockDetailLogic logic = Get.put(LockDetailLogic());
final state = Get.find<LockDetailLogic>().state; final LockDetailState state = Get.find<LockDetailLogic>().state;
@override @override
void initState() { void initState() {
@ -75,8 +76,9 @@ class _LockDetailPageState extends State<LockDetailPage>
void _initRefreshLockDetailInfoDataEventAction() { void _initRefreshLockDetailInfoDataEventAction() {
// eventBus // eventBus
_lockRefreshLockDetailInfoDataEvent = _lockRefreshLockDetailInfoDataEvent = eventBus
eventBus.on<RefreshLockDetailInfoDataEvent>().listen((event) { .on<RefreshLockDetailInfoDataEvent>()
.listen((RefreshLockDetailInfoDataEvent event) {
setState(() {}); setState(() {});
}); });
} }
@ -114,26 +116,28 @@ class _LockDetailPageState extends State<LockDetailPage>
BlueManage().connectDeviceName = BlueManage().connectDeviceName =
state.keyInfos.value.bluetooth!.bluetoothDeviceName!; state.keyInfos.value.bluetooth!.bluetoothDeviceName!;
List<int> publicKeyData = final List<int> publicKeyData =
state.keyInfos.value.bluetooth!.publicKey!.cast<int>(); state.keyInfos.value.bluetooth!.publicKey!.cast<int>();
var saveStrList = changeIntListToStringList(publicKeyData); final List<String> saveStrList = changeIntListToStringList(publicKeyData);
Storage.setStringList(saveBluePublicKey, saveStrList); Storage.setStringList(saveBluePublicKey, saveStrList);
// //
List<int> privateKeyData = final List<int> privateKeyData =
state.keyInfos.value.bluetooth!.privateKey!.cast<int>(); state.keyInfos.value.bluetooth!.privateKey!.cast<int>();
var savePrivateKeyList = changeIntListToStringList(privateKeyData); final List<String> savePrivateKeyList =
changeIntListToStringList(privateKeyData);
Storage.setStringList(saveBluePrivateKey, savePrivateKeyList); Storage.setStringList(saveBluePrivateKey, savePrivateKeyList);
// signKey // signKey
List<int> signKeyData = final List<int> signKeyData =
state.keyInfos.value.bluetooth!.signKey!.cast<int>(); state.keyInfos.value.bluetooth!.signKey!.cast<int>();
var saveSignKeyList = changeIntListToStringList(signKeyData); final List<String> saveSignKeyList = changeIntListToStringList(signKeyData);
Storage.setStringList(saveBlueSignKey, saveSignKeyList); Storage.setStringList(saveBlueSignKey, saveSignKeyList);
bool ifHaveKey = await Storage.ifHaveKey(saveBlueToken); final bool ifHaveKey = await Storage.ifHaveKey(saveBlueToken);
if (!ifHaveKey) { if (!ifHaveKey) {
var saveTokenList = changeIntListToStringList([0, 0, 0, 0]); final List<String> saveTokenList =
changeIntListToStringList(<int>[0, 0, 0, 0]);
Storage.setStringList(saveBlueToken, saveTokenList); Storage.setStringList(saveBlueToken, saveTokenList);
} }
} }
@ -141,7 +145,7 @@ class _LockDetailPageState extends State<LockDetailPage>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
loadData(); loadData();
return F.sw(defaultCall: () => skWidget(), xhjCall: () => xhjWidget()); return F.sw(defaultCall: skWidget, xhjCall: xhjWidget);
} }
// //
@ -150,9 +154,9 @@ class _LockDetailPageState extends State<LockDetailPage>
backgroundColor: Colors.white, backgroundColor: Colors.white,
body: Obx(() { body: Obx(() {
return Stack( return Stack(
children: [ children: <Widget>[
Column( Column(
children: [ children: <Widget>[
SizedBox( SizedBox(
height: 35.h, height: 35.h,
), ),
@ -193,7 +197,7 @@ class _LockDetailPageState extends State<LockDetailPage>
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(16.r), borderRadius: BorderRadius.circular(16.r),
boxShadow: [ boxShadow: <BoxShadow>[
BoxShadow( BoxShadow(
color: Colors.black.withOpacity(0.15), color: Colors.black.withOpacity(0.15),
offset: const Offset(0, 0), offset: const Offset(0, 0),
@ -202,7 +206,7 @@ class _LockDetailPageState extends State<LockDetailPage>
), ),
]), ]),
child: Row( child: Row(
children: [ children: <Widget>[
Image.asset( Image.asset(
img, img,
width: 32.r, width: 32.r,
@ -236,7 +240,7 @@ class _LockDetailPageState extends State<LockDetailPage>
fit: BoxFit.cover, fit: BoxFit.cover,
), ),
borderRadius: BorderRadius.circular(20.r), borderRadius: BorderRadius.circular(20.r),
boxShadow: [ boxShadow: <BoxShadow>[
BoxShadow( BoxShadow(
color: Colors.black.withOpacity(0.15), color: Colors.black.withOpacity(0.15),
offset: const Offset(0, 0), offset: const Offset(0, 0),
@ -247,19 +251,15 @@ class _LockDetailPageState extends State<LockDetailPage>
), ),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: <Widget>[
const Spacer(), const Spacer(),
GestureDetector( GestureDetector(
onTap: state.openDoorBtnisUneable.value == true onTap: state.openDoorBtnisUneable.value == true
? () { ? isNeedRealNameAuthThenOpenLock
isNeedRealNameAuthThenOpenLock();
}
: null, : null,
onLongPressStart: state.openDoorBtnisUneable.value == true onLongPressStart: state.openDoorBtnisUneable.value == true
? (details) { ? (LongPressStartDetails details) {
setState(() { setState(startUnLock);
startUnLock();
});
} }
: null, : null,
child: Container( child: Container(
@ -268,7 +268,7 @@ class _LockDetailPageState extends State<LockDetailPage>
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(100.w), borderRadius: BorderRadius.circular(100.w),
boxShadow: [ boxShadow: <BoxShadow>[
BoxShadow( BoxShadow(
color: Colors.black.withOpacity(0.3), color: Colors.black.withOpacity(0.3),
offset: const Offset(0, 0), offset: const Offset(0, 0),
@ -279,42 +279,44 @@ class _LockDetailPageState extends State<LockDetailPage>
margin: EdgeInsets.only(left: 35.w, bottom: 15.h), margin: EdgeInsets.only(left: 35.w, bottom: 15.h),
child: Stack( child: Stack(
alignment: AlignmentDirectional.center, alignment: AlignmentDirectional.center,
children: [ children: <Widget>[
state.openDoorBtnisUneable.value == false if (state.openDoorBtnisUneable.value == false)
? Icon( Icon(
Icons.bluetooth_searching, Icons.bluetooth_searching,
size: 48.r, size: 48.r,
color: AppColors.mainColor, color: AppColors.mainColor,
) )
: Image.asset( else
state.isOpenPassageMode.value == 1 Image.asset(
? 'images/icon_lock_err.png' state.isOpenPassageMode.value == 1
: 'images/icon_lock_fill.png', ? 'images/icon_lock_err.png'
width: 38.r, : 'images/icon_lock_fill.png',
height: 38.r, width: 38.r,
color: AppColors.mainColor, height: 38.r,
), color: AppColors.mainColor,
state.openDoorBtnisUneable.value == false ),
? Positioned( if (state.openDoorBtnisUneable.value == false)
child: Icon( Positioned(
Icons.bluetooth_searching, child: Icon(
size: 96.r, Icons.bluetooth_searching,
), size: 96.r,
) ),
: state.openLockBtnState.value == 1 )
? xhjBuildRotationTransition( else
width: 88.r, state.openLockBtnState.value == 1
height: 88.r, ? xhjBuildRotationTransition(
) width: 88.r,
: Positioned( height: 88.r,
child: Image.asset( )
'images/icon_circle_dotted.png', : Positioned(
width: 88.r, child: Image.asset(
height: 88.r, 'images/icon_circle_dotted.png',
color: state.isOpenPassageMode.value == 1 width: 88.r,
? Colors.red height: 88.r,
: AppColors.mainColor, color: state.isOpenPassageMode.value == 1
)), ? Colors.red
: AppColors.mainColor,
)),
], ],
), ),
), ),
@ -323,10 +325,10 @@ class _LockDetailPageState extends State<LockDetailPage>
padding: EdgeInsets.only(left: 15.w, right: 00.w, bottom: 15.h), padding: EdgeInsets.only(left: 15.w, right: 00.w, bottom: 15.h),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: <Widget>[
Column( Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: <Widget>[
Text( Text(
TranslationLoader TranslationLoader
.lanKeys!.clickUnlockAndHoldDownClose!.tr, .lanKeys!.clickUnlockAndHoldDownClose!.tr,
@ -341,16 +343,16 @@ class _LockDetailPageState extends State<LockDetailPage>
Column( Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: <Widget>[
Row( Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: <Widget>[
Image.asset( Image.asset(
showElectricIcon(state.electricQuantity.value), showElectricIcon(state.electricQuantity.value),
width: 30.w, width: 30.w,
height: 24.w), height: 24.w),
SizedBox(width: 2.w), SizedBox(width: 2.w),
Text("${state.electricQuantity.value}%", Text('${state.electricQuantity.value}%',
style: TextStyle( style: TextStyle(
fontSize: 18.sp, fontSize: 18.sp,
color: AppColors.darkGrayTextColor)), color: AppColors.darkGrayTextColor)),
@ -368,13 +370,13 @@ class _LockDetailPageState extends State<LockDetailPage>
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: <Widget>[
Image.asset( Image.asset(
showElectricIcon(state.electricQuantity.value), showElectricIcon(state.electricQuantity.value),
width: 30.w, width: 30.w,
height: 24.w), height: 24.w),
SizedBox(width: 2.w), SizedBox(width: 2.w),
Text("--%", Text('--%',
style: TextStyle( style: TextStyle(
fontSize: 18.sp, fontSize: 18.sp,
color: AppColors.darkGrayTextColor)), color: AppColors.darkGrayTextColor)),
@ -400,32 +402,30 @@ class _LockDetailPageState extends State<LockDetailPage>
// //
Widget skWidget() { Widget skWidget() {
return ListView( return ListView(
children: [ children: <Widget>[
Visibility( Visibility(
visible: visible:
((state.keyInfos.value.keyType == XSConstantMacro.keyTypeTime || (state.keyInfos.value.keyType == XSConstantMacro.keyTypeTime ||
state.keyInfos.value.keyType == state.keyInfos.value.keyType ==
XSConstantMacro.keyTypeLoop) && // XSConstantMacro.keyTypeLoop) && //
(DateTool().compareTimeGetDaysFromNow( (DateTool().compareTimeGetDaysFromNow(
state.keyInfos.value.endDate!) <= state.keyInfos.value.endDate!) <=
15 && 15 &&
DateTool().compareTimeGetDaysFromNow( DateTool().compareTimeGetDaysFromNow(
state.keyInfos.value.endDate!) >= state.keyInfos.value.endDate!) >=
0) && // 030 0) && // 030
(state.keyInfos.value.keyStatus == (state.keyInfos.value.keyStatus ==
XSConstantMacro.keyStatusNormalUse || XSConstantMacro.keyStatusNormalUse ||
state.keyInfos.value.keyStatus == state.keyInfos.value.keyStatus ==
XSConstantMacro.keyStatusWaitReceive) // 使 XSConstantMacro.keyStatusWaitReceive) // 使
) ,
? true
: false,
child: Container( child: Container(
// height: 30.h, // height: 30.h,
color: const Color(0xFFFBEFD4), color: const Color(0xFFFBEFD4),
padding: EdgeInsets.only(top: 8.h, bottom: 8.h), padding: EdgeInsets.only(top: 8.h, bottom: 8.h),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Text( Text(
"${"钥匙将在".tr}${DateTool().compareTimeGetDaysFromNow(state.keyInfos.value.endDate!)}${"天后失效".tr}", "${"钥匙将在".tr}${DateTool().compareTimeGetDaysFromNow(state.keyInfos.value.endDate!)}${"天后失效".tr}",
style: TextStyle( style: TextStyle(
@ -434,26 +434,26 @@ class _LockDetailPageState extends State<LockDetailPage>
), ),
), ),
), ),
Stack(children: [ Stack(children: <Widget>[
Container( Container(
width: 1.sw, width: 1.sw,
height: 1.sh - ScreenUtil().statusBarHeight, height: 1.sh - ScreenUtil().statusBarHeight,
color: Colors.white, color: Colors.white,
child: Column( child: Column(
children: [ children: <Widget>[
topWidget(), topWidget(),
SizedBox( SizedBox(
height: 10.h, height: 10.h,
), ),
Obx(() => buildPageIndicator()), Obx(buildPageIndicator),
Expanded( Expanded(
child: Container( child: Container(
margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 30.h), margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 30.h),
child: PageView( child: PageView(
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,
controller: state.pageController, controller: state.pageController,
children: [ children: <Widget>[
Obx(() => bottomWidget()), Obx(bottomWidget),
attachmentWidget(), attachmentWidget(),
], ],
), ),
@ -476,7 +476,7 @@ class _LockDetailPageState extends State<LockDetailPage>
Widget topWidget() { Widget topWidget() {
return Column( return Column(
children: [ children: <Widget>[
F.sw( F.sw(
defaultCall: () => SizedBox(height: 50.h), defaultCall: () => SizedBox(height: 50.h),
xhjCall: () => Padding( xhjCall: () => Padding(
@ -490,7 +490,7 @@ class _LockDetailPageState extends State<LockDetailPage>
), ),
), ),
Stack( Stack(
children: [ children: <Widget>[
Center( Center(
child: Text( child: Text(
state.lockAlias.value, state.lockAlias.value,
@ -504,7 +504,7 @@ class _LockDetailPageState extends State<LockDetailPage>
Positioned( Positioned(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: <Widget>[
GestureDetector( GestureDetector(
onTap: () { onTap: () {
ShowTipView().showSureAlertDialog( ShowTipView().showSureAlertDialog(
@ -512,7 +512,7 @@ class _LockDetailPageState extends State<LockDetailPage>
}, },
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: <Widget>[
FlavorsImg( FlavorsImg(
child: Image.asset( child: Image.asset(
showElectricIcon(state.electricQuantity.value), showElectricIcon(state.electricQuantity.value),
@ -520,7 +520,7 @@ class _LockDetailPageState extends State<LockDetailPage>
height: 24.w), height: 24.w),
), ),
SizedBox(width: 2.w), SizedBox(width: 2.w),
Text("${state.electricQuantity.value}%", Text('${state.electricQuantity.value}%',
style: TextStyle( style: TextStyle(
fontSize: 18.sp, fontSize: 18.sp,
color: AppColors.darkGrayTextColor)), color: AppColors.darkGrayTextColor)),
@ -542,7 +542,7 @@ class _LockDetailPageState extends State<LockDetailPage>
1, 1,
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: <Widget>[
FlavorsImg( FlavorsImg(
child: Image.asset( child: Image.asset(
showElectricIcon( showElectricIcon(
@ -551,7 +551,7 @@ class _LockDetailPageState extends State<LockDetailPage>
height: 24.w), height: 24.w),
), ),
SizedBox(width: 2.w), SizedBox(width: 2.w),
Text("${state.electricQuantityStandby.value}%", Text('${state.electricQuantityStandby.value}%',
style: TextStyle( style: TextStyle(
fontSize: 18.sp, fontSize: 18.sp,
color: AppColors.darkGrayTextColor)), color: AppColors.darkGrayTextColor)),
@ -580,23 +580,19 @@ class _LockDetailPageState extends State<LockDetailPage>
color: Colors.white, color: Colors.white,
height: 330.w, height: 330.w,
child: Stack( child: Stack(
children: [ children: <Widget>[
Center( Center(
child: GestureDetector( child: GestureDetector(
onTap: state.openDoorBtnisUneable.value == true onTap: state.openDoorBtnisUneable.value == true
? () { ? isNeedRealNameAuthThenOpenLock
isNeedRealNameAuthThenOpenLock();
}
: null, : null,
onLongPressStart: state.openDoorBtnisUneable.value == true onLongPressStart: state.openDoorBtnisUneable.value == true
? (details) { ? (LongPressStartDetails details) {
setState(() { setState(startUnLock);
startUnLock();
});
} }
: null, : null,
child: Stack( child: Stack(
children: [ children: <Widget>[
FlavorsImg( FlavorsImg(
child: Image.asset( child: Image.asset(
state.openDoorBtnisUneable.value == false state.openDoorBtnisUneable.value == false
@ -609,31 +605,32 @@ class _LockDetailPageState extends State<LockDetailPage>
// color: AppColors.primaryTopColor, // color: AppColors.primaryTopColor,
), ),
), ),
state.openDoorBtnisUneable.value == false if (state.openDoorBtnisUneable.value == false)
? Positioned( Positioned(
child: FlavorsImg( child: FlavorsImg(
child: Image.asset(
'images/main/icon_main_openLockBtn_grey.png',
width: 330.w,
height: 330.w,
),
),
)
else
state.openLockBtnState.value == 1
? buildRotationTransition(
width: 330.w,
height: 330.w,
)
: Positioned(
child: FlavorsImg(
child: Image.asset( child: Image.asset(
'images/main/icon_main_openLockBtn_grey.png', state.isOpenPassageMode.value == 1
? 'images/main/icon_main_normallyOpenMode_circle.png'
: 'images/main/icon_main_openLockBtn_circle.png',
width: 330.w, width: 330.w,
height: 330.w, height: 330.w,
), ),
), )),
)
: state.openLockBtnState.value == 1
? buildRotationTransition(
width: 330.w,
height: 330.w,
)
: Positioned(
child: FlavorsImg(
child: Image.asset(
state.isOpenPassageMode.value == 1
? 'images/main/icon_main_normallyOpenMode_circle.png'
: 'images/main/icon_main_openLockBtn_circle.png',
width: 330.w,
height: 330.w,
),
)),
], ],
), ),
)), )),
@ -641,9 +638,8 @@ class _LockDetailPageState extends State<LockDetailPage>
right: 90.w, right: 90.w,
bottom: 1, bottom: 1,
child: Obx(() => Visibility( child: Obx(() => Visibility(
visible: state.keyInfos.value.lockSetting!.remoteUnlock == 1 visible:
? true state.keyInfos.value.lockSetting!.remoteUnlock == 1,
: false,
child: GestureDetector( child: GestureDetector(
onTap: () { onTap: () {
ShowCupertinoAlertView().isToRemoteUnLockAlert( ShowCupertinoAlertView().isToRemoteUnLockAlert(
@ -672,7 +668,7 @@ class _LockDetailPageState extends State<LockDetailPage>
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Text( Text(
logic.getKeyStatusTextAndShow(), logic.getKeyStatusTextAndShow(),
style: TextStyle( style: TextStyle(
@ -685,9 +681,7 @@ class _LockDetailPageState extends State<LockDetailPage>
SizedBox( SizedBox(
height: 30.h, height: 30.h,
), ),
F.sw( F.sw(defaultCall: adminInfoView, xhjCall: () => const SizedBox()),
defaultCall: () => adminInfoView(),
xhjCall: () => const SizedBox()),
SizedBox( SizedBox(
height: 20.h, height: 20.h,
), ),
@ -707,7 +701,7 @@ class _LockDetailPageState extends State<LockDetailPage>
mainAxisAlignment: mainAxisAlignment:
center ? MainAxisAlignment.center : MainAxisAlignment.start, center ? MainAxisAlignment.center : MainAxisAlignment.start,
mainAxisSize: max ? MainAxisSize.max : MainAxisSize.min, mainAxisSize: max ? MainAxisSize.max : MainAxisSize.min,
children: [ children: <Widget>[
Image.asset( Image.asset(
'images/icon_electronicKey_admin.png', 'images/icon_electronicKey_admin.png',
width: 24.w, width: 24.w,
@ -742,7 +736,7 @@ class _LockDetailPageState extends State<LockDetailPage>
? AppColors.mainColor ? AppColors.mainColor
: AppColors.btnDisableColor), : AppColors.btnDisableColor),
), ),
if (add) ...[ if (add) ...<Widget>[
const Spacer(), const Spacer(),
GestureDetector( GestureDetector(
onTap: () { onTap: () {
@ -752,7 +746,7 @@ class _LockDetailPageState extends State<LockDetailPage>
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: <Widget>[
FlavorsImg( FlavorsImg(
child: Image.asset( child: Image.asset(
'images/mine/icon_mine_main_addLock.png', 'images/mine/icon_mine_main_addLock.png',
@ -823,7 +817,7 @@ class _LockDetailPageState extends State<LockDetailPage>
Widget buildPageIndicator() { Widget buildPageIndicator() {
return Row( return Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(2, (index) { children: List.generate(2, (int index) {
return Container( return Container(
width: 10.0.w, width: 10.0.w,
height: 10.0.w, height: 10.0.w,
@ -855,7 +849,7 @@ class _LockDetailPageState extends State<LockDetailPage>
// //
List<Widget> getAttachmentWidget() { List<Widget> getAttachmentWidget() {
var showWidgetArr = <Widget>[]; final List<Widget> showWidgetArr = <Widget>[];
// 线 // 线
// if (state.isAttendance.value == 1) { // if (state.isAttendance.value == 1) {
// showWidgetArr.add(bottomItem( // showWidgetArr.add(bottomItem(
@ -911,7 +905,7 @@ class _LockDetailPageState extends State<LockDetailPage>
// //
List<Widget> getNormalWidget() { List<Widget> getNormalWidget() {
List<Widget> showWidgetArr = <Widget>[]; final List<Widget> showWidgetArr = <Widget>[];
// //
if (state.isAttendance.value == 1) { if (state.isAttendance.value == 1) {
showWidgetArr.add(bottomItem( showWidgetArr.add(bottomItem(
@ -928,15 +922,17 @@ class _LockDetailPageState extends State<LockDetailPage>
TranslationLoader.lanKeys!.operatingRecord!.tr, TranslationLoader.lanKeys!.operatingRecord!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.doorLockLogPage, Get.toNamed(Routers.doorLockLogPage,
arguments: {"keyInfo": state.keyInfos.value}); arguments: <String, LockListInfoItemEntity>{
'keyInfo': state.keyInfos.value
});
})); }));
// //
showWidgetArr.add(bottomItem('images/main/icon_main_set.png', showWidgetArr.add(bottomItem('images/main/icon_main_set.png',
TranslationLoader.lanKeys!.set!.tr, true, () { TranslationLoader.lanKeys!.set!.tr, true, () {
Get.toNamed(Routers.lockSetPage, arguments: { Get.toNamed(Routers.lockSetPage, arguments: <String, Object?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
"isOnlyOneData": state.isOnlyOneData 'isOnlyOneData': state.isOnlyOneData
}); });
})); }));
@ -945,7 +941,7 @@ class _LockDetailPageState extends State<LockDetailPage>
// //
List<Widget> getAllWidget() { List<Widget> getAllWidget() {
var showWidgetArr = <Widget>[]; final List<Widget> showWidgetArr = <Widget>[];
// //
if (state.isAttendance.value == 1) { if (state.isAttendance.value == 1) {
showWidgetArr.add(bottomItem( showWidgetArr.add(bottomItem(
@ -971,7 +967,9 @@ class _LockDetailPageState extends State<LockDetailPage>
TranslationLoader.lanKeys!.password!.tr, TranslationLoader.lanKeys!.password!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.passwordKeyListPage, Get.toNamed(Routers.passwordKeyListPage,
arguments: {"keyInfo": state.keyInfos.value}); arguments: <String, LockListInfoItemEntity>{
'keyInfo': state.keyInfos.value
});
})); }));
// ic卡 // ic卡
@ -980,8 +978,8 @@ class _LockDetailPageState extends State<LockDetailPage>
'images/main/icon_main_icCard.png', 'images/main/icon_main_icCard.png',
TranslationLoader.lanKeys!.card!.tr, TranslationLoader.lanKeys!.card!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.cardListPage, arguments: { Get.toNamed(Routers.cardListPage, arguments: <String, int?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
}); });
})); }));
} }
@ -992,8 +990,8 @@ class _LockDetailPageState extends State<LockDetailPage>
'images/main/icon_main_fingerprint.png', 'images/main/icon_main_fingerprint.png',
TranslationLoader.lanKeys!.fingerprint!.tr, TranslationLoader.lanKeys!.fingerprint!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.fingerprintListPage, arguments: { Get.toNamed(Routers.fingerprintListPage, arguments: <String, int?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
}); });
})); }));
} }
@ -1015,8 +1013,8 @@ class _LockDetailPageState extends State<LockDetailPage>
'images/main/icon_face.png', 'images/main/icon_face.png',
TranslationLoader.lanKeys!.humanFace!.tr, TranslationLoader.lanKeys!.humanFace!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.faceListPage, arguments: { Get.toNamed(Routers.faceListPage, arguments: <String, int?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
}); });
}), }),
); );
@ -1027,8 +1025,8 @@ class _LockDetailPageState extends State<LockDetailPage>
bottomItem( bottomItem(
'images/main/icon_iris.png', '虹膜'.tr, state.bottomBtnisEable.value, 'images/main/icon_iris.png', '虹膜'.tr, state.bottomBtnisEable.value,
() { () {
Get.toNamed(Routers.irisListPage, arguments: { Get.toNamed(Routers.irisListPage, arguments: <String, int?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
}); });
}), }),
); );
@ -1039,8 +1037,8 @@ class _LockDetailPageState extends State<LockDetailPage>
bottomItem( bottomItem(
'images/main/icon_palm.png', '手掌'.tr, state.bottomBtnisEable.value, 'images/main/icon_palm.png', '手掌'.tr, state.bottomBtnisEable.value,
() { () {
Get.toNamed(Routers.palmListPage, arguments: { Get.toNamed(Routers.palmListPage, arguments: <String, int?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
}); });
}), }),
); );
@ -1053,9 +1051,9 @@ class _LockDetailPageState extends State<LockDetailPage>
'images/main/icon_catEyes.png', 'images/main/icon_catEyes.png',
TranslationLoader.lanKeys!.monitoring!.tr, TranslationLoader.lanKeys!.monitoring!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.realTimePicturePage, arguments: { Get.toNamed(Routers.realTimePicturePage, arguments: <String, Object?>{
"lockName": state.keyInfos.value.lockName, 'lockName': state.keyInfos.value.lockName,
"isMonitoring": true 'isMonitoring': true
}); });
}), }),
); );
@ -1068,11 +1066,13 @@ class _LockDetailPageState extends State<LockDetailPage>
TranslationLoader.lanKeys!.authorizedAdmin!.tr, TranslationLoader.lanKeys!.authorizedAdmin!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.authorizedAdminListPage, Get.toNamed(Routers.authorizedAdminListPage,
arguments: {"keyInfo": state.keyInfos.value}); arguments: <String, LockListInfoItemEntity>{
'keyInfo': state.keyInfos.value
});
})); }));
} }
var endWiddget = <Widget>[]; final List<Widget> endWiddget = <Widget>[];
endWiddget.add( endWiddget.add(
// //
bottomItem( bottomItem(
@ -1082,7 +1082,9 @@ class _LockDetailPageState extends State<LockDetailPage>
// Get.toNamed(Routers.lockOperatingRecordPage, // Get.toNamed(Routers.lockOperatingRecordPage,
// arguments: {"keyInfo": state.keyInfos.value}); // arguments: {"keyInfo": state.keyInfos.value});
Get.toNamed(Routers.doorLockLogPage, Get.toNamed(Routers.doorLockLogPage,
arguments: {"keyInfo": state.keyInfos.value}); arguments: <String, LockListInfoItemEntity>{
'keyInfo': state.keyInfos.value
});
}), }),
); );
@ -1092,8 +1094,8 @@ class _LockDetailPageState extends State<LockDetailPage>
'images/main/icon_lockDetail_videoLog.png', 'images/main/icon_lockDetail_videoLog.png',
TranslationLoader.lanKeys!.videoLog!.tr, TranslationLoader.lanKeys!.videoLog!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.videoLogPage, arguments: { Get.toNamed(Routers.videoLogPage, arguments: <String, int?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
}); });
})); }));
} }
@ -1103,8 +1105,8 @@ class _LockDetailPageState extends State<LockDetailPage>
'images/main/icon_lockDetail_messageReminding.png', 'images/main/icon_lockDetail_messageReminding.png',
TranslationLoader.lanKeys!.messageReminding!.tr, TranslationLoader.lanKeys!.messageReminding!.tr,
state.bottomBtnisEable.value, () { state.bottomBtnisEable.value, () {
Get.toNamed(Routers.msgNotificationPage, arguments: { Get.toNamed(Routers.msgNotificationPage, arguments: <String, int?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
}); });
}), }),
); );
@ -1114,9 +1116,9 @@ class _LockDetailPageState extends State<LockDetailPage>
bottomItem('images/main/icon_main_set.png', bottomItem('images/main/icon_main_set.png',
TranslationLoader.lanKeys!.set!.tr, true, () { TranslationLoader.lanKeys!.set!.tr, true, () {
// logic.clickItemBtnAction(10); // logic.clickItemBtnAction(10);
Get.toNamed(Routers.lockSetPage, arguments: { Get.toNamed(Routers.lockSetPage, arguments: <String, Object?>{
"lockId": state.keyInfos.value.lockId, 'lockId': state.keyInfos.value.lockId,
"isOnlyOneData": state.isOnlyOneData, 'isOnlyOneData': state.isOnlyOneData,
}); });
}), }),
); );
@ -1126,12 +1128,12 @@ class _LockDetailPageState extends State<LockDetailPage>
Widget bottomItem( Widget bottomItem(
String iconUrl, String name, bool bottomBtnisEable, Function() onClick) { String iconUrl, String name, bool bottomBtnisEable, Function() onClick) {
Widget child = F.sw( final Widget child = F.sw(
defaultCall: () => Container( defaultCall: () => Container(
color: Colors.white, color: Colors.white,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: <Widget>[
SizedBox( SizedBox(
width: 42.w, width: 42.w,
height: 42.h, height: 42.h,
@ -1164,7 +1166,7 @@ class _LockDetailPageState extends State<LockDetailPage>
padding: EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.w), padding: EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.w),
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: <Widget>[
SizedBox( SizedBox(
width: 42.w, width: 42.w,
height: 42.h, height: 42.h,
@ -1195,19 +1197,19 @@ class _LockDetailPageState extends State<LockDetailPage>
onTap: bottomBtnisEable onTap: bottomBtnisEable
? onClick ? onClick
: () { : () {
logic.showToast("请在锁旁边完成第一次开锁".tr); logic.showToast('请在锁旁边完成第一次开锁'.tr);
}, },
child: child, child: child,
); );
} }
listeningAnimations() async { Future<void> listeningAnimations() async {
await Future.delayed(Duration.zero, () { await Future<void>.delayed(Duration.zero, () {
state.animationController = AnimationController( state.animationController = AnimationController(
duration: const Duration(seconds: 1), vsync: this); duration: const Duration(seconds: 1), vsync: this);
state.animationController!.repeat(); state.animationController!.repeat();
//StatusListener //StatusListener
state.animationController!.addStatusListener((status) { state.animationController!.addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) { if (status == AnimationStatus.completed) {
state.animationController!.reset(); state.animationController!.reset();
state.animationController!.forward(); state.animationController!.forward();
@ -1237,7 +1239,7 @@ class _LockDetailPageState extends State<LockDetailPage>
Widget _unlockSuccessWidget() { Widget _unlockSuccessWidget() {
return Center( return Center(
child: Stack( child: Stack(
children: [ children: <Widget>[
Image.asset( Image.asset(
state.iSOpenLock.value == true state.iSOpenLock.value == true
? 'images/main/unlocked_bg.png' ? 'images/main/unlocked_bg.png'
@ -1247,10 +1249,11 @@ class _LockDetailPageState extends State<LockDetailPage>
), ),
Positioned( Positioned(
top: 180.h, top: 180.h,
left: 55.w, width: 358.w,
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text( Text(
state.keyInfos.value.lockAlias!, state.keyInfos.value.lockAlias!,
style: TextStyle( style: TextStyle(
@ -1289,9 +1292,9 @@ class _LockDetailPageState extends State<LockDetailPage>
String getCurrentFormattedTime() { String getCurrentFormattedTime() {
// //
DateTime now = DateTime.now(); final DateTime now = DateTime.now();
// //
String formattedTime = DateFormat('MM/dd HH:mm').format(now); final String formattedTime = DateFormat('MM/dd HH:mm').format(now);
return formattedTime; return formattedTime;
} }
@ -1303,65 +1306,57 @@ class _LockDetailPageState extends State<LockDetailPage>
DateTool().compareTimeIsOvertime(state.nextAuthTime.value) == true) { DateTool().compareTimeIsOvertime(state.nextAuthTime.value) == true) {
AliyunRealNameAuthProvider( AliyunRealNameAuthProvider(
getLockInfo: state.keyInfos.value, getLockInfo: state.keyInfos.value,
onCertifyResultWithTime: ((bool isSuccess, int getNextAuthTime) { onCertifyResultWithTime: (bool isSuccess, int getNextAuthTime) {
state.nextAuthTime.value = getNextAuthTime; state.nextAuthTime.value = getNextAuthTime;
if (isSuccess) { if (isSuccess) {
// //
setState(() { setState(startOpenLock);
startOpenLock();
});
} }
})).initAliyunRealNameAuth(); }).initAliyunRealNameAuth();
} else { } else {
// //
setState(() { setState(startOpenLock);
startOpenLock();
});
} }
} }
startOpenLock() { void startOpenLock() {
if (state.openLockBtnState.value == 1) { if (state.openLockBtnState.value == 1) {
return; return;
} }
state.iSOpenLock.value = true; state.iSOpenLock.value = true;
state.iSClosedUnlockSuccessfulPopup.value = false;
state.openLockBtnState.value = 1; state.openLockBtnState.value = 1;
state.animationController!.forward(); state.animationController!.forward();
AppLog.log('点击开锁');
AppLog.log("点击开锁");
if (state.isOpenLockNeedOnline.value == 0) { if (state.isOpenLockNeedOnline.value == 0) {
// //
state.openDoorModel = 0; state.openDoorModel = 0;
AppLog.log("点击开锁 state.openDoorModel = 0 不需要联网"); AppLog.log('点击开锁 state.openDoorModel = 0 不需要联网');
logic.openDoorAction(); logic.openDoorAction();
} else { } else {
// //
state.openDoorModel = 2; state.openDoorModel = 2;
AppLog.log("点击开锁 state.openDoorModel = 2 需要联网"); AppLog.log('点击开锁 state.openDoorModel = 2 需要联网');
logic.getLockNetToken(); logic.getLockNetToken();
} }
} }
startUnLock() { void startUnLock() {
if (state.openLockBtnState.value == 1) { if (state.openLockBtnState.value == 1) {
return; return;
} }
state.iSOpenLock.value = false; state.iSOpenLock.value = false;
state.iSClosedUnlockSuccessfulPopup.value = false;
state.openLockBtnState.value = 1; state.openLockBtnState.value = 1;
state.animationController!.forward(); state.animationController!.forward();
EasyLoading.showToast('正在尝试闭锁……'.tr, duration: 2000.milliseconds);
EasyLoading.showToast("正在尝试闭锁……".tr, duration: 2000.milliseconds); AppLog.log('长按闭锁');
AppLog.log("长按闭锁");
if (state.isOpenLockNeedOnline.value == 0) { if (state.isOpenLockNeedOnline.value == 0) {
// //
AppLog.log("长按闭锁 state.openDoorModel = 32 不需要联网"); AppLog.log('长按闭锁 state.openDoorModel = 32 不需要联网');
state.openDoorModel = 32; state.openDoorModel = 32;
logic.openDoorAction(); logic.openDoorAction();
} else { } else {
// //
AppLog.log("长按闭锁 state.openDoorModel = 34 需要联网"); AppLog.log('长按闭锁 state.openDoorModel = 34 需要联网');
state.openDoorModel = 34; state.openDoorModel = 34;
logic.getLockNetToken(); logic.getLockNetToken();
} }

View File

@ -97,7 +97,7 @@ class LockOperatingRecordLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: (){
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionStateState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionStateState) async {
if (connectionStateState == BluetoothConnectionState.connected) { if (connectionStateState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -1,9 +1,10 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/blue/io_protocol/io_setSupportFunctionsWithParameters.dart'; import 'package:star_lock/blue/io_protocol/io_setSupportFunctionsWithParameters.dart';
import 'package:star_lock/login/login/entity/LoginEntity.dart';
import 'package:star_lock/tools/baseGetXController.dart'; import 'package:star_lock/tools/baseGetXController.dart';
import '../../../../blue/blue_manage.dart'; import '../../../../blue/blue_manage.dart';
import '../../../../blue/io_reply.dart'; import '../../../../blue/io_reply.dart';
@ -15,47 +16,50 @@ import '../../../../tools/eventBusEventManage.dart';
import '../../../../tools/storage.dart'; import '../../../../tools/storage.dart';
import 'automaticBlocking_state.dart'; import 'automaticBlocking_state.dart';
class AutomaticBlockingLogic extends BaseGetXController{ class AutomaticBlockingLogic extends BaseGetXController {
final AutomaticBlockingState state = AutomaticBlockingState(); final AutomaticBlockingState state = AutomaticBlockingState();
void setAutoUnLock() async{ Future<void> setAutoUnLock() async {
String autoTime; String autoTime;
if(state.isOpen.value == false){ if (state.isOpen.value == false) {
autoTime = "0"; autoTime = '0';
}else{ } else {
if(state.isCustomLockTime.value == true){ if (state.isCustomLockTime.value == true) {
autoTime = state.timeController.text; autoTime = state.timeController.text;
if(int.parse(autoTime) >= 1000){ if (int.parse(autoTime) > 60) {
showToast("请输入小于1000的数字".tr); showToast('请输入小于或等于60的数字'.tr);
return; return;
} }
}else{ } else {
autoTime = state.autoLockTime.value; autoTime = state.autoLockTime.value;
} }
} }
var entity = await ApiRepository.to.setAutoUnlock( final LoginEntity entity = await ApiRepository.to.setAutoUnlock(
lockId: state.lockSetInfoData.value.lockId!, lockId: state.lockSetInfoData.value.lockId!,
autoLock:state.isOpen.value == true ? 1 : 0, autoLock: state.isOpen.value == true ? 1 : 0,
autoLockSecond: int.parse(autoTime), autoLockSecond: int.parse(autoTime),
); );
if(entity.errorCode!.codeIsSuccessful){ if (entity.errorCode!.codeIsSuccessful) {
state.autoLockTime.value = autoTime; state.autoLockTime.value = autoTime;
state.lockSetInfoData.value.lockSettingInfo!.autoLockSecond = int.parse(state.autoLockTime.value); state.lockSetInfoData.value.lockSettingInfo!.autoLockSecond =
showToast("操作成功".tr, something: (){ int.parse(state.autoLockTime.value);
showToast('操作成功'.tr, something: () {
eventBus.fire(RefreshLockListInfoDataEvent()); eventBus.fire(RefreshLockListInfoDataEvent());
eventBus.fire(PassCurrentLockInformationEvent(state.lockSetInfoData.value)); eventBus
.fire(PassCurrentLockInformationEvent(state.lockSetInfoData.value));
Get.back(); Get.back();
}); }, maskType: EasyLoadingMaskType.clear);
} }
} }
// //
late StreamSubscription<Reply> _replySubscription; late StreamSubscription<Reply> _replySubscription;
void _initReplySubscription() { void _initReplySubscription() {
_replySubscription = EventBusManager().eventBus!.on<Reply>().listen((reply) { _replySubscription =
if(reply is SetSupportFunctionsWithParametersReply) { EventBusManager().eventBus!.on<Reply>().listen((Reply reply) {
if (reply is SetSupportFunctionsWithParametersReply) {
_replySetSupportFunctionsWithParameters(reply); _replySetSupportFunctionsWithParameters(reply);
} }
@ -86,10 +90,10 @@ class AutomaticBlockingLogic extends BaseGetXController{
// //
Future<void> _replySetSupportFunctionsWithParameters(Reply reply) async { Future<void> _replySetSupportFunctionsWithParameters(Reply reply) async {
int status = reply.data[2]; final int status = reply.data[2];
switch(status){ switch (status) {
case 0x00: case 0x00:
// //
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
dismissEasyLoading(); dismissEasyLoading();
@ -106,34 +110,39 @@ class AutomaticBlockingLogic extends BaseGetXController{
// () // ()
Future<void> sendAutoLock() async { Future<void> sendAutoLock() async {
if(state.sureBtnState.value == 1){ if (state.sureBtnState.value == 1) {
return; return;
} }
state.sureBtnState.value = 1; state.sureBtnState.value = 1;
showEasyLoading(); showEasyLoading();
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: () {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); final List<String>? privateKey =
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList =
changeStringListToIntList(privateKey!);
var token = await Storage.getStringList(saveBlueToken); final List<String>? token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); final List<int> getTokenList = changeStringListToIntList(token!);
var publicKey = await Storage.getStringList(saveBluePublicKey); final List<String>? publicKey =
List<int> getPublicKeyList = changeStringListToIntList(publicKey!); await Storage.getStringList(saveBluePublicKey);
final List<int> getPublicKeyList =
changeStringListToIntList(publicKey!);
String autoTime; String autoTime;
if(state.isOpen.value == false){ if (state.isOpen.value == false) {
autoTime = "0"; autoTime = '0';
}else{ } else {
if(state.isCustomLockTime.value == true){ if (state.isCustomLockTime.value == true) {
autoTime = state.timeController.text; autoTime = state.timeController.text;
}else{ } else {
autoTime = state.autoLockTime.value; autoTime = state.autoLockTime.value;
} }
} }
@ -142,7 +151,7 @@ class AutomaticBlockingLogic extends BaseGetXController{
userID: await Storage.getUid(), userID: await Storage.getUid(),
featureBit: 29, featureBit: 29,
featureParaLength: 2, featureParaLength: 2,
featureData: [int.parse(autoTime)], featureData: <int>[int.parse(autoTime)],
token: getTokenList, token: getTokenList,
needAuthor: 1, needAuthor: 1,
publicKey: getPublicKeyList, publicKey: getPublicKeyList,
@ -151,7 +160,7 @@ class AutomaticBlockingLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
if(state.ifCurrentScreen.value == true){ if (state.ifCurrentScreen.value == true) {
showBlueConnetctToast(); showBlueConnetctToast();
} }
} }
@ -159,36 +168,42 @@ class AutomaticBlockingLogic extends BaseGetXController{
} }
void ifCanNext() { void ifCanNext() {
if(((state.isOpen.value != (state.lockSetInfoData.value.lockSettingInfo!.autoLock! == 1 ? true : false)) && final int autoLock = state.lockSetInfoData.value.lockSettingInfo!.autoLock!;
(state.autoLockTime.value != state.lockSetInfoData.value.lockSettingInfo!.autoLockSecond!.toString()) && final String autoLockSecond =
(state.isJustForShow.value == false)) || ((state.isOpen.value = true) && (state.lockSetInfoData.value.lockSettingInfo!.autoLock! == 1) && state.lockSetInfoData.value.lockSettingInfo!.autoLockSecond!.toString();
(state.autoLockTime.value != state.lockSetInfoData.value.lockSettingInfo!.autoLockSecond!.toString()) && final bool openLock = autoLock == 1;
(state.isJustForShow.value == false))){ final bool isNotJustForShow = state.isJustForShow.value == false;
final bool isEditAutoLockSecond =
state.autoLockTime.value != autoLockSecond;
if (!isNotJustForShow) {
//
state.canNext.value = false;
return;
}
if (state.isOpen.value != openLock || isEditAutoLockSecond) {
state.canNext.value = true; state.canNext.value = true;
}else{ } else {
state.canNext.value = false; state.canNext.value = false;
} }
} }
@override @override
void onReady() { void onReady() {
// TODO: implement onReady
super.onReady(); super.onReady();
_initReplySubscription(); _initReplySubscription();
Storage.getAutomaticLockOffTime()
.then((String value) => state.timeController.text = value);
} }
@override @override
void onInit() { void onInit() {
// TODO: implement onInit
super.onInit(); super.onInit();
// _readSupportFunctionsWithParameters();
} }
@override @override
void onClose() { void onClose() {
// TODO: implement onClose
super.onClose(); super.onClose();
_replySubscription.cancel(); _replySubscription.cancel();
} }

View File

@ -4,9 +4,10 @@ import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/lockSet/automaticBlocking/automaticBlocking_state.dart';
import 'package:star_lock/tools/storage.dart';
import '../../../../app_settings/app_colors.dart'; import '../../../../app_settings/app_colors.dart';
import '../../../../blue/blue_manage.dart';
import '../../../../tools/appRouteObserver.dart'; import '../../../../tools/appRouteObserver.dart';
import '../../../../tools/commonItem.dart'; import '../../../../tools/commonItem.dart';
import '../../../../tools/showBottomSheetTool.dart'; import '../../../../tools/showBottomSheetTool.dart';
@ -22,9 +23,10 @@ class AutomaticBlockingPage extends StatefulWidget {
State<AutomaticBlockingPage> createState() => _AutomaticBlockingPageState(); State<AutomaticBlockingPage> createState() => _AutomaticBlockingPageState();
} }
class _AutomaticBlockingPageState extends State<AutomaticBlockingPage> with RouteAware { class _AutomaticBlockingPageState extends State<AutomaticBlockingPage>
final logic = Get.put(AutomaticBlockingLogic()); with RouteAware {
final state = Get.find<AutomaticBlockingLogic>().state; final AutomaticBlockingLogic logic = Get.put(AutomaticBlockingLogic());
final AutomaticBlockingState state = Get.find<AutomaticBlockingLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -33,85 +35,90 @@ class _AutomaticBlockingPageState extends State<AutomaticBlockingPage> with Rout
appBar: TitleAppBar( appBar: TitleAppBar(
barTitle: TranslationLoader.lanKeys!.automaticBlocking!.tr, barTitle: TranslationLoader.lanKeys!.automaticBlocking!.tr,
haveBack: true, haveBack: true,
actionsList: [ actionsList: <Widget>[
Obx(() => TextButton( Obx(() => TextButton(
onPressed: state.canNext.value == false ? null :() { onPressed: state.canNext.value == false
// if(state.isJustForShow.value == true){ ? null
// return; : () {
// } if (state.isOpen.value == false) {
// if(state.isCustomLockTime.value == true && state.timeController.text.isEmpty){ ShowTipView().showIosTipWithContentDialog(
// logic.showToast("请输入自定义时间"); '关闭后,智能锁将设置为全天常开模式,直到手动关闭'.tr,
// return; logic.sendAutoLock);
// } } else {
logic.sendAutoLock();
if(state.isOpen.value == false){ }
ShowTipView().showIosTipWithContentDialog('关闭后,智能锁将设置为全天常开模式,直到手动关闭'.tr, (){ },
logic.sendAutoLock(); child: Text(
}); state.canNext.value == false
}else{ ? ''
logic.sendAutoLock(); : TranslationLoader.lanKeys!.save!.tr,
} style: TextStyle(color: Colors.white, fontSize: 24.sp),
}, ),
child: Text( )),
state.canNext.value == false ? "" : TranslationLoader.lanKeys!.save!.tr,
style: TextStyle(color: Colors.white, fontSize: 24.sp),
),
)),
], ],
backgroundColor: AppColors.mainColor), backgroundColor: AppColors.mainColor),
body: ListView( body: ListView(
children: [ children: <Widget>[
Obx(() => CommonItem( Obx(
leftTitel: TranslationLoader.lanKeys!.automaticBlocking!.tr, () => CommonItem(
isHaveLine: false, leftTitel: TranslationLoader.lanKeys!.automaticBlocking!.tr,
isHaveRightWidget: true, isHaveLine: false,
rightWidget: isHaveRightWidget: true,
SizedBox(width: 60.w, height: 50.h, child: _switch())),), rightWidget:
SizedBox(width: 60.w, height: 50.h, child: _switch())),
),
Visibility( Visibility(
visible: state.isOpen.value == true ? true : false, visible: state.isOpen.value == true,
child: Column( child: Column(
children: [ children: <Widget>[
Container(height: 10.h,), Container(
Builder(builder: (context) { height: 10.h,
),
Builder(builder: (BuildContext context) {
return Obx(() => CommonItem( return Obx(() => CommonItem(
leftTitel: TranslationLoader.lanKeys!.delayTime!.tr, leftTitel: TranslationLoader.lanKeys!.delayTime!.tr,
rightTitle: state.isCustomLockTime.value == true ? "自定义".tr : (state.autoLockTime.value.isNotEmpty && state.autoLockTime.value != "0") ? "${state.autoLockTime}s" : "", rightTitle: state.isCustomLockTime.value == true
? '自定义'.tr
: (state.autoLockTime.value.isNotEmpty &&
state.autoLockTime.value != '0')
? '${state.autoLockTime}s'
: '',
isHaveLine: false, isHaveLine: false,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
if(state.isJustForShow.value == true){ if (state.isJustForShow.value == true) {
return; return;
} }
var list = [ final List<String> list = <String>[
"5", '5',
"10", '10',
"15", '15',
"30", '30',
"60", '60',
TranslationLoader.lanKeys!.custom!.tr TranslationLoader.lanKeys!.custom!.tr
]; ];
ShowBottomSheetTool().showSingleRowPicker( ShowBottomSheetTool().showSingleRowPicker(
// //
context, context,
// //
normalIndex: 0, normalIndex: 0,
title: TranslationLoader.lanKeys!.time!.tr, title: TranslationLoader.lanKeys!.time!.tr,
cancelTitle: TranslationLoader.lanKeys!.cancel!.tr, cancelTitle:
TranslationLoader.lanKeys!.cancel!.tr,
sureTitle: TranslationLoader.lanKeys!.sure!.tr, sureTitle: TranslationLoader.lanKeys!.sure!.tr,
// //
//
//adapter: PickerAdapter(),
data: list, data: list,
// //
clickCallBack: (int index, var str) { clickCallBack: (int index, Object str) {
if(index != 5){ if (index != 5) {
state.isCustomLockTime.value = false; state.isCustomLockTime.value = false;
state.autoLockTime.value = str.toString(); state.autoLockTime.value = str.toString();
}else{ Storage.saveAutomaticLockOffTime(str.toString());
state.isCustomLockTime.value = true; } else {
} state.isCustomLockTime.value = true;
logic.ifCanNext(); }
}); logic.ifCanNext();
});
})); }));
}), }),
Container(height: 10.h), Container(height: 10.h),
@ -122,37 +129,37 @@ class _AutomaticBlockingPageState extends State<AutomaticBlockingPage> with Rout
padding: EdgeInsets.only( padding: EdgeInsets.only(
left: 30.w, top: 10.w, right: 30.w, bottom: 10.w), left: 30.w, top: 10.w, right: 30.w, bottom: 10.w),
child: Column( child: Column(
children: [ children: <Widget>[
Row( Row(
children: [ children: <Widget>[
Text( Text(
"${TranslationLoader.lanKeys!.pleaseEnter!.tr}${TranslationLoader.lanKeys!.time!.tr}(S)", '${TranslationLoader.lanKeys!.pleaseEnter!.tr}${TranslationLoader.lanKeys!.time!.tr}(S)',
style: TextStyle(fontSize: 24.sp), style: TextStyle(fontSize: 24.sp),
), ),
], ],
), ),
Obx(() => TextField( Obx(() => TextField(
// //
maxLines: 1, maxLines: 1,
controller: state.timeController, controller: state.timeController,
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
autofocus: false, autofocus: false,
readOnly: state.isJustForShow.value == true ? true : false, readOnly: state.isJustForShow.value == true,
onChanged: (value) { onChanged: (String value) {
state.autoLockTime.value = value; state.autoLockTime.value = value;
logic.ifCanNext(); logic.ifCanNext();
}, },
decoration: InputDecoration( decoration: InputDecoration(
// //
contentPadding: contentPadding: const EdgeInsets.only(
const EdgeInsets.only(top: 12.0, bottom: 8.0), top: 12.0, bottom: 8.0),
hintText: hintText:
"${TranslationLoader.lanKeys!.pleaseEnter!.tr}${TranslationLoader.lanKeys!.time!.tr}(S)", '${TranslationLoader.lanKeys!.pleaseEnter!.tr}${TranslationLoader.lanKeys!.time!.tr}(S)',
hintStyle: TextStyle(fontSize: 24.sp), hintStyle: TextStyle(fontSize: 24.sp),
//线 //线
border: InputBorder.none, border: InputBorder.none,
), ),
)), )),
Container( Container(
height: 0.5.h, height: 0.5.h,
color: Colors.grey, color: Colors.grey,
@ -167,7 +174,7 @@ class _AutomaticBlockingPageState extends State<AutomaticBlockingPage> with Rout
padding: EdgeInsets.all(30.w), padding: EdgeInsets.all(30.w),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: <Widget>[
Expanded( Expanded(
child: Text( child: Text(
TranslationLoader.lanKeys!.automaticBlockingTip!.tr, TranslationLoader.lanKeys!.automaticBlockingTip!.tr,
@ -186,21 +193,19 @@ class _AutomaticBlockingPageState extends State<AutomaticBlockingPage> with Rout
trackColor: CupertinoColors.systemGrey5, trackColor: CupertinoColors.systemGrey5,
thumbColor: CupertinoColors.white, thumbColor: CupertinoColors.white,
value: state.isOpen.value, value: state.isOpen.value,
onChanged: state.isJustForShow.value == true ? null : (value){ onChanged: state.isJustForShow.value == true
setState(() { ? null
state.isOpen.value = value; : (bool value) {
if(state.isOpen.value == false){ setState(() {
state.autoLockTime.value = ""; state.isOpen.value = value;
} logic.ifCanNext();
logic.ifCanNext(); });
}); },
},
); );
} }
@override @override
void didChangeDependencies() { void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies(); super.didChangeDependencies();
/// ///
@ -209,7 +214,6 @@ class _AutomaticBlockingPageState extends State<AutomaticBlockingPage> with Rout
@override @override
void dispose() { void dispose() {
// TODO: implement dispose
/// ///
AppRouteObserver().routeObserver.unsubscribe(this); AppRouteObserver().routeObserver.unsubscribe(this);
super.dispose(); super.dispose();
@ -227,7 +231,9 @@ class _AutomaticBlockingPageState extends State<AutomaticBlockingPage> with Rout
void didPop() { void didPop() {
super.didPop(); super.didPop();
logic.cancelBlueConnetctToastTimer(); logic.cancelBlueConnetctToastTimer();
if (EasyLoading.isShow) EasyLoading.dismiss(animation: true); if (EasyLoading.isShow) {
EasyLoading.dismiss(animation: true);
}
state.ifCurrentScreen.value = false; state.ifCurrentScreen.value = false;
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
} }
@ -244,9 +250,10 @@ class _AutomaticBlockingPageState extends State<AutomaticBlockingPage> with Rout
void didPushNext() { void didPushNext() {
super.didPushNext(); super.didPushNext();
logic.cancelBlueConnetctToastTimer(); logic.cancelBlueConnetctToastTimer();
if (EasyLoading.isShow) EasyLoading.dismiss(animation: true); if (EasyLoading.isShow) {
EasyLoading.dismiss(animation: true);
}
state.ifCurrentScreen.value = false; state.ifCurrentScreen.value = false;
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
} }
} }

View File

@ -188,7 +188,7 @@ class AdminOpenLockPasswordLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);
List<int> signKeyDataList = changeStringListToIntList(signKey!); List<int> signKeyDataList = changeStringListToIntList(signKey!);

View File

@ -50,7 +50,7 @@ class UploadElectricQuantityLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
dismissEasyLoading(); dismissEasyLoading();

View File

@ -99,7 +99,7 @@ class BurglarAlarmLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -136,7 +136,7 @@ class ConfiguringWifiLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected){ if (connectionState == BluetoothConnectionState.connected){
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -113,7 +113,7 @@ class WifiListLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected){ if (connectionState == BluetoothConnectionState.connected){
var token = await Storage.getStringList(saveBlueToken); var token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); List<int> getTokenList = changeStringListToIntList(token!);

View File

@ -80,7 +80,7 @@ class LockEscalationLogic extends BaseGetXController {
// ota // ota
void blueOTAUpgrade(Map data, List<int> token) { void blueOTAUpgrade(Map data, List<int> token) {
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);

View File

@ -245,7 +245,7 @@ class LockSetLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
showDeletAlertTipDialog(); showDeletAlertTipDialog();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
@ -306,7 +306,7 @@ class LockSetLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: (){
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -103,7 +103,7 @@ class LockSoundSetLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -103,7 +103,7 @@ class LockTimeLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -84,7 +84,7 @@ class MotorPowerLogic extends BaseGetXController {
// - // -
Future<void> _readSupportFunctionsNoParameters() async { Future<void> _readSupportFunctionsNoParameters() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
@ -110,7 +110,7 @@ class MotorPowerLogic extends BaseGetXController {
// () // ()
Future<void> sendOpenDoorDirection() async { Future<void> sendOpenDoorDirection() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -120,7 +120,7 @@ class NormallyOpenModeLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -86,7 +86,7 @@ class OpenDoorDirectionLogic extends BaseGetXController {
// () // ()
Future<void> sendOpenDoorDirection() async { Future<void> sendOpenDoorDirection() async {
showEasyLoading(); showEasyLoading();
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
dismissEasyLoading(); dismissEasyLoading();
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);

View File

@ -109,7 +109,7 @@ class RemoteUnlockingLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState connectionState) async { (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);

View File

@ -98,7 +98,7 @@ class ResetButtonLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);

View File

@ -289,7 +289,7 @@ class UploadDataLogic extends BaseGetXController{
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var token = await Storage.getStringList(saveBlueToken); var token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); List<int> getTokenList = changeStringListToIntList(token!);
@ -334,7 +334,7 @@ class UploadDataLogic extends BaseGetXController{
state.indexCount.value = 0; state.indexCount.value = 0;
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var token = await Storage.getStringList(saveBlueToken); var token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); List<int> getTokenList = changeStringListToIntList(token!);
@ -380,7 +380,7 @@ class UploadDataLogic extends BaseGetXController{
state.indexCount.value = 0; state.indexCount.value = 0;
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var token = await Storage.getStringList(saveBlueToken); var token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); List<int> getTokenList = changeStringListToIntList(token!);
@ -426,7 +426,7 @@ class UploadDataLogic extends BaseGetXController{
state.indexCount.value = 0; state.indexCount.value = 0;
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var token = await Storage.getStringList(saveBlueToken); var token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); List<int> getTokenList = changeStringListToIntList(token!);
@ -473,7 +473,7 @@ class UploadDataLogic extends BaseGetXController{
state.indexCount.value = 0; state.indexCount.value = 0;
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
var token = await Storage.getStringList(saveBlueToken); var token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); List<int> getTokenList = changeStringListToIntList(token!);

View File

@ -1,9 +1,6 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/appRouters.dart';
import 'package:star_lock/app_settings/app_colors.dart';
import 'package:star_lock/main/lockDetail/messageWarn/addFamily/addFamily_state.dart'; import 'package:star_lock/main/lockDetail/messageWarn/addFamily/addFamily_state.dart';
import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/msgNotification/msgNotification_entity.dart';
import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/openDoorNotify/openDoorNotify_entity.dart'; import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/openDoorNotify/openDoorNotify_entity.dart';
import 'package:star_lock/main/lockDetail/messageWarn/notificationMode/notificationMode_data.dart'; import 'package:star_lock/main/lockDetail/messageWarn/notificationMode/notificationMode_data.dart';
import 'package:star_lock/network/api_repository.dart'; import 'package:star_lock/network/api_repository.dart';
@ -13,29 +10,44 @@ class AddFamilyLogic extends BaseGetXController {
final AddFamilyState state = AddFamilyState(); final AddFamilyState state = AddFamilyState();
// //
void addLockNoticeSetting() async { Future<void> addLockNoticeSetting() async {
var entity = await ApiRepository.to.addLockNoticeSetting( final Map<String, Object?> settingValue = <String, Object?>{
'openDoorId': state.lockUserKeys.value.currentOpenDoorID,
'openDoorType': state.lockUserKeys.value.currentKeyType,
'remark': state.lockUserKeys.value.currentKeyName ?? '',
'noticeWay': getNoticeWayList(),
};
final MsgNotificationEntity entity =
await ApiRepository.to.addLockNoticeSetting(
lockId: state.getLockId.value, lockId: state.getLockId.value,
noticeType: 10, noticeType: 10,
settingValue: { settingValue: settingValue,
'openDoorId': state.lockUserKeys.value.currentOpenDoorID,
'openDoorType': state.lockUserKeys.value.currentKeyType,
'remark': state.lockUserKeys.value.currentKeyName ?? '',
'noticeWay': [
{'type': 'mail', 'accounts': getEmailAndSMSAccountList(true)},
{'type': 'sms', 'accounts': getEmailAndSMSAccountList(false)}
]
},
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
showToast('添加成功'.tr); showToast('添加成功'.tr);
Get.back(result: true); Get.back(result: true);
} }
} }
List<Map<String, Object>> getNoticeWayList() {
return <Map<String, Object>>[
<String, Object>{
'type': 'mail',
'accounts': getEmailAndSMSAccountList(true)
},
<String, Object>{
'type': 'sms',
'accounts': getEmailAndSMSAccountList(false)
},
];
}
// //
void updateLockNoticeSetting() async { Future<void> updateLockNoticeSetting() async {
var entity = await ApiRepository.to.updateLockNoticeSettingAccount( final OpenDoorNotifyEntity entity =
await ApiRepository.to.updateLockNoticeSettingAccount(
lockNoticeSettingAccountId: state.familyData.value.id!, lockNoticeSettingAccountId: state.familyData.value.id!,
settingValue: { settingValue: {
'openDoorId': state.familyData.value.settingValue!.openDoorId!, 'openDoorId': state.familyData.value.settingValue!.openDoorId!,
@ -52,8 +64,9 @@ class AddFamilyLogic extends BaseGetXController {
} }
// //
void deleteLockNoticeSetting() async { Future<void> deleteLockNoticeSetting() async {
var entity = await ApiRepository.to.deleteLockNoticeSettingAccount( final OpenDoorNotifyEntity entity =
await ApiRepository.to.deleteLockNoticeSettingAccount(
lockNoticeSettingAccountId: state.familyData.value.id!, lockNoticeSettingAccountId: state.familyData.value.id!,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
@ -64,14 +77,14 @@ class AddFamilyLogic extends BaseGetXController {
// //
List getEmailAndSMSAccountList(bool isEmail) { List getEmailAndSMSAccountList(bool isEmail) {
List list = []; final List list = [];
List accountList = []; List accountList = [];
isEmail isEmail
? accountList = state.emailReceiverList.value ? accountList = state.emailReceiverList.value
: accountList = state.phoneReceiverList.value; : accountList = state.phoneReceiverList.value;
for (int i = 0; i < accountList.length; i++) { for (int i = 0; i < accountList.length; i++) {
MsgNoticeModeData item = accountList[i]; final MsgNoticeModeData item = accountList[i];
Map map = {}; final Map map = {};
map['countryCode'] = isEmail ? 0 : item.countryCode; map['countryCode'] = isEmail ? 0 : item.countryCode;
map['account'] = isEmail ? item.receiveEmail : item.receivePhone; map['account'] = isEmail ? item.receiveEmail : item.receivePhone;
list.add(map); list.add(map);
@ -83,9 +96,9 @@ class AddFamilyLogic extends BaseGetXController {
String emailListStr = ''; String emailListStr = '';
if (val['emailReceiverList'] != null) { if (val['emailReceiverList'] != null) {
state.emailReceiverList.value = val['emailReceiverList']; state.emailReceiverList.value = val['emailReceiverList'];
List emailReceiverList = state.emailReceiverList.value; final List emailReceiverList = state.emailReceiverList.value;
for (int i = 0; i < emailReceiverList.length; i++) { for (int i = 0; i < emailReceiverList.length; i++) {
MsgNoticeModeData item = emailReceiverList[i]; final MsgNoticeModeData item = emailReceiverList[i];
emailListStr += item.receiveEmail; emailListStr += item.receiveEmail;
// //
if (i < emailReceiverList.length - 1) { if (i < emailReceiverList.length - 1) {
@ -101,9 +114,9 @@ class AddFamilyLogic extends BaseGetXController {
if (val['phoneReceiverList'] != null) { if (val['phoneReceiverList'] != null) {
state.phoneReceiverList.value = val['phoneReceiverList']; state.phoneReceiverList.value = val['phoneReceiverList'];
List phoneReceiverList = state.phoneReceiverList.value; final List phoneReceiverList = state.phoneReceiverList.value;
for (int i = 0; i < phoneReceiverList.length; i++) { for (int i = 0; i < phoneReceiverList.length; i++) {
MsgNoticeModeData item = phoneReceiverList[i]; final MsgNoticeModeData item = phoneReceiverList[i];
phoneListStr += item.receivePhone; phoneListStr += item.receivePhone;
// //
if (i < phoneReceiverList.length - 1) { if (i < phoneReceiverList.length - 1) {
@ -116,19 +129,19 @@ class AddFamilyLogic extends BaseGetXController {
// //
bool checkBtnDisable() { bool checkBtnDisable() {
if ((state.emailListStr.value.isEmpty || final String? keyTypeStr = state.lockUserKeys.value.currentKeyTypeStr;
state.phontListStr.value.isEmpty) || final String? keyName = state.lockUserKeys.value.currentKeyName;
state.lockUserKeys.value.currentKeyTypeStr!.isEmpty ||
state.lockUserKeys.value.currentKeyName!.isEmpty) { if (keyTypeStr == null || keyName == null) {
return false; return false;
} else {
return true;
} }
return keyTypeStr.isNotEmpty && keyName.isNotEmpty;
} }
// 1: 2: 3: 4: 5: // 1: 2: 3: 4: 5:
String getKeyTypeStr() { String getKeyTypeStr() {
int keyType = state.familyData.value.settingValue!.openDoorType!; final int keyType = state.familyData.value.settingValue!.openDoorType!;
switch (keyType) { switch (keyType) {
case 1: case 1:
return '电子钥匙'; return '电子钥匙';
@ -147,34 +160,32 @@ class AddFamilyLogic extends BaseGetXController {
// //
Map<String, List<MsgNoticeModeData>> getAccountsMap() { Map<String, List<MsgNoticeModeData>> getAccountsMap() {
List<MsgNoticeModeData> mailAccounts = []; final List<MsgNoticeModeData> mailAccounts = <MsgNoticeModeData>[];
List<MsgNoticeModeData> smsAccounts = []; final List<MsgNoticeModeData> smsAccounts = <MsgNoticeModeData>[];
if (state.familyData.value.settingValue != null) { state.familyData.value.settingValue?.noticeWayList
for (NoticeWay item ?.forEach((NoticeWay item) {
in state.familyData.value.settingValue!.noticeWayList!) { if (item.type == 'mail') {
if (item.type == 'mail' && item.accounts != null) { item.accounts?.forEach((Accounts account) {
for (Accounts account in item.accounts!) { if (account.account != null) {
if (account.account != null) { final MsgNoticeModeData msgNoticeModeData = MsgNoticeModeData();
MsgNoticeModeData msgNoticeModeData = MsgNoticeModeData(); msgNoticeModeData.receiveEmail = account.account!;
msgNoticeModeData.receiveEmail = account.account!; mailAccounts.add(msgNoticeModeData);
mailAccounts.add(msgNoticeModeData);
}
} }
} else if (item.type == 'sms' && item.accounts != null) { });
for (Accounts account in item.accounts!) { } else if (item.type == 'sms') {
if (account.account != null && account.countryCode != null) { item.accounts?.forEach((Accounts account) {
MsgNoticeModeData msgNoticeModeData = MsgNoticeModeData(); if (account.account != null && account.countryCode != null) {
msgNoticeModeData.receivePhone = account.account!; final MsgNoticeModeData msgNoticeModeData = MsgNoticeModeData();
msgNoticeModeData.countryCode = account.countryCode!; msgNoticeModeData.receivePhone = account.account!;
smsAccounts.add(msgNoticeModeData); msgNoticeModeData.countryCode = account.countryCode!;
} smsAccounts.add(msgNoticeModeData);
} }
} });
} }
} });
return { return <String, List<MsgNoticeModeData>>{
'emailReceiverList': mailAccounts, 'emailReceiverList': mailAccounts,
'phoneReceiverList': smsAccounts, 'phoneReceiverList': smsAccounts,
}; };

View File

@ -4,8 +4,10 @@ import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/appRouters.dart'; import 'package:star_lock/appRouters.dart';
import 'package:star_lock/main/lockDetail/messageWarn/addFamily/addFamily_logic.dart'; import 'package:star_lock/main/lockDetail/messageWarn/addFamily/addFamily_logic.dart';
import 'package:star_lock/tools/showCupertinoAlertView.dart'; import 'package:star_lock/main/lockDetail/messageWarn/addFamily/addFamily_state.dart';
import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/openDoorNotify/openDoorNotify_entity.dart';
import 'package:star_lock/tools/commonItem.dart'; import 'package:star_lock/tools/commonItem.dart';
import 'package:star_lock/tools/showCupertinoAlertView.dart';
import 'package:star_lock/tools/showTFView.dart'; import 'package:star_lock/tools/showTFView.dart';
import 'package:star_lock/tools/storage.dart'; import 'package:star_lock/tools/storage.dart';
import 'package:star_lock/tools/submitBtn.dart'; import 'package:star_lock/tools/submitBtn.dart';
@ -22,8 +24,8 @@ class AddFamilyPage extends StatefulWidget {
} }
class _AddFamilyPageState extends State<AddFamilyPage> { class _AddFamilyPageState extends State<AddFamilyPage> {
final logic = Get.put(AddFamilyLogic()); final AddFamilyLogic logic = Get.put(AddFamilyLogic());
final state = Get.find<AddFamilyLogic>().state; final AddFamilyState state = Get.find<AddFamilyLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -36,7 +38,7 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
body: Container( body: Container(
padding: EdgeInsets.all(30.w), padding: EdgeInsets.all(30.w),
child: Column( child: Column(
children: [ children: <Widget>[
Obx(() => CommonItem( Obx(() => CommonItem(
leftTitel: '开门方式'.tr, leftTitel: '开门方式'.tr,
rightTitle: state.isDetail.value rightTitle: state.isDetail.value
@ -46,9 +48,9 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
// //
Get.toNamed(Routers.lockUserPage, Get.toNamed(Routers.lockUserPage, arguments: <String, int>{
arguments: {'getLockId': state.getLockId.value}) 'getLockId': state.getLockId.value
?.then((val) { })?.then((val) {
if (val != null) { if (val != null) {
state.lockUserKeys.value = val; state.lockUserKeys.value = val;
} }
@ -73,8 +75,9 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
GestureDetector( GestureDetector(
onTap: () { onTap: () {
Get.toNamed(Routers.notificationModePage, Get.toNamed(Routers.notificationModePage,
arguments: {'familyData': state.familyData.value}) arguments: <String, DataList>{
?.then((val) { 'familyData': state.familyData.value
})?.then((val) {
if (val != null) { if (val != null) {
state.emailListStr.value = logic.getEmailListStr(val); state.emailListStr.value = logic.getEmailListStr(val);
state.phontListStr.value = logic.getPhoneListStr(val); state.phontListStr.value = logic.getPhoneListStr(val);
@ -85,10 +88,10 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
color: Colors.white, color: Colors.white,
margin: EdgeInsets.only(bottom: 10.h), margin: EdgeInsets.only(bottom: 10.h),
child: Column( child: Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: '提醒方式'.tr, leftTitel: '提醒方式'.tr,
rightTitle: "", rightTitle: '',
isHaveLine: false, isHaveLine: false,
isHaveRightWidget: false, isHaveRightWidget: false,
isHaveDirection: true, isHaveDirection: true,
@ -117,7 +120,7 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
: logic.checkBtnDisable(), : logic.checkBtnDisable(),
isDelete: state.isDetail.value, isDelete: state.isDetail.value,
onClick: () async { onClick: () async {
var isVip = await Storage.getBool(saveIsVip); final bool? isVip = await Storage.getBool(saveIsVip);
if (isVip == true) { if (isVip == true) {
if (state.isDetail.value) { if (state.isDetail.value) {
logic.deleteLockNoticeSetting(); logic.deleteLockNoticeSetting();
@ -148,7 +151,7 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
borderRadius: BorderRadius.circular(6.0.w), borderRadius: BorderRadius.circular(6.0.w),
), ),
child: Row( child: Row(
children: [ children: <Widget>[
Text( Text(
notifyTitle, notifyTitle,
style: TextStyle(color: Colors.black, fontSize: 20.sp), style: TextStyle(color: Colors.black, fontSize: 20.sp),
@ -173,8 +176,8 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
builder: (BuildContext context) { builder: (BuildContext context) {
return ShowTFView( return ShowTFView(
title: title:
"${TranslationLoader.lanKeys!.amend!.tr}${TranslationLoader.lanKeys!.name!.tr}", '${TranslationLoader.lanKeys!.amend!.tr}${TranslationLoader.lanKeys!.name!.tr}',
tipTitle: "请输入".tr, tipTitle: '请输入'.tr,
controller: state.changeNameController, controller: state.changeNameController,
sureClick: () { sureClick: () {
// //
@ -194,13 +197,13 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
// //
Widget getFamilyWidget(String tfStr) { Widget getFamilyWidget(String tfStr) {
TextEditingController emailController = TextEditingController(); final TextEditingController emailController = TextEditingController();
emailController.text = state.lockUserKeys.value.currentKeyName ?? ''; emailController.text = state.lockUserKeys.value.currentKeyName ?? '';
return SizedBox( return SizedBox(
height: 50.h, height: 50.h,
width: 360.w, width: 360.w,
child: Row( child: Row(
children: [ children: <Widget>[
Expanded( Expanded(
child: TextField( child: TextField(
controller: emailController, controller: emailController,
@ -231,7 +234,7 @@ class _AddFamilyPageState extends State<AddFamilyPage> {
), ),
style: TextStyle( style: TextStyle(
fontSize: 22.sp, textBaseline: TextBaseline.alphabetic), fontSize: 22.sp, textBaseline: TextBaseline.alphabetic),
onChanged: (value) { onChanged: (String value) {
state.lockUserKeys.value.currentKeyName = value; state.lockUserKeys.value.currentKeyName = value;
state.lockUserKeys.refresh(); state.lockUserKeys.refresh();
}, },

View File

@ -5,9 +5,9 @@ import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/openDoorNo
class AddFamilyState { class AddFamilyState {
final TextEditingController changeNameController = TextEditingController(); final TextEditingController changeNameController = TextEditingController();
var getLockId = 0.obs; RxInt getLockId = 0.obs;
var lockUserKeys = LockUserListKeys().obs; Rx<LockUserListKeys> lockUserKeys = LockUserListKeys().obs;
var emailReceiverList = [].obs; RxList emailReceiverList = [].obs;
var phoneReceiverList = [].obs; var phoneReceiverList = [].obs;
var emailListStr = ''.obs; var emailListStr = ''.obs;
var phontListStr = ''.obs; var phontListStr = ''.obs;

View File

@ -9,8 +9,9 @@ class CoerceFingerprintListLogic extends BaseGetXController {
final CoerceFingerprintListState state = CoerceFingerprintListState(); final CoerceFingerprintListState state = CoerceFingerprintListState();
// //
void getCoercedFingerprintList() async { Future<void> getCoercedFingerprintList() async {
var entity = await ApiRepository.to.getCoercedFingerprintList( final CoerceFingerprintListEntity entity =
await ApiRepository.to.getCoercedFingerprintList(
lockId: state.getLockId.value, lockId: state.getLockId.value,
pageNo: state.pageNum.value, pageNo: state.pageNum.value,
pageSize: state.pageSize.value, pageSize: state.pageSize.value,
@ -24,15 +25,15 @@ class CoerceFingerprintListLogic extends BaseGetXController {
// //
String getfingerprintUseDateStr( String getfingerprintUseDateStr(
CoerceFingerprintItemData fingerprintItemData) { CoerceFingerprintItemData fingerprintItemData) {
var keyDateTypeStr = ""; // :1;23:4 var keyDateTypeStr = ''; // :1;23:4
if (fingerprintItemData.fingerprintType! == 1) { if (fingerprintItemData.fingerprintType! == 1) {
keyDateTypeStr = "永久".tr; keyDateTypeStr = '永久'.tr;
} else if (fingerprintItemData.fingerprintType! == 2) { } else if (fingerprintItemData.fingerprintType! == 2) {
keyDateTypeStr = keyDateTypeStr =
"${DateTool().dateToYMDHNString(fingerprintItemData.startDate.toString())} - ${DateTool().dateToYMDHNString(fingerprintItemData.endDate.toString())} 限时"; '${DateTool().dateToYMDHNString(fingerprintItemData.startDate.toString())} - ${DateTool().dateToYMDHNString(fingerprintItemData.endDate.toString())} 限时';
} else if (fingerprintItemData.fingerprintType! == 4) { } else if (fingerprintItemData.fingerprintType! == 4) {
keyDateTypeStr = keyDateTypeStr =
"${DateTool().dateToYMDString(fingerprintItemData.startDate.toString())}-${DateTool().dateToYMDString(fingerprintItemData.endDate.toString())} 循环"; '${DateTool().dateToYMDString(fingerprintItemData.startDate.toString())}-${DateTool().dateToYMDString(fingerprintItemData.endDate.toString())} 循环';
} }
return keyDateTypeStr; return keyDateTypeStr;
} }

View File

@ -3,6 +3,7 @@ import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/coerceOpenDoor/coerceFingerprintList/coerceFingerprintList_entity.dart'; import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/coerceOpenDoor/coerceFingerprintList/coerceFingerprintList_entity.dart';
import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/coerceOpenDoor/coerceFingerprintList/coerceFingerprintList_logic.dart'; import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/coerceOpenDoor/coerceFingerprintList/coerceFingerprintList_logic.dart';
import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/coerceOpenDoor/coerceFingerprintList/coerceFingerprintList_state.dart';
import 'package:star_lock/tools/keySearchWidget.dart'; import 'package:star_lock/tools/keySearchWidget.dart';
import '../../../../../../app_settings/app_colors.dart'; import '../../../../../../app_settings/app_colors.dart';
@ -18,8 +19,10 @@ class CoerceFingerprintListPage extends StatefulWidget {
} }
class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> { class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> {
final logic = Get.put(CoerceFingerprintListLogic()); final CoerceFingerprintListLogic logic =
final state = Get.find<CoerceFingerprintListLogic>().state; Get.put(CoerceFingerprintListLogic());
final CoerceFingerprintListState state =
Get.find<CoerceFingerprintListLogic>().state;
@override @override
initState() { initState() {
@ -37,7 +40,7 @@ class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> {
backgroundColor: AppColors.mainColor, backgroundColor: AppColors.mainColor,
), ),
body: Column( body: Column(
children: [ children: <Widget>[
KeySearchWidget( KeySearchWidget(
editingController: state.searchController, editingController: state.searchController,
onSubmittedAction: () { onSubmittedAction: () {
@ -48,7 +51,7 @@ class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> {
SizedBox( SizedBox(
height: 20.h, height: 20.h,
), ),
Expanded(child: Obx(() => _buildMainUI())), Expanded(child: Obx(_buildMainUI)),
SubmitBtn( SubmitBtn(
btnName: '确定'.tr, btnName: '确定'.tr,
onClick: () { onClick: () {
@ -68,7 +71,7 @@ class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> {
return ListView.separated( return ListView.separated(
shrinkWrap: true, shrinkWrap: true,
itemCount: state.fingerprintList.length, itemCount: state.fingerprintList.length,
itemBuilder: (c, index) { itemBuilder: (BuildContext c, int index) {
return _electronicKeyItem(state.fingerprintList[index], index); return _electronicKeyItem(state.fingerprintList[index], index);
}, },
separatorBuilder: (BuildContext context, int index) { separatorBuilder: (BuildContext context, int index) {
@ -85,7 +88,7 @@ class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> {
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
for (int i = 0; i < state.fingerprintList.value.length; i++) { for (int i = 0; i < state.fingerprintList.value.length; i++) {
CoerceFingerprintItemData item = state.fingerprintList.value[i]; final CoerceFingerprintItemData item = state.fingerprintList.value[i];
if (selectIndex == i) { if (selectIndex == i) {
item.isCurrentSelect = true; item.isCurrentSelect = true;
} else { } else {
@ -100,7 +103,7 @@ class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> {
color: Colors.white, color: Colors.white,
height: 90.h, height: 90.h,
child: Row( child: Row(
children: [ children: <Widget>[
SizedBox( SizedBox(
width: 30.w, width: 30.w,
), ),
@ -115,9 +118,9 @@ class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> {
Expanded( Expanded(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Row( Row(
children: [ children: <Widget>[
Text( Text(
itemData.fingerprintName ?? '', itemData.fingerprintName ?? '',
style: TextStyle( style: TextStyle(
@ -133,7 +136,7 @@ class _CoerceFingerprintListPageState extends State<CoerceFingerprintListPage> {
SizedBox(height: 10.h), SizedBox(height: 10.h),
Row( Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: <Widget>[
Text( Text(
logic.getfingerprintUseDateStr(itemData), logic.getfingerprintUseDateStr(itemData),
style: TextStyle( style: TextStyle(

View File

@ -9,12 +9,13 @@ import 'nDaysUnopened_state.dart';
class NDaysUnopenedLogic extends BaseGetXController { class NDaysUnopenedLogic extends BaseGetXController {
NDaysUnopenedState state = NDaysUnopenedState(); NDaysUnopenedState state = NDaysUnopenedState();
void lockNoticeSettingAccountList() async { Future<void> lockNoticeSettingAccountList() async {
var entity = await ApiRepository.to.updateNdaysNotCloseDoorNoticeSetting( final OpenDoorNotifyEntity entity = await ApiRepository.to
lockId: state.getLockId.value, .updateNdaysNotCloseDoorNoticeSetting(
dayNotOpenDoorState: state.isUnOpenNotice.value == true ? 1 : 0, lockId: state.getLockId.value,
dayNotOpenDoorValue: state.unOpenDoorTime.value, dayNotOpenDoorState: state.isUnOpenNotice.value == true ? 1 : 0,
dayNotOpenDoorNoticeWayList: [ dayNotOpenDoorValue: state.unOpenDoorTime.value,
dayNotOpenDoorNoticeWayList: [
{'type': 'mail', 'accounts': getEmailAndSMSAccountList(true)}, {'type': 'mail', 'accounts': getEmailAndSMSAccountList(true)},
{'type': 'sms', 'accounts': getEmailAndSMSAccountList(false)} {'type': 'sms', 'accounts': getEmailAndSMSAccountList(false)}
]); ]);
@ -26,14 +27,14 @@ class NDaysUnopenedLogic extends BaseGetXController {
// //
List getEmailAndSMSAccountList(bool isEmail) { List getEmailAndSMSAccountList(bool isEmail) {
List list = []; final List list = [];
List accountList = []; List accountList = [];
isEmail isEmail
? accountList = state.emailReceiverList.value ? accountList = state.emailReceiverList.value
: accountList = state.phoneReceiverList.value; : accountList = state.phoneReceiverList.value;
for (int i = 0; i < accountList.length; i++) { for (int i = 0; i < accountList.length; i++) {
MsgNoticeModeData item = accountList[i]; final MsgNoticeModeData item = accountList[i];
Map map = {}; final Map map = {};
map['countryCode'] = isEmail ? 0 : item.countryCode; map['countryCode'] = isEmail ? 0 : item.countryCode;
map['account'] = isEmail ? item.receiveEmail : item.receivePhone; map['account'] = isEmail ? item.receiveEmail : item.receivePhone;
list.add(map); list.add(map);
@ -45,9 +46,9 @@ class NDaysUnopenedLogic extends BaseGetXController {
String emailListStr = ''; String emailListStr = '';
if (val['emailReceiverList'] != null) { if (val['emailReceiverList'] != null) {
state.emailReceiverList.value = val['emailReceiverList']; state.emailReceiverList.value = val['emailReceiverList'];
List emailReceiverList = state.emailReceiverList.value; final List emailReceiverList = state.emailReceiverList.value;
for (int i = 0; i < emailReceiverList.length; i++) { for (int i = 0; i < emailReceiverList.length; i++) {
MsgNoticeModeData item = emailReceiverList[i]; final MsgNoticeModeData item = emailReceiverList[i];
emailListStr += item.receiveEmail; emailListStr += item.receiveEmail;
// //
if (i < emailReceiverList.length - 1) { if (i < emailReceiverList.length - 1) {
@ -63,9 +64,9 @@ class NDaysUnopenedLogic extends BaseGetXController {
if (val['phoneReceiverList'] != null) { if (val['phoneReceiverList'] != null) {
state.phoneReceiverList.value = val['phoneReceiverList']; state.phoneReceiverList.value = val['phoneReceiverList'];
List phoneReceiverList = state.phoneReceiverList.value; final List phoneReceiverList = state.phoneReceiverList.value;
for (int i = 0; i < phoneReceiverList.length; i++) { for (int i = 0; i < phoneReceiverList.length; i++) {
MsgNoticeModeData item = phoneReceiverList[i]; final MsgNoticeModeData item = phoneReceiverList[i];
phoneListStr += item.receivePhone; phoneListStr += item.receivePhone;
// //
if (i < phoneReceiverList.length - 1) { if (i < phoneReceiverList.length - 1) {
@ -78,24 +79,24 @@ class NDaysUnopenedLogic extends BaseGetXController {
// //
Map<String, List<MsgNoticeModeData>> getAccountsMap() { Map<String, List<MsgNoticeModeData>> getAccountsMap() {
List<MsgNoticeModeData> mailAccounts = []; final List<MsgNoticeModeData> mailAccounts = [];
List<MsgNoticeModeData> smsAccounts = []; final List<MsgNoticeModeData> smsAccounts = [];
if (state.msgNoticeInfo.value.dayNotOpenDoorNoticeWayList != null) { if (state.msgNoticeInfo.value.dayNotOpenDoorNoticeWayList != null) {
for (NoticeWay item for (final NoticeWay item
in state.msgNoticeInfo.value.dayNotOpenDoorNoticeWayList!) { in state.msgNoticeInfo.value.dayNotOpenDoorNoticeWayList!) {
if (item.type == 'mail' && item.accounts != null) { if (item.type == 'mail' && item.accounts != null) {
for (Accounts account in item.accounts!) { for (final Accounts account in item.accounts!) {
if (account.account != null) { if (account.account != null) {
MsgNoticeModeData msgNoticeModeData = MsgNoticeModeData(); final MsgNoticeModeData msgNoticeModeData = MsgNoticeModeData();
msgNoticeModeData.receiveEmail = account.account!; msgNoticeModeData.receiveEmail = account.account!;
mailAccounts.add(msgNoticeModeData); mailAccounts.add(msgNoticeModeData);
} }
} }
} else if (item.type == 'sms' && item.accounts != null) { } else if (item.type == 'sms' && item.accounts != null) {
for (Accounts account in item.accounts!) { for (final Accounts account in item.accounts!) {
if (account.account != null && account.countryCode != null) { if (account.account != null && account.countryCode != null) {
MsgNoticeModeData msgNoticeModeData = MsgNoticeModeData(); final MsgNoticeModeData msgNoticeModeData = MsgNoticeModeData();
msgNoticeModeData.receivePhone = account.account!; msgNoticeModeData.receivePhone = account.account!;
msgNoticeModeData.countryCode = account.countryCode!; msgNoticeModeData.countryCode = account.countryCode!;
smsAccounts.add(msgNoticeModeData); smsAccounts.add(msgNoticeModeData);

View File

@ -3,11 +3,13 @@ import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/appRouters.dart'; import 'package:star_lock/appRouters.dart';
import 'package:star_lock/app_settings/app_settings.dart';
import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/msgNotification/msgNotification_entity.dart'; import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/msgNotification/msgNotification_entity.dart';
import 'package:star_lock/tools/showCupertinoAlertView.dart'; import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/nDaysUnopened/nDaysUnopened_state.dart';
import 'package:star_lock/tools/commonItem.dart'; import 'package:star_lock/tools/commonItem.dart';
import 'package:star_lock/tools/pickers/pickers.dart'; import 'package:star_lock/tools/pickers/pickers.dart';
import 'package:star_lock/tools/pickers/style/default_style.dart'; import 'package:star_lock/tools/pickers/style/default_style.dart';
import 'package:star_lock/tools/showCupertinoAlertView.dart';
import 'package:star_lock/tools/storage.dart'; import 'package:star_lock/tools/storage.dart';
import 'package:star_lock/tools/submitBtn.dart'; import 'package:star_lock/tools/submitBtn.dart';
@ -23,147 +25,138 @@ class NDaysUnopenedPage extends StatefulWidget {
} }
class _NDaysUnopenedPageState extends State<NDaysUnopenedPage> { class _NDaysUnopenedPageState extends State<NDaysUnopenedPage> {
final logic = Get.put(NDaysUnopenedLogic()); final NDaysUnopenedLogic logic = Get.put(NDaysUnopenedLogic());
final state = Get.find<NDaysUnopenedLogic>().state; final NDaysUnopenedState state = Get.find<NDaysUnopenedLogic>().state;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
backgroundColor: AppColors.mainBackgroundColor, backgroundColor: AppColors.mainBackgroundColor,
appBar: TitleAppBar( appBar: TitleAppBar(
barTitle: 'N天未开门'.tr, barTitle: 'N天未开门'.tr,
haveBack: true, haveBack: true,
backgroundColor: AppColors.mainColor), backgroundColor: AppColors.mainColor,
body: ListView( ),
body: Padding(
padding: EdgeInsets.all(30.w), padding: EdgeInsets.all(30.w),
children: [ child: Column(
Row( children: <Widget>[
mainAxisAlignment: MainAxisAlignment.start, Row(
children: [ mainAxisAlignment: MainAxisAlignment.start,
Expanded( children: <Widget>[
Expanded(
child: Text( child: Text(
"经过以上设定的时间,锁没有被开启,系统会给指定对象发送提醒消息,该功能需要锁联网".tr, '经过以上设定的时间,锁没有被开启,系统会给指定对象发送提醒消息,该功能需要锁联网'.tr,
style: TextStyle( style: TextStyle(
fontSize: 20.sp, color: AppColors.darkGrayTextColor), fontSize: 20.sp, color: AppColors.darkGrayTextColor),
)), ),
], ),
), ],
SizedBox( ),
height: 20.h, SizedBox(height: 20.h),
), CommonItem(
CommonItem(
leftTitel: 'N天未开门提醒'.tr, leftTitel: 'N天未开门提醒'.tr,
rightTitle: '', rightTitle: '',
isHaveLine: true, isHaveLine: true,
isHaveDirection: false, isHaveDirection: false,
isHaveRightWidget: true, isHaveRightWidget: true,
rightWidget: _unOpenDoorSwitch(), rightWidget: Obx(_unOpenDoorSwitch),
action: () {}), ),
_buildOpenNoticeWidget(), Obx(_buildOpenNoticeWidget),
Expanded( Expanded(child: Container()),
child: SizedBox( SubmitBtn(
height: 20.h, btnName: '保存'.tr,
)), onClick: () async {
SubmitBtn( final bool? isVip = await Storage.getBool(saveIsVip);
btnName: '保存'.tr, if (isVip == false) {
onClick: () async { ShowCupertinoAlertView().advancedFeatureAlert();
var isVip = await Storage.getBool(saveIsVip); } else {
if (isVip == false) { logic.lockNoticeSettingAccountList();
ShowCupertinoAlertView().advancedFeatureAlert(); }
} else { },
logic.lockNoticeSettingAccountList(); ),
} SizedBox(height: 60.h),
}, ],
), ),
SizedBox(
height: 60.h,
)
],
), ),
); );
} }
Widget _buildOpenNoticeWidget() { Widget _buildOpenNoticeWidget() {
return Visibility( return Visibility(
visible: state.isUnOpenNotice.value, visible: state.isUnOpenNotice.value,
child: Column( child: Column(
children: [ children: <Widget>[
Obx(() => CommonItem( CommonItem(
leftTitel: '门未开时间'.tr, leftTitel: '门未开时间'.tr,
rightTitle: '${state.unOpenDoorTime.value}${''.tr}', rightTitle: '${state.unOpenDoorTime.value}',
isHaveLine: true, isHaveLine: true,
isHaveRightWidget: false, isHaveRightWidget: false,
isHaveDirection: true, isHaveDirection: true,
action: () { action: () {
_openBottomItemSheet(context, state.unopenDoorTimeList); _openBottomItemSheet(context, state.unopenDoorTimeList);
}, },
)), ),
SizedBox( SizedBox(height: 20.h),
height: 20.h, GestureDetector(
), onTap: () {
GestureDetector( Get.toNamed(Routers.notificationModePage,
onTap: () { arguments: <String, MsgNoticeData>{
Get.toNamed(Routers.notificationModePage, 'msgNoticeInfo': state.msgNoticeInfo.value
arguments: {'msgNoticeInfo': state.msgNoticeInfo.value}) })?.then((val) {
?.then((val) { if (val != null) {
if (val != null) { state.emailListStr.value = logic.getEmailListStr(val);
state.emailListStr.value = logic.getEmailListStr(val); state.phontListStr.value = logic.getPhoneListStr(val);
state.phontListStr.value = logic.getPhoneListStr(val); }
} });
}); },
}, child: Container(
child: Container( color: Colors.white,
color: Colors.white, margin: EdgeInsets.only(bottom: 10.h),
margin: EdgeInsets.only(bottom: 10.h), child: Column(
child: Column( children: <Widget>[
children: [ CommonItem(
CommonItem( leftTitel: '提醒方式'.tr,
leftTitel: '提醒方式'.tr, rightTitle: '',
rightTitle: "", isHaveLine: false,
isHaveLine: false, isHaveRightWidget: false,
isHaveRightWidget: false, isHaveDirection: true,
isHaveDirection: true, ),
), _buildNotifyContain('APP推送'.tr, '管理员'.tr),
_buildNotifyContain('APP推送'.tr, '管理员'.tr), if (state.emailListStr.value.isNotEmpty)
Obx(() => state.emailListStr.value.isNotEmpty _buildNotifyContain('邮件提醒'.tr, state.emailListStr.value),
? _buildNotifyContain( if (state.phontListStr.value.isNotEmpty)
'邮件提醒'.tr, state.emailListStr.value) _buildNotifyContain('短信提醒'.tr, state.phontListStr.value),
: Container()), ],
Obx(() => state.phontListStr.value.isNotEmpty
? _buildNotifyContain(
'短信提醒'.tr, state.phontListStr.value)
: Container()),
],
),
), ),
), ),
], ),
)); ],
),
);
} }
Widget _buildNotifyContain(String notifyTitle, String notifyContent) { Widget _buildNotifyContain(String notifyTitle, String notifyContent) {
return Container( return Container(
padding: padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 12.h),
EdgeInsets.only(left: 10.w, right: 10.w, top: 12.h, bottom: 12.h), margin: EdgeInsets.symmetric(vertical: 10.h, horizontal: 20.w),
margin: EdgeInsets.only(bottom: 20.h, top: 10.h, left: 20.w, right: 20.w),
decoration: BoxDecoration( decoration: BoxDecoration(
color: AppColors.mainBackgroundColor, color: AppColors.mainBackgroundColor,
borderRadius: BorderRadius.circular(6.0.w), borderRadius: BorderRadius.circular(6.0.w),
), ),
child: Row( child: Row(
children: [ children: <Widget>[
Text( Text(
notifyTitle, notifyTitle,
style: TextStyle(color: Colors.black, fontSize: 20.sp), style: TextStyle(color: Colors.black, fontSize: 20.sp),
), ),
Expanded( Expanded(child: Container()),
child: SizedBox( Text(
width: 20.w, notifyContent,
)), textAlign: TextAlign.end,
Text(notifyContent, style: TextStyle(
textAlign: TextAlign.end, color: AppColors.placeholderTextColor, fontSize: 20.sp),
style: TextStyle( ),
color: AppColors.placeholderTextColor, fontSize: 20.sp)),
], ],
), ),
); );
@ -175,23 +168,22 @@ class _NDaysUnopenedPageState extends State<NDaysUnopenedPage> {
trackColor: CupertinoColors.systemGrey5, trackColor: CupertinoColors.systemGrey5,
thumbColor: CupertinoColors.white, thumbColor: CupertinoColors.white,
value: state.isUnOpenNotice.value, value: state.isUnOpenNotice.value,
onChanged: (value) { onChanged: (bool value) {
setState(() { state.isUnOpenNotice.value = value;
state.isUnOpenNotice.value = value; if (!state.isUnOpenNotice.value) {
if (!state.isUnOpenNotice.value) { state.msgNoticeInfo.value = MsgNoticeData();
state.msgNoticeInfo.value = MsgNoticeData(); }
}
});
}, },
); );
} }
//pickerView // pickerView
_openBottomItemSheet(BuildContext context, List dataList) { void _openBottomItemSheet(BuildContext context, List dataList) {
Pickers.showSinglePicker(context, Pickers.showSinglePicker(context,
data: dataList, data: dataList,
pickerStyle: DefaultPickerStyle(), onConfirm: (p, position) { pickerStyle: DefaultPickerStyle(), onConfirm: (p, int position) {
state.unOpenDoorTime.value = p; state.unOpenDoorTime.value =
}, onChanged: (p, position) {}); int.parse(state.unopenDoorTimeList[position].replaceAll('', ''));
});
} }
} }

View File

@ -4,25 +4,25 @@ import 'package:star_lock/main/lockDetail/messageWarn/msgNotification/msgNotific
class NDaysUnopenedState { class NDaysUnopenedState {
final List unopenDoorTimeList = [ final List unopenDoorTimeList = [
1, '1天',
2, '2天',
3, '3天',
4, '4天',
5, '5天',
6, '6天',
7, '7天',
8, '8天',
9, '9天',
10, '10天',
11, '11天',
12, '12天',
13, '13天',
14, '14天',
15, '15天',
]; ];
var isUnOpenNotice = false.obs; // N天未开门提醒 var isUnOpenNotice = false.obs; // N天未开门提醒
var unOpenDoorTime = 1.obs; // var unOpenDoorTime = 3.obs; //
var getLockId = 0.obs; var getLockId = 0.obs;
var lockUserKeys = LockUserListKeys().obs; var lockUserKeys = LockUserListKeys().obs;
@ -43,7 +43,9 @@ class NDaysUnopenedState {
msgNoticeInfo.value = map['lockSetInfoData']; msgNoticeInfo.value = map['lockSetInfoData'];
isUnOpenNotice.value = isUnOpenNotice.value =
msgNoticeInfo.value.dayNotOpenDoorState == 1 ? true : false; msgNoticeInfo.value.dayNotOpenDoorState == 1 ? true : false;
unOpenDoorTime.value = msgNoticeInfo.value.dayNotOpenDoorValue!; if (msgNoticeInfo.value.dayNotOpenDoorValue != 0) {
unOpenDoorTime.value = msgNoticeInfo.value.dayNotOpenDoorValue!;
}
} }
} }
} }

View File

@ -5,7 +5,9 @@ import 'package:get/get.dart';
import 'package:star_lock/appRouters.dart'; import 'package:star_lock/appRouters.dart';
import 'package:star_lock/main/lockDetail/messageWarn/notificationMode/notificationMode_data.dart'; import 'package:star_lock/main/lockDetail/messageWarn/notificationMode/notificationMode_data.dart';
import 'package:star_lock/main/lockDetail/messageWarn/notificationMode/notificationMode_logic.dart'; import 'package:star_lock/main/lockDetail/messageWarn/notificationMode/notificationMode_logic.dart';
import 'package:star_lock/main/lockDetail/messageWarn/notificationMode/notificationMode_state.dart';
import 'package:star_lock/tools/commonItem.dart'; import 'package:star_lock/tools/commonItem.dart';
import 'package:star_lock/tools/regularExpression.dart';
import 'package:star_lock/tools/submitBtn.dart'; import 'package:star_lock/tools/submitBtn.dart';
import 'package:star_lock/translations/trans_lib.dart'; import 'package:star_lock/translations/trans_lib.dart';
@ -20,8 +22,8 @@ class NotificationModePage extends StatefulWidget {
} }
class _NotificationModePageState extends State<NotificationModePage> { class _NotificationModePageState extends State<NotificationModePage> {
final logic = Get.put(NotificationModeLogic()); final NotificationModeLogic logic = Get.put(NotificationModeLogic());
final state = Get.find<NotificationModeLogic>().state; final NotificationModeState state = Get.find<NotificationModeLogic>().state;
@override @override
void initState() { void initState() {
@ -43,7 +45,7 @@ class _NotificationModePageState extends State<NotificationModePage> {
Widget _buildMainView() { Widget _buildMainView() {
return Column( return Column(
children: [ children: <Widget>[
CommonItem( CommonItem(
leftTitel: 'APP推送'.tr, leftTitel: 'APP推送'.tr,
rightTitle: '管理员'.tr, rightTitle: '管理员'.tr,
@ -66,7 +68,7 @@ class _NotificationModePageState extends State<NotificationModePage> {
SubmitBtn( SubmitBtn(
btnName: '确定'.tr, btnName: '确定'.tr,
onClick: () { onClick: () {
Get.back(result: { Get.back(result: <String, List>{
'emailReceiverList': state.emailReceiverList.value, 'emailReceiverList': state.emailReceiverList.value,
'phoneReceiverList': state.phoneReceiverList.value 'phoneReceiverList': state.phoneReceiverList.value
}); });
@ -135,9 +137,9 @@ class _NotificationModePageState extends State<NotificationModePage> {
height: 62.h, height: 62.h,
color: Colors.white, color: Colors.white,
child: Row( child: Row(
children: [ children: <Widget>[
GestureDetector( GestureDetector(
onTap: (() { onTap: () {
if (isEmail) { if (isEmail) {
state.emailReceiverList.value.removeAt(index); state.emailReceiverList.value.removeAt(index);
state.emailReceiverList.refresh(); state.emailReceiverList.refresh();
@ -145,7 +147,7 @@ class _NotificationModePageState extends State<NotificationModePage> {
state.phoneReceiverList.value.removeAt(index); state.phoneReceiverList.value.removeAt(index);
state.phoneReceiverList.refresh(); state.phoneReceiverList.refresh();
} }
}), },
child: Container( child: Container(
color: Colors.white, color: Colors.white,
child: Image.asset( child: Image.asset(
@ -163,39 +165,40 @@ class _NotificationModePageState extends State<NotificationModePage> {
style: TextStyle(fontSize: 22.sp), style: TextStyle(fontSize: 22.sp),
), ),
Expanded(child: SizedBox(width: 10.w)), Expanded(child: SizedBox(width: 10.w)),
!isEmail if (!isEmail)
? GestureDetector( GestureDetector(
child: Container( child: Container(
width: 90.w, width: 90.w,
color: Colors.white, color: Colors.white,
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: <Widget>[
Obx(() => Text( Obx(() => Text(
'+${state.countryCode}', '+${state.countryCode}',
style: TextStyle( style: TextStyle(
color: AppColors.darkGrayTextColor, color: AppColors.darkGrayTextColor,
fontSize: 20.sp), fontSize: 20.sp),
)), )),
Image.asset( Image.asset(
'images/icon_grayPullDown.png', 'images/icon_grayPullDown.png',
width: 20.w, width: 20.w,
height: 20.w, height: 20.w,
),
],
), ),
), ],
onTap: () async { ),
var result = ),
await Get.toNamed(Routers.selectCountryRegionPage); onTap: () async {
if (result != null) { final result =
result as Map<String, dynamic>; await Get.toNamed(Routers.selectCountryRegionPage);
state.countryCode.value = result['code']; if (result != null) {
state.countryName.value = result['countryName']; result as Map<String, dynamic>;
} state.countryCode.value = result['code'];
}, state.countryName.value = result['countryName'];
) }
: Container(), },
)
else
Container(),
getReceiverTFWidget(isEmail ? '请输入Email'.tr : '请输入手机号'.tr, index, getReceiverTFWidget(isEmail ? '请输入Email'.tr : '请输入手机号'.tr, index,
isEmail: isEmail) isEmail: isEmail)
], ],
@ -206,7 +209,7 @@ class _NotificationModePageState extends State<NotificationModePage> {
// //
Widget getReceiverTFWidget(String tfStr, int lineIndex, Widget getReceiverTFWidget(String tfStr, int lineIndex,
{required bool isEmail}) { {required bool isEmail}) {
MsgNoticeModeData msgData = isEmail final MsgNoticeModeData msgData = isEmail
? state.emailReceiverList.value[lineIndex] ? state.emailReceiverList.value[lineIndex]
: state.phoneReceiverList.value[lineIndex]; : state.phoneReceiverList.value[lineIndex];
msgData.countryCode = state.countryCode.value; msgData.countryCode = state.countryCode.value;
@ -216,7 +219,7 @@ class _NotificationModePageState extends State<NotificationModePage> {
height: 65.h, height: 65.h,
width: 200.w, width: 200.w,
child: Row( child: Row(
children: [ children: <Widget>[
Expanded( Expanded(
child: TextField( child: TextField(
controller: msgData.receiverTF, controller: msgData.receiverTF,
@ -247,7 +250,7 @@ class _NotificationModePageState extends State<NotificationModePage> {
), ),
style: TextStyle( style: TextStyle(
fontSize: 22.sp, textBaseline: TextBaseline.alphabetic), fontSize: 22.sp, textBaseline: TextBaseline.alphabetic),
onChanged: (value) { onChanged: (String value) {
if (isEmail) { if (isEmail) {
msgData.receiveEmail = value; msgData.receiveEmail = value;
state.emailReceiverList.value[lineIndex] = msgData; state.emailReceiverList.value[lineIndex] = msgData;

View File

@ -89,7 +89,7 @@ class PalmDetailLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
// var publicKey = await Storage.getStringList(saveBluePublicKey); // var publicKey = await Storage.getStringList(saveBluePublicKey);

View File

@ -185,7 +185,7 @@ class PalmListLogic extends BaseGetXController {
// //
Future<void> senderQueryingFaceStatus() async { Future<void> senderQueryingFaceStatus() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState state) async { (BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.connected) { if (state == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
@ -214,7 +214,7 @@ class PalmListLogic extends BaseGetXController {
// () // ()
Future<void> senderCheckingUserInfoCount() async { Future<void> senderCheckingUserInfoCount() async {
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState state) async { (BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.connected) { if (state == BluetoothConnectionState.connected) {
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
@ -246,7 +246,7 @@ class PalmListLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState deviceConnectionState) async { (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);

View File

@ -127,7 +127,7 @@ class PasswordKeyDetailLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);
List<int> signKeyDataList = changeStringListToIntList(signKey!); List<int> signKeyDataList = changeStringListToIntList(signKey!);

View File

@ -121,7 +121,7 @@ class PasswordKeyDetailChangeDateLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);
List<int> signKeyDataList = changeStringListToIntList(signKey!); List<int> signKeyDataList = changeStringListToIntList(signKey!);

View File

@ -128,7 +128,7 @@ class PasswordKeyListLogic extends BaseGetXController {
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: (){
dismissEasyLoading(); dismissEasyLoading();
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);
List<int> signKeyDataList = changeStringListToIntList(signKey!); List<int> signKeyDataList = changeStringListToIntList(signKey!);
@ -177,7 +177,7 @@ class PasswordKeyListLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);
List<int> signKeyDataList = changeStringListToIntList(signKey!); List<int> signKeyDataList = changeStringListToIntList(signKey!);

View File

@ -342,7 +342,7 @@ class PasswordKeyPerpetualLogic extends BaseGetXController {
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) { if (deviceConnectionState == BluetoothConnectionState.connected) {
var signKey = await Storage.getStringList(saveBlueSignKey); var signKey = await Storage.getStringList(saveBlueSignKey);
List<int> signKeyDataList = changeStringListToIntList(signKey!); List<int> signKeyDataList = changeStringListToIntList(signKey!);

View File

@ -252,6 +252,11 @@ class LockListInfoItemEntity {
data['hasGateway'] = hasGateway; data['hasGateway'] = hasGateway;
return data; return data;
} }
//
bool isLockOwnerBool(){
return isLockOwner== 1;
}
} }
class Bluetooth { class Bluetooth {

View File

@ -4,7 +4,6 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/scheduler.dart'; import 'package:flutter/scheduler.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/blue/io_type.dart';
import 'package:star_lock/tools/baseGetXController.dart'; import 'package:star_lock/tools/baseGetXController.dart';
import '../../../blue/blue_manage.dart'; import '../../../blue/blue_manage.dart';
@ -23,26 +22,44 @@ import '../../../translations/trans_lib.dart';
import '../entity/lockListInfo_entity.dart'; import '../entity/lockListInfo_entity.dart';
import 'lockList_state.dart'; import 'lockList_state.dart';
class LockListLogic extends BaseGetXController{ class LockListLogic extends BaseGetXController {
LockListLogic(this.entity){
}
LockListState state = LockListState(); LockListState state = LockListState();
List<GroupList> groupDataList = <GroupList>[];
LockListInfoGroupEntity? entity;
//
void setLockListInfoGroupEntity(LockListInfoGroupEntity entity) {
this.entity = entity;
if (entity.pageNo == 1) {
groupDataList = <GroupList>[];
}
groupDataList.addAll(entity.groupList!);
update();
}
// //
late StreamSubscription<Reply> _replySubscription; late StreamSubscription<Reply> _replySubscription;
void _initReplySubscription() { void _initReplySubscription() {
_replySubscription = EventBusManager().eventBus!.on<Reply>().listen((reply) async { _replySubscription =
EventBusManager().eventBus!.on<Reply>().listen((Reply reply) async {
// //
if ((reply is FactoryDataResetReply) && (state.ifCurrentScreen.value == true)) { if ((reply is FactoryDataResetReply) &&
(state.ifCurrentScreen.value == true)) {
_replyFactoryDataResetKey(reply); _replyFactoryDataResetKey(reply);
} }
}); });
} }
Future<void> _replyFactoryDataResetKey(Reply reply) async { Future<void> _replyFactoryDataResetKey(Reply reply) async {
var token = reply.data.sublist(2, 6); final List<int> token = reply.data.sublist(2, 6);
var saveStrList = changeIntListToStringList(token); final List<String> saveStrList = changeIntListToStringList(token);
Storage.setStringList(saveBlueToken, saveStrList); Storage.setStringList(saveBlueToken, saveStrList);
int status = reply.data[6]; final int status = reply.data[6];
switch (status) { switch (status) {
case 0x00: case 0x00:
// //
@ -52,22 +69,24 @@ class LockListLogic extends BaseGetXController{
break; break;
case 0x06: case 0x06:
// //
var token = await Storage.getStringList(saveBlueToken); final List<String>? token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!); final List<int> getTokenList = changeStringListToIntList(token!);
IoSenderManage.senderFactoryDataReset( IoSenderManage.senderFactoryDataReset(
lockID: BlueManage().connectDeviceName, lockID: BlueManage().connectDeviceName,
userID: await Storage.getUid(), userID: await Storage.getUid(),
keyID: "1", keyID: '1',
needAuthor: 1, needAuthor: 1,
publicKey: state.lockListInfoItemEntity.bluetooth!.publicKey!.cast<int>(), publicKey:
privateKey: state.lockListInfoItemEntity.bluetooth!.privateKey!.cast<int>(), state.lockListInfoItemEntity.bluetooth!.publicKey!.cast<int>(),
privateKey:
state.lockListInfoItemEntity.bluetooth!.privateKey!.cast<int>(),
token: getTokenList); token: getTokenList);
break; break;
case 0x07: case 0x07:
// //
dismissEasyLoading(); dismissEasyLoading();
showToast("用户无权限"); showToast('用户无权限');
break; break;
case 0x09: case 0x09:
// //
@ -82,62 +101,63 @@ class LockListLogic extends BaseGetXController{
} }
} }
String showElectricIcon (int electricnumber){ String showElectricIcon(int electricnumber) {
if(electricnumber >= 100){ if (electricnumber >= 100) {
return 'images/main/icon_lockElectricLevel_5.png'; return 'images/main/icon_lockElectricLevel_5.png';
}else if((electricnumber > 50) && (electricnumber < 100)){ } else if ((electricnumber > 50) && (electricnumber < 100)) {
return 'images/main/icon_lockElectricLevel_4.png'; return 'images/main/icon_lockElectricLevel_4.png';
}else if((electricnumber > 25) && (electricnumber <= 50)){ } else if ((electricnumber > 25) && (electricnumber <= 50)) {
return 'images/main/icon_lockElectricLevel_3.png'; return 'images/main/icon_lockElectricLevel_3.png';
}else if((electricnumber > 5) && (electricnumber <= 25)){ } else if ((electricnumber > 5) && (electricnumber <= 25)) {
return 'images/main/icon_lockElectricLevel_2.png'; return 'images/main/icon_lockElectricLevel_2.png';
}else if(electricnumber <= 5){ } else if (electricnumber <= 5) {
return 'images/main/icon_lockElectricLevel_1.png'; return 'images/main/icon_lockElectricLevel_1.png';
} }
return 'images/main/icon_lockElectricLevel_5.png'; return 'images/main/icon_lockElectricLevel_5.png';
} }
String getKeyEffective(LockListInfoItemEntity keyInfo){ String getKeyEffective(LockListInfoItemEntity keyInfo) {
// //
if(keyInfo.keyType == XSConstantMacro.keyTypeTime || keyInfo.keyType == XSConstantMacro.keyTypeLoop){ if (keyInfo.keyType == XSConstantMacro.keyTypeTime ||
keyInfo.keyType == XSConstantMacro.keyTypeLoop) {
// 使 // 使
if(keyInfo.keyStatus == XSConstantMacro.keyStatusNormalUse || keyInfo.keyStatus == XSConstantMacro.keyStatusWaitReceive) { if (keyInfo.keyStatus == XSConstantMacro.keyStatusNormalUse ||
keyInfo.keyStatus == XSConstantMacro.keyStatusWaitReceive) {
return "${"".tr}${DateTool().compareTimeGetDaysFromNow(keyInfo.endDate!)}${"".tr}"; return "${"".tr}${DateTool().compareTimeGetDaysFromNow(keyInfo.endDate!)}${"".tr}";
} else { } else {
return XSConstantMacro.getKeyStatusStr(keyInfo.keyStatus!); return XSConstantMacro.getKeyStatusStr(keyInfo.keyStatus!);
} }
} }
return ""; return '';
} }
/// ///
deleyLockLogicOfRoles(){ void deleyLockLogicOfRoles() {
if (state.lockListInfoItemEntity.isLockOwner == 1) { if (state.lockListInfoItemEntity.isLockOwner == 1) {
// //
ShowTipView().showIosTipWithContentDialog("删除锁后,所有信息都会一起删除,确定删除锁吗?".tr, (){ ShowTipView().showIosTipWithContentDialog('删除锁后,所有信息都会一起删除,确定删除锁吗?'.tr,
() {
// //
ShowTipView().showTFViewAlertDialog(state.passwordTF, "请输入登录密码".tr, "请输入登录密码".tr, (){ ShowTipView().showTFViewAlertDialog(
checkLoginPassword(); state.passwordTF, '请输入登录密码'.tr, '请输入登录密码'.tr, checkLoginPassword);
});
}); });
} else if (state.lockListInfoItemEntity.keyRight == 1){ } else if (state.lockListInfoItemEntity.keyRight == 1) {
// //
ShowTipView().showDeleteAdministratorIsHaveAllDataDialog("同时删除其发送的所有钥匙,钥匙删除后不能恢复".tr, (a){ ShowTipView().showDeleteAdministratorIsHaveAllDataDialog(
'同时删除其发送的所有钥匙,钥匙删除后不能恢复'.tr, (bool a) {
// //
state.deleteAdministratorIsHaveAllData.value = a; state.deleteAdministratorIsHaveAllData.value = a;
deletKeyData(); deletKeyData();
}); });
} else{ } else {
// //
ShowTipView().showIosTipWithContentDialog("是否删除钥匙?".tr, (){ ShowTipView().showIosTipWithContentDialog('是否删除钥匙?'.tr, deletKeyData);
deletKeyData();
});
} }
} }
// //
void checkLoginPassword() async { Future<void> checkLoginPassword() async {
var entity = await ApiRepository.to.checkLoginPassword( final LockListInfoEntity entity = await ApiRepository.to.checkLoginPassword(
password: state.passwordTF.text, password: state.passwordTF.text,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
@ -147,12 +167,12 @@ class LockListLogic extends BaseGetXController{
} }
// //
void deletLockInfoData() async { Future<void> deletLockInfoData() async {
var entity = await ApiRepository.to.deletOwnerLockData( final LockListInfoEntity entity = await ApiRepository.to.deletOwnerLockData(
lockId: state.lockListInfoItemEntity.lockId!, lockId: state.lockListInfoItemEntity.lockId!,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
BlueManage().connectDeviceMacAddress = ""; BlueManage().connectDeviceMacAddress = '';
SchedulerBinding.instance.addPostFrameCallback((_) { SchedulerBinding.instance.addPostFrameCallback((_) {
eventBus.fire(RefreshLockListInfoDataEvent()); eventBus.fire(RefreshLockListInfoDataEvent());
}); });
@ -160,14 +180,14 @@ class LockListLogic extends BaseGetXController{
} }
// //
void deletKeyData() async { Future<void> deletKeyData() async {
var entity = await ApiRepository.to.deletOwnerKeyData( final LockListInfoEntity entity = await ApiRepository.to.deletOwnerKeyData(
lockId: state.lockListInfoItemEntity.lockId.toString(), lockId: state.lockListInfoItemEntity.lockId.toString(),
keyId: state.lockListInfoItemEntity.keyId.toString(), keyId: state.lockListInfoItemEntity.keyId.toString(),
includeUnderlings: state.deleteAdministratorIsHaveAllData.value == true ? 1 : 0 includeUnderlings:
); state.deleteAdministratorIsHaveAllData.value == true ? 1 : 0);
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
BlueManage().connectDeviceMacAddress = ""; BlueManage().connectDeviceMacAddress = '';
SchedulerBinding.instance.addPostFrameCallback((_) { SchedulerBinding.instance.addPostFrameCallback((_) {
eventBus.fire(RefreshLockListInfoDataEvent()); eventBus.fire(RefreshLockListInfoDataEvent());
}); });
@ -177,62 +197,74 @@ class LockListLogic extends BaseGetXController{
// //
Future<void> factoryDataResetAction() async { Future<void> factoryDataResetAction() async {
showEasyLoading(); showEasyLoading();
showBlueConnetctToastTimer(isShowBlueConnetctToast: false, action: (){ showBlueConnetctToastTimer(
dismissEasyLoading(); isShowBlueConnetctToast: false,
showDeletAlertTipDialog(); action: () {
}); dismissEasyLoading();
BlueManage().bludSendData(state.lockListInfoItemEntity.lockName!, (BluetoothConnectionState connectionState) async { showDeletAlertTipDialog();
});
BlueManage().blueSendData(state.lockListInfoItemEntity.lockName!,
(BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
List<int> publicKeyData = state.lockListInfoItemEntity.bluetooth!.publicKey!.cast<int>(); final List<int> publicKeyData =
var saveStrList = changeIntListToStringList(publicKeyData); state.lockListInfoItemEntity.bluetooth!.publicKey!.cast<int>();
final List<String> saveStrList =
changeIntListToStringList(publicKeyData);
Storage.setStringList(saveBluePublicKey, saveStrList); Storage.setStringList(saveBluePublicKey, saveStrList);
// //
List<int> privateKeyData = state.lockListInfoItemEntity.bluetooth!.privateKey!.cast<int>(); final List<int> privateKeyData =
var savePrivateKeyList = changeIntListToStringList(privateKeyData); state.lockListInfoItemEntity.bluetooth!.privateKey!.cast<int>();
final List<String> savePrivateKeyList =
changeIntListToStringList(privateKeyData);
Storage.setStringList(saveBluePrivateKey, savePrivateKeyList); Storage.setStringList(saveBluePrivateKey, savePrivateKeyList);
// signKey // signKey
List<int> signKeyData = state.lockListInfoItemEntity.bluetooth!.signKey!.cast<int>(); final List<int> signKeyData =
var saveSignKeyList = changeIntListToStringList(signKeyData); state.lockListInfoItemEntity.bluetooth!.signKey!.cast<int>();
final List<String> saveSignKeyList =
changeIntListToStringList(signKeyData);
Storage.setStringList(saveBlueSignKey, saveSignKeyList); Storage.setStringList(saveBlueSignKey, saveSignKeyList);
var saveTokenList = changeIntListToStringList([0, 0, 0, 0]); final List<String> saveTokenList =
changeIntListToStringList(<int>[0, 0, 0, 0]);
Storage.setStringList(saveBlueToken, saveTokenList); Storage.setStringList(saveBlueToken, saveTokenList);
IoSenderManage.senderFactoryDataReset( IoSenderManage.senderFactoryDataReset(
lockID: BlueManage().connectDeviceName, lockID: BlueManage().connectDeviceName,
userID: await Storage.getUid(), userID: await Storage.getUid(),
keyID: "1", keyID: '1',
needAuthor: 1, needAuthor: 1,
publicKey: state.lockListInfoItemEntity.bluetooth!.publicKey!.cast<int>(), publicKey:
privateKey: state.lockListInfoItemEntity.bluetooth!.privateKey!.cast<int>(), state.lockListInfoItemEntity.bluetooth!.publicKey!.cast<int>(),
token: [0,0,0,0]); privateKey:
state.lockListInfoItemEntity.bluetooth!.privateKey!.cast<int>(),
token: <int>[0, 0, 0, 0]);
} else if (connectionState == BluetoothConnectionState.disconnected) { } else if (connectionState == BluetoothConnectionState.disconnected) {
dismissEasyLoading(); dismissEasyLoading();
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
if(state.ifCurrentScreen.value == true){ if (state.ifCurrentScreen.value == true) {
showDeletAlertTipDialog(); showDeletAlertTipDialog();
} }
} }
}); });
} }
void showDeletAlertTipDialog({String? showContent = ""}) { void showDeletAlertTipDialog({String? showContent = ''}) {
// bool isContains = BlueManage().connectDeviceName!.contains("T9A"); // bool isContains = BlueManage().connectDeviceName!.contains("T9A");
var content = showContent!.isEmpty ? "${"删除设备失败,请确保在设备附近,设备未被连接,设备已打开".tr}${BlueManage().connectDeviceName!.contains("T9A") == true ? "。如果是全自动锁,请使屏幕变亮".tr : ""}" : showContent; final String content = showContent!.isEmpty
? "${"删除设备失败,请确保在设备附近,设备未被连接,设备已打开".tr}${BlueManage().connectDeviceName.contains("T9A") == true ? "。如果是全自动锁,请使屏幕变亮".tr : ""}"
: showContent;
showCupertinoDialog( showCupertinoDialog(
context: Get.context!, context: Get.context!,
builder: (context) { builder: (BuildContext context) {
return CupertinoAlertDialog( return CupertinoAlertDialog(
title: Text("提示".tr), title: Text('提示'.tr),
content: Text(content), content: Text(content),
actions: [ actions: <Widget>[
CupertinoDialogAction( CupertinoDialogAction(
child: Text(TranslationLoader.lanKeys!.sure!.tr), child: Text(TranslationLoader.lanKeys!.sure!.tr),
onPressed: () { onPressed: Get.back,
Get.back();
},
), ),
], ],
); );
@ -242,23 +274,18 @@ class LockListLogic extends BaseGetXController{
@override @override
void onReady() { void onReady() {
// TODO: implement onReady
super.onReady(); super.onReady();
_initReplySubscription(); _initReplySubscription();
} }
@override @override
void onInit() { void onInit() {
// TODO: implement onInit
super.onInit(); super.onInit();
setLockListInfoGroupEntity(entity!);
} }
@override @override
void onClose() { void onClose() {
// TODO: implement onClose
_replySubscription.cancel(); _replySubscription.cancel();
} }
}
}

View File

@ -3,6 +3,7 @@ import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/flavors.dart'; import 'package:star_lock/flavors.dart';
import 'package:star_lock/main/lockMian/lockList/lockList_state.dart';
import '../../../appRouters.dart'; import '../../../appRouters.dart';
import '../../../app_settings/app_colors.dart'; import '../../../app_settings/app_colors.dart';
@ -14,50 +15,53 @@ import 'lockListGroup_view.dart';
import 'lockList_logic.dart'; import 'lockList_logic.dart';
class LockListPage extends StatefulWidget { class LockListPage extends StatefulWidget {
final LockListInfoGroupEntity lockListInfoGroupEntity;
const LockListPage({Key? key, required this.lockListInfoGroupEntity}) const LockListPage({required this.lockListInfoGroupEntity, Key? key})
: super(key: key); : super(key: key);
final LockListInfoGroupEntity lockListInfoGroupEntity;
@override @override
State<LockListPage> createState() => _LockListPageState(); State<LockListPage> createState() => _LockListPageState();
} }
class _LockListPageState extends State<LockListPage> with RouteAware { class _LockListPageState extends State<LockListPage> with RouteAware {
final logic = Get.put(LockListLogic()); late LockListLogic logic;
final state = Get.find<LockListLogic>().state; late LockListState state;
var groupDataList = <GroupList>[]; @override
void initState() {
super.initState();
logic = Get.put(LockListLogic(widget.lockListInfoGroupEntity));
state = Get.find<LockListLogic>().state;
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.lockListInfoGroupEntity.pageNo == 1) { return GetBuilder<LockListLogic>(builder: (LockListLogic logic) {
groupDataList = <GroupList>[]; return Scaffold(
} body: ListView.separated(
groupDataList.addAll( itemCount: logic.groupDataList.length,
widget.lockListInfoGroupEntity.groupList as Iterable<GroupList>); itemBuilder: (BuildContext context, int index) {
final GroupList itemData = logic.groupDataList[index];
return Scaffold( return _buildLockExpandedList(context, index, itemData);
body: ListView.separated( },
itemCount: groupDataList.length, shrinkWrap: true,
itemBuilder: (context, index) { physics: const AlwaysScrollableScrollPhysics(),
GroupList itemData = groupDataList[index]; separatorBuilder: (BuildContext context, int index) {
return _buildLockExpandedList(context, index, itemData); return const Divider(
}, height: 1,
shrinkWrap: true, color: AppColors.greyLineColor,
physics: const AlwaysScrollableScrollPhysics(), );
separatorBuilder: (context, index) { }),
return const Divider( );
height: 1, });
color: AppColors.greyLineColor,
);
}),
);
} }
// //
Widget _buildLockExpandedList(context, index, GroupList itemData) { Widget _buildLockExpandedList(
List lockItemList = itemData.lockList ?? []; BuildContext context, int index, GroupList itemData) {
final List<LockListInfoItemEntity> lockItemList =
itemData.lockList ?? <LockListInfoItemEntity>[];
return LockListGroupView( return LockListGroupView(
onTap: () { onTap: () {
// //
@ -65,28 +69,28 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
} else {} } else {}
setState(() {}); setState(() {});
}, },
typeImgList: const [], typeImgList: const <dynamic>[],
groupItem: itemData, groupItem: itemData,
child: ListView.separated( child: ListView.separated(
itemCount: lockItemList.length, itemCount: lockItemList.length,
shrinkWrap: true, shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(), physics: const NeverScrollableScrollPhysics(),
separatorBuilder: (context, index) { separatorBuilder: (BuildContext context, int index) {
return const Divider(height: 1, color: AppColors.greyLineColor); return const Divider(height: 1, color: AppColors.greyLineColor);
}, },
itemBuilder: (c, index) { itemBuilder: (BuildContext c, int index) {
LockListInfoItemEntity keyInfo = lockItemList[index]; final LockListInfoItemEntity keyInfo = lockItemList[index];
bool isLast = false; bool isLast = false;
if (lockItemList.length == index + 1) { if (lockItemList.length == index + 1) {
isLast = true; isLast = true;
} }
return Slidable( return Slidable(
key: ValueKey(keyInfo.keyId), key: ValueKey<int?>(keyInfo.keyId),
endActionPane: ActionPane( endActionPane: ActionPane(
extentRatio: 0.2, extentRatio: 0.2,
motion: const ScrollMotion(), motion: const ScrollMotion(),
children: [ children: <Widget>[
SlidableAction( SlidableAction(
onPressed: (BuildContext context) { onPressed: (BuildContext context) {
state.lockListInfoItemEntity = keyInfo; state.lockListInfoItemEntity = keyInfo;
@ -104,26 +108,27 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
keyInfo.keyType == XSConstantMacro.keyTypeLoop) && keyInfo.keyType == XSConstantMacro.keyTypeLoop) &&
(keyInfo.keyStatus == (keyInfo.keyStatus ==
XSConstantMacro.keyStatusWaitIneffective)) { XSConstantMacro.keyStatusWaitIneffective)) {
logic.showToast("您的钥匙未生效".tr); logic.showToast('您的钥匙未生效'.tr);
return; return;
} }
if ((keyInfo.keyType == XSConstantMacro.keyTypeTime || if ((keyInfo.keyType == XSConstantMacro.keyTypeTime ||
keyInfo.keyType == XSConstantMacro.keyTypeLoop) && keyInfo.keyType == XSConstantMacro.keyTypeLoop) &&
(keyInfo.keyStatus == XSConstantMacro.keyStatusFrozen)) { (keyInfo.keyStatus == XSConstantMacro.keyStatusFrozen)) {
logic.showToast("您的钥匙已冻结".tr); logic.showToast('您的钥匙已冻结'.tr);
return; return;
} }
if ((keyInfo.keyType == XSConstantMacro.keyTypeTime || if ((keyInfo.keyType == XSConstantMacro.keyTypeTime ||
keyInfo.keyType == XSConstantMacro.keyTypeLoop) && keyInfo.keyType == XSConstantMacro.keyTypeLoop) &&
(keyInfo.keyStatus == XSConstantMacro.keyStatusExpired)) { (keyInfo.keyStatus == XSConstantMacro.keyStatusExpired)) {
logic.showToast("您的钥匙已过期".tr); logic.showToast('您的钥匙已过期'.tr);
return; return;
} }
Get.toNamed(Routers.lockDetailMainPage, arguments: { Get.toNamed(Routers.lockDetailMainPage,
// "lockMainEntity": widget.lockMainEntity, arguments: <String, Object>{
"keyInfo": keyInfo, // "lockMainEntity": widget.lockMainEntity,
"isOnlyOneData": false, 'keyInfo': keyInfo,
}); 'isOnlyOneData': false,
});
}), }),
); );
}), }),
@ -152,18 +157,18 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
), ),
child: Column( child: Column(
// mainAxisAlignment: MainAxisAlignment.center, // mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
SizedBox( SizedBox(
height: 20.h, height: 20.h,
), ),
Row( Row(
children: [ children: <Widget>[
SizedBox(width: 30.w), SizedBox(width: 30.w),
Expanded( Expanded(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: <Widget>[
Text( Text(
keyInfo.lockAlias!, keyInfo.lockAlias!,
style: TextStyle( style: TextStyle(
@ -184,7 +189,7 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
), ),
SizedBox(width: 2.w), SizedBox(width: 2.w),
Text( Text(
"${keyInfo.electricQuantity!}%", '${keyInfo.electricQuantity!}%',
style: TextStyle( style: TextStyle(
fontSize: 18.sp, color: AppColors.darkGrayTextColor), fontSize: 18.sp, color: AppColors.darkGrayTextColor),
), ),
@ -193,9 +198,9 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
), ),
SizedBox(height: 5.h), SizedBox(height: 5.h),
Visibility( Visibility(
visible: keyInfo.passageMode == 1 ? true : false, visible: keyInfo.passageMode == 1,
child: Row( child: Row(
children: [ children: <Widget>[
SizedBox(width: 30.w), SizedBox(width: 30.w),
Container( Container(
padding: EdgeInsets.only(right: 5.w, left: 5.w), padding: EdgeInsets.only(right: 5.w, left: 5.w),
@ -203,7 +208,7 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
borderRadius: BorderRadius.circular(5.w), borderRadius: BorderRadius.circular(5.w),
color: AppColors.openPassageModeColor, color: AppColors.openPassageModeColor,
), ),
child: Text("常开模式开启".tr, child: Text('常开模式开启'.tr,
style: TextStyle( style: TextStyle(
fontSize: 18.sp, fontSize: 18.sp,
color: AppColors.appBarIconColor)), color: AppColors.appBarIconColor)),
@ -212,12 +217,12 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
)), )),
SizedBox(height: 5.h), SizedBox(height: 5.h),
Visibility( Visibility(
visible: keyInfo.lockSetting!.remoteUnlock == 1 ? true : false, visible: keyInfo.lockSetting!.remoteUnlock == 1,
child: Row( child: Row(
children: [ children: <Widget>[
SizedBox(width: 30.w), SizedBox(width: 30.w),
Text( Text(
"远程开锁".tr, '远程开锁'.tr,
style: TextStyle( style: TextStyle(
fontSize: 18.sp, color: AppColors.darkGrayTextColor), fontSize: 18.sp, color: AppColors.darkGrayTextColor),
), ),
@ -225,19 +230,15 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
)), )),
SizedBox(height: 20.h), SizedBox(height: 20.h),
Visibility( Visibility(
visible: ((keyInfo.keyType == XSConstantMacro.keyTypeTime || visible: (keyInfo.keyType == XSConstantMacro.keyTypeTime ||
keyInfo.keyType == XSConstantMacro.keyTypeLoop) && keyInfo.keyType == XSConstantMacro.keyTypeLoop) &&
(keyInfo.keyStatus == (keyInfo.keyStatus ==
XSConstantMacro.keyStatusWaitIneffective || XSConstantMacro.keyStatusWaitIneffective ||
keyInfo.keyStatus == keyInfo.keyStatus == XSConstantMacro.keyStatusFrozen ||
XSConstantMacro.keyStatusFrozen || keyInfo.keyStatus == XSConstantMacro.keyStatusExpired),
keyInfo.keyStatus ==
XSConstantMacro.keyStatusExpired))
? true
: false,
// visible: true, // visible: true,
child: Row( child: Row(
children: [ children: <Widget>[
SizedBox(width: 30.w), SizedBox(width: 30.w),
Container( Container(
padding: EdgeInsets.only(right: 5.w, left: 5.w), padding: EdgeInsets.only(right: 5.w, left: 5.w),
@ -257,7 +258,7 @@ class _LockListPageState extends State<LockListPage> with RouteAware {
)), )),
SizedBox(height: 5.h), SizedBox(height: 5.h),
Row( Row(
children: [ children: <Widget>[
SizedBox(width: 30.w), SizedBox(width: 30.w),
Text( Text(
"${logic.getUseKeyTypeStr(keyInfo.startDate, keyInfo.endDate, keyInfo.keyType)}/${keyInfo.isLockOwner == 1 ? '超级管理员'.tr : (keyInfo.keyRight == 1 ? "授权管理员".tr : "普通用户".tr)}", "${logic.getUseKeyTypeStr(keyInfo.startDate, keyInfo.endDate, keyInfo.keyType)}/${keyInfo.isLockOwner == 1 ? '超级管理员'.tr : (keyInfo.keyRight == 1 ? "授权管理员".tr : "普通用户".tr)}",

View File

@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/flavors.dart'; import 'package:star_lock/main/lockMian/lockList/lockList_state.dart';
import '../../../appRouters.dart'; import '../../../appRouters.dart';
import '../../../app_settings/app_colors.dart'; import '../../../app_settings/app_colors.dart';
@ -14,87 +14,90 @@ import 'lockListGroup_view.dart';
import 'lockList_logic.dart'; import 'lockList_logic.dart';
class LockListXHJPage extends StatefulWidget { class LockListXHJPage extends StatefulWidget {
final LockListInfoGroupEntity lockListInfoGroupEntity;
const LockListXHJPage({Key? key, required this.lockListInfoGroupEntity}) const LockListXHJPage({required this.lockListInfoGroupEntity, Key? key})
: super(key: key); : super(key: key);
final LockListInfoGroupEntity lockListInfoGroupEntity;
@override @override
State<LockListXHJPage> createState() => _LockListXHJPageState(); State<LockListXHJPage> createState() => _LockListXHJPageState();
} }
class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware { class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
final logic = Get.put(LockListLogic()); late LockListLogic logic;
final state = Get.find<LockListLogic>().state; late LockListState state;
var groupDataList = <GroupList>[]; @override
void initState() {
super.initState();
logic = Get.put(LockListLogic(widget.lockListInfoGroupEntity));
state = Get.find<LockListLogic>().state;
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.lockListInfoGroupEntity.pageNo == 1) { return GetBuilder<LockListLogic>(builder: (LockListLogic logic) {
groupDataList = <GroupList>[]; return SafeArea(
} bottom: false,
groupDataList.addAll( child: Column(
widget.lockListInfoGroupEntity.groupList as Iterable<GroupList>); crossAxisAlignment: CrossAxisAlignment.start,
return SafeArea( children: <Widget>[
bottom: false, Align(
child: Column( alignment: Alignment.topRight,
crossAxisAlignment: CrossAxisAlignment.start, child: IconButton(
children: [ onPressed: () {
Align( Get.toNamed(Routers.selectLockTypePage);
alignment: Alignment.topRight, },
child: IconButton( icon: Icon(
onPressed: () { Icons.add_circle,
Get.toNamed(Routers.selectLockTypePage); size: 48.w,
}, color: AppColors.mainColor,
icon: Icon( )),
Icons.add_circle, ),
size: 48.w, Padding(
color: AppColors.mainColor, padding: EdgeInsets.only(left: 45.w),
)), child: Text(
), '常用程序'.tr,
Padding( style: TextStyle(
padding: EdgeInsets.only(left: 45.w), fontSize: 32.sp,
child: Text( color: AppColors.blackColor,
'常用程序'.tr, fontWeight: FontWeight.w600,
style: TextStyle( ),
fontSize: 32.sp,
color: AppColors.blackColor,
fontWeight: FontWeight.w600,
), ),
), ),
), Expanded(
Expanded( child: ListView.separated(
child: ListView.separated( itemCount: logic.groupDataList.length,
itemCount: groupDataList.length, itemBuilder: (BuildContext context, int index) {
itemBuilder: (context, index) { final GroupList itemData = logic.groupDataList[index];
GroupList itemData = groupDataList[index]; return _buildLockExpandedList(context, index, itemData);
return _buildLockExpandedList(context, index, itemData); },
}, shrinkWrap: true,
shrinkWrap: true, physics: const AlwaysScrollableScrollPhysics(),
physics: const AlwaysScrollableScrollPhysics(), separatorBuilder: (BuildContext context, int index) {
separatorBuilder: (context, index) { return const Divider(
return const Divider( height: 1,
height: 1, color: AppColors.greyLineColor,
color: AppColors.greyLineColor, );
); }),
}), ),
), ],
], ),
), );
); });
} }
// //
Widget _buildLockExpandedList(context, index, GroupList itemData) { Widget _buildLockExpandedList(context, index, GroupList itemData) {
List lockItemList = itemData.lockList ?? []; final List<LockListInfoItemEntity> lockItemList =
itemData.lockList ?? <LockListInfoItemEntity>[];
return LockListGroupView( return LockListGroupView(
onTap: () { onTap: () {
setState(() {}); setState(() {});
}, },
textStyle: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.w600), textStyle: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.w600),
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
typeImgList: const [], typeImgList: const <dynamic>[],
groupItem: itemData, groupItem: itemData,
child: GridView.extent( child: GridView.extent(
padding: EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.w), padding: EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.w),
@ -109,9 +112,9 @@ class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
} }
List<Widget> forItems(List lockItemList) { List<Widget> forItems(List lockItemList) {
List<Widget> list = []; final List<Widget> list = <Widget>[];
for (int i = 0, j = 0; i < lockItemList.length; i++, j++) { for (int i = 0, j = 0; i < lockItemList.length; i++, j++) {
LockListInfoItemEntity keyInfo = lockItemList[i]; final LockListInfoItemEntity keyInfo = lockItemList[i];
bool isLast = false; bool isLast = false;
if (lockItemList.length == i + 1) { if (lockItemList.length == i + 1) {
isLast = true; isLast = true;
@ -121,7 +124,7 @@ class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
endActionPane: ActionPane( endActionPane: ActionPane(
extentRatio: 0.2, extentRatio: 0.2,
motion: const ScrollMotion(), motion: const ScrollMotion(),
children: [ children: <Widget>[
SlidableAction( SlidableAction(
onPressed: (BuildContext context) { onPressed: (BuildContext context) {
state.lockListInfoItemEntity = keyInfo; state.lockListInfoItemEntity = keyInfo;
@ -153,7 +156,7 @@ class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
logic.showToast("您的钥匙已过期".tr); logic.showToast("您的钥匙已过期".tr);
return; return;
} }
Get.toNamed(Routers.lockDetailMainPage, arguments: { Get.toNamed(Routers.lockDetailMainPage, arguments: <String, Object>{
"keyInfo": keyInfo, "keyInfo": keyInfo,
"isOnlyOneData": false, "isOnlyOneData": false,
}); });
@ -189,9 +192,9 @@ class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: <Widget>[
Row( Row(
children: [ children: <Widget>[
Image.asset( Image.asset(
'images/icon_lock_circle.png', 'images/icon_lock_circle.png',
width: 32.r, width: 32.r,
@ -218,7 +221,7 @@ class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
child: Padding( child: Padding(
padding: EdgeInsets.only(top: 5.h), padding: EdgeInsets.only(top: 5.h),
child: Row( child: Row(
children: [ children: <Widget>[
Container( Container(
padding: EdgeInsets.only(right: 5.w, left: 5.w), padding: EdgeInsets.only(right: 5.w, left: 5.w),
decoration: BoxDecoration( decoration: BoxDecoration(
@ -239,7 +242,7 @@ class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
child: Padding( child: Padding(
padding: EdgeInsets.only(top: 5.h), padding: EdgeInsets.only(top: 5.h),
child: Row( child: Row(
children: [ children: <Widget>[
Text( Text(
"远程开锁".tr, "远程开锁".tr,
style: TextStyle( style: TextStyle(
@ -263,7 +266,7 @@ class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
child: Padding( child: Padding(
padding: EdgeInsets.only(top: 20.h), padding: EdgeInsets.only(top: 20.h),
child: Row( child: Row(
children: [ children: <Widget>[
Container( Container(
padding: EdgeInsets.only(right: 5.w, left: 5.w), padding: EdgeInsets.only(right: 5.w, left: 5.w),
decoration: BoxDecoration( decoration: BoxDecoration(
@ -284,7 +287,7 @@ class _LockListXHJPageState extends State<LockListXHJPage> with RouteAware {
)), )),
SizedBox(height: 5.h), SizedBox(height: 5.h),
Row( Row(
children: [ children: <Widget>[
Expanded( Expanded(
child: Text( child: Text(
keyInfo.isLockOwner == 1 keyInfo.isLockOwner == 1

View File

@ -1,7 +1,7 @@
import 'dart:async'; import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/main/lockMian/lockList/lockList_logic.dart';
import '../../../app_settings/app_settings.dart'; import '../../../app_settings/app_settings.dart';
import '../../../blue/blue_manage.dart'; import '../../../blue/blue_manage.dart';
@ -15,10 +15,12 @@ import 'lockMain_state.dart';
class LockMainLogic extends BaseGetXController { class LockMainLogic extends BaseGetXController {
final LockMainState state = LockMainState(); final LockMainState state = LockMainState();
Future<LockListInfoEntity> getStarLockInfo() async { Future<LockListInfoEntity> getStarLockInfo(
{bool isUnShowLoading = false}) async {
LockListInfoEntity entity = await ApiRepository.to.getStarLockListInfo( LockListInfoEntity entity = await ApiRepository.to.getStarLockListInfo(
pageNo: pageNo, pageNo: pageNo,
pageSize: 50, pageSize: 50,
isUnShowLoading: isUnShowLoading,
); );
if (entity.errorCode!.codeIsSuccessful) { if (entity.errorCode!.codeIsSuccessful) {
loadMainDataLogic(entity.data!); loadMainDataLogic(entity.data!);
@ -34,11 +36,11 @@ class LockMainLogic extends BaseGetXController {
return entity; return entity;
} }
Future<void> loadMainDataLogic(LockListInfoGroupEntity entity){ void loadMainDataLogic(LockListInfoGroupEntity entity) {
if (entity.groupList!.isEmpty) { if (entity.groupList!.isEmpty) {
state.dataLength.value = 0; state.dataLength.value = 0;
} else if (entity.groupList!.length == 1) { } else if (entity.groupList!.length == 1) {
GroupList groupList = entity.groupList![0]; final GroupList groupList = entity.groupList![0];
if (groupList.lockList!.length > 1) { if (groupList.lockList!.length > 1) {
state.dataLength.value = 2; state.dataLength.value = 2;
} else { } else {
@ -48,7 +50,11 @@ class LockMainLogic extends BaseGetXController {
state.dataLength.value = 2; state.dataLength.value = 2;
} }
state.lockListInfoGroupEntity.value = entity; state.lockListInfoGroupEntity.value = entity;
return Future.value(); //
if (Get.isRegistered<LockListLogic>()) {
//
Get.find<LockListLogic>().setLockListInfoGroupEntity(entity);
}
} }
/// ///
@ -80,7 +86,8 @@ class LockMainLogic extends BaseGetXController {
connectListener() async { connectListener() async {
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) { Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
AppLog.log("设置网络切换监听:$result"); AppLog.log("设置网络切换监听:$result");
if (state.networkConnectionStatus.value == 0 && result != ConnectivityResult.none) { if (state.networkConnectionStatus.value == 0 &&
result != ConnectivityResult.none) {
// //
state.networkConnectionStatus.value = 1; state.networkConnectionStatus.value = 1;
getStarLockInfo(); getStarLockInfo();

View File

@ -37,14 +37,15 @@ class _StarLockMainPageState extends State<StarLockMainPage> with BaseWidget {
final logic = Get.put(LockMainLogic()); final logic = Get.put(LockMainLogic());
final state = Get.find<LockMainLogic>().state; final state = Get.find<LockMainLogic>().state;
Future<void> getHttpData({bool clearScanDevices = false}) async { Future<void> getHttpData(
{bool clearScanDevices = false, bool isUnShowLoading = false}) async {
LockListInfoGroupEntity? lockListInfoGroupEntity = LockListInfoGroupEntity? lockListInfoGroupEntity =
await Storage.getLockMainListData(); await Storage.getLockMainListData();
if (lockListInfoGroupEntity != null) { if (lockListInfoGroupEntity != null) {
var localLockListInfoGroupEntity = lockListInfoGroupEntity; var localLockListInfoGroupEntity = lockListInfoGroupEntity;
await logic.loadMainDataLogic(localLockListInfoGroupEntity); logic.loadMainDataLogic(localLockListInfoGroupEntity);
} }
await logic.getStarLockInfo(); await logic.getStarLockInfo(isUnShowLoading: isUnShowLoading);
await Future.delayed(const Duration(milliseconds: 200)); await Future.delayed(const Duration(milliseconds: 200));
if (clearScanDevices) { if (clearScanDevices) {
BlueManage().scanDevices.clear(); BlueManage().scanDevices.clear();
@ -237,7 +238,9 @@ class _StarLockMainPageState extends State<StarLockMainPage> with BaseWidget {
void _initLoadDataAction() { void _initLoadDataAction() {
_teamEvent = eventBus.on<RefreshLockListInfoDataEvent>().listen((event) { _teamEvent = eventBus.on<RefreshLockListInfoDataEvent>().listen((event) {
logic.pageNo = 1; logic.pageNo = 1;
getHttpData(clearScanDevices: event.clearScanDevices); getHttpData(
clearScanDevices: event.clearScanDevices,
isUnShowLoading: event.isUnShowLoading);
}); });
} }

Some files were not shown because too many files have changed in this diff Show More