From f61b7bf90b14dc6b8ae434dd17a8d57bda233bdf Mon Sep 17 00:00:00 2001 From: andyesfly <35127884@qq.com> Date: Fri, 2 Oct 2026 17:21:53 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E6=88=90=20Flutter=20?= =?UTF-8?q?=E7=89=88=E6=99=BA=E8=83=BD=E7=94=B5=E7=BD=91=20IoT=20=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=BA=94=E7=94=A8=E5=88=9D=E5=A7=8B=E5=8C=96=E6=90=AD?= =?UTF-8?q?=E5=BB=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 45 + .metadata | 33 + README.md | 17 + analysis_options.yaml | 28 + android/.gitignore | 14 + android/app/build.gradle.kts | 44 + android/app/src/debug/AndroidManifest.xml | 7 + android/app/src/main/AndroidManifest.xml | 53 + .../MainActivity.kt | 5 + .../res/drawable-v21/launch_background.xml | 12 + .../main/res/drawable/launch_background.xml | 12 + .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 544 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 442 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 721 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 1031 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 1443 bytes .../app/src/main/res/values-night/styles.xml | 18 + android/app/src/main/res/values/styles.xml | 18 + android/app/src/profile/AndroidManifest.xml | 7 + android/build.gradle.kts | 25 + .../reports/problems/problems-report.html | 663 +++++++++ android/gradle.properties | 6 + .../gradle/wrapper/gradle-wrapper.properties | 5 + android/settings.gradle.kts | 27 + ios/.gitignore | 34 + ios/Flutter/AppFrameworkInfo.plist | 24 + ios/Flutter/Debug.xcconfig | 1 + ios/Flutter/Release.xcconfig | 1 + ios/Runner.xcodeproj/project.pbxproj | 620 ++++++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + .../xcshareddata/xcschemes/Runner.xcscheme | 101 ++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + ios/Runner/AppDelegate.swift | 16 + .../AppIcon.appiconset/Contents.json | 122 ++ .../Icon-App-1024x1024@1x.png | Bin 0 -> 10932 bytes .../AppIcon.appiconset/Icon-App-20x20@1x.png | Bin 0 -> 295 bytes .../AppIcon.appiconset/Icon-App-20x20@2x.png | Bin 0 -> 406 bytes .../AppIcon.appiconset/Icon-App-20x20@3x.png | Bin 0 -> 450 bytes .../AppIcon.appiconset/Icon-App-29x29@1x.png | Bin 0 -> 282 bytes .../AppIcon.appiconset/Icon-App-29x29@2x.png | Bin 0 -> 462 bytes .../AppIcon.appiconset/Icon-App-29x29@3x.png | Bin 0 -> 704 bytes .../AppIcon.appiconset/Icon-App-40x40@1x.png | Bin 0 -> 406 bytes .../AppIcon.appiconset/Icon-App-40x40@2x.png | Bin 0 -> 586 bytes .../AppIcon.appiconset/Icon-App-40x40@3x.png | Bin 0 -> 862 bytes .../AppIcon.appiconset/Icon-App-60x60@2x.png | Bin 0 -> 862 bytes .../AppIcon.appiconset/Icon-App-60x60@3x.png | Bin 0 -> 1674 bytes .../AppIcon.appiconset/Icon-App-76x76@1x.png | Bin 0 -> 762 bytes .../AppIcon.appiconset/Icon-App-76x76@2x.png | Bin 0 -> 1226 bytes .../Icon-App-83.5x83.5@2x.png | Bin 0 -> 1418 bytes .../LaunchImage.imageset/Contents.json | 23 + .../LaunchImage.imageset/LaunchImage.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/LaunchImage@2x.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/LaunchImage@3x.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/README.md | 5 + ios/Runner/Base.lproj/LaunchScreen.storyboard | 37 + ios/Runner/Base.lproj/Main.storyboard | 26 + ios/Runner/Info.plist | 84 ++ ios/Runner/Runner-Bridging-Header.h | 1 + ios/Runner/SceneDelegate.swift | 6 + ios/RunnerTests/RunnerTests.swift | 12 + lib/app/app.dart | 37 + lib/app/router.dart | 109 ++ lib/app/tab_index.dart | 31 + lib/app/tabs_page.dart | 52 + lib/core/app_keys.dart | 7 + lib/core/env.dart | 10 + lib/core/network/api_client.dart | 242 ++++ lib/core/network/api_response.dart | 33 + lib/core/providers.dart | 15 + lib/core/storage/token_storage.dart | 49 + lib/core/theme/app_colors.dart | 103 ++ lib/core/theme/app_dimens.dart | 32 + lib/core/theme/app_theme.dart | 71 + lib/core/theme/app_typography.dart | 93 ++ lib/core/utils/format_util.dart | 46 + lib/core/utils/id_util.dart | 17 + .../auth/application/session_controller.dart | 95 ++ lib/features/auth/data/auth_api.dart | 27 + lib/features/auth/data/auth_models.dart | 80 + .../auth/presentation/login_page.dart | 279 ++++ lib/features/customer/data/customer_api.dart | 77 + .../customer/data/customer_models.dart | 143 ++ lib/features/customer/data/user_api.dart | 99 ++ .../presentation/customer_detail_page.dart | 443 ++++++ .../presentation/customer_edit_page.dart | 653 +++++++++ .../customer/presentation/customer_tab.dart | 465 ++++++ .../dashboard/data/dashboard_api.dart | 22 + .../dashboard/data/dashboard_models.dart | 159 ++ lib/features/mine/presentation/mine_tab.dart | 345 +++++ lib/features/project/data/project_api.dart | 73 + lib/features/project/data/project_models.dart | 150 ++ .../presentation/project_detail_page.dart | 338 +++++ .../project/presentation/project_tab.dart | 330 +++++ lib/features/survey/data/survey_api.dart | 95 ++ lib/features/survey/data/survey_models.dart | 357 +++++ .../survey/presentation/survey_form_page.dart | 1285 +++++++++++++++++ .../survey/presentation/survey_list_page.dart | 165 +++ lib/features/visit/data/visit_api.dart | 105 ++ lib/features/visit/data/visit_models.dart | 342 +++++ .../visit/presentation/visit_batch_page.dart | 695 +++++++++ .../visit/presentation/visit_detail_page.dart | 604 ++++++++ .../presentation/visit_execute_page.dart | 947 ++++++++++++ .../visit/presentation/visit_form_page.dart | 550 +++++++ .../visit/presentation/visit_list_page.dart | 553 +++++++ .../workbench/presentation/workbench_tab.dart | 651 +++++++++ lib/main.dart | 29 + lib/shared/widgets/app_feedback.dart | 95 ++ lib/shared/widgets/x_bottom_nav.dart | 95 ++ lib/shared/widgets/x_card.dart | 55 + lib/shared/widgets/x_chip.dart | 88 ++ lib/shared/widgets/x_common.dart | 254 ++++ lib/shared/widgets/x_icon.dart | 113 ++ lib/shared/widgets/x_top_bar.dart | 138 ++ pubspec.lock | 967 +++++++++++++ pubspec.yaml | 98 ++ test/widget_test.dart | 25 + 120 files changed, 15229 insertions(+) create mode 100644 .gitignore create mode 100644 .metadata create mode 100644 README.md create mode 100644 analysis_options.yaml create mode 100644 android/.gitignore create mode 100644 android/app/build.gradle.kts create mode 100644 android/app/src/debug/AndroidManifest.xml create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/kotlin/cn/xintong/smart_grid_iot_manage_app_flutter/MainActivity.kt create mode 100644 android/app/src/main/res/drawable-v21/launch_background.xml create mode 100644 android/app/src/main/res/drawable/launch_background.xml create mode 100644 android/app/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 android/app/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 android/app/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 android/app/src/main/res/values-night/styles.xml create mode 100644 android/app/src/main/res/values/styles.xml create mode 100644 android/app/src/profile/AndroidManifest.xml create mode 100644 android/build.gradle.kts create mode 100644 android/build/reports/problems/problems-report.html create mode 100644 android/gradle.properties create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100644 android/settings.gradle.kts create mode 100644 ios/.gitignore create mode 100644 ios/Flutter/AppFrameworkInfo.plist create mode 100644 ios/Flutter/Debug.xcconfig create mode 100644 ios/Flutter/Release.xcconfig create mode 100644 ios/Runner.xcodeproj/project.pbxproj create mode 100644 ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme create mode 100644 ios/Runner.xcworkspace/contents.xcworkspacedata create mode 100644 ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 ios/Runner/AppDelegate.swift create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png create mode 100644 ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png create mode 100644 ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md create mode 100644 ios/Runner/Base.lproj/LaunchScreen.storyboard create mode 100644 ios/Runner/Base.lproj/Main.storyboard create mode 100644 ios/Runner/Info.plist create mode 100644 ios/Runner/Runner-Bridging-Header.h create mode 100644 ios/Runner/SceneDelegate.swift create mode 100644 ios/RunnerTests/RunnerTests.swift create mode 100644 lib/app/app.dart create mode 100644 lib/app/router.dart create mode 100644 lib/app/tab_index.dart create mode 100644 lib/app/tabs_page.dart create mode 100644 lib/core/app_keys.dart create mode 100644 lib/core/env.dart create mode 100644 lib/core/network/api_client.dart create mode 100644 lib/core/network/api_response.dart create mode 100644 lib/core/providers.dart create mode 100644 lib/core/storage/token_storage.dart create mode 100644 lib/core/theme/app_colors.dart create mode 100644 lib/core/theme/app_dimens.dart create mode 100644 lib/core/theme/app_theme.dart create mode 100644 lib/core/theme/app_typography.dart create mode 100644 lib/core/utils/format_util.dart create mode 100644 lib/core/utils/id_util.dart create mode 100644 lib/features/auth/application/session_controller.dart create mode 100644 lib/features/auth/data/auth_api.dart create mode 100644 lib/features/auth/data/auth_models.dart create mode 100644 lib/features/auth/presentation/login_page.dart create mode 100644 lib/features/customer/data/customer_api.dart create mode 100644 lib/features/customer/data/customer_models.dart create mode 100644 lib/features/customer/data/user_api.dart create mode 100644 lib/features/customer/presentation/customer_detail_page.dart create mode 100644 lib/features/customer/presentation/customer_edit_page.dart create mode 100644 lib/features/customer/presentation/customer_tab.dart create mode 100644 lib/features/dashboard/data/dashboard_api.dart create mode 100644 lib/features/dashboard/data/dashboard_models.dart create mode 100644 lib/features/mine/presentation/mine_tab.dart create mode 100644 lib/features/project/data/project_api.dart create mode 100644 lib/features/project/data/project_models.dart create mode 100644 lib/features/project/presentation/project_detail_page.dart create mode 100644 lib/features/project/presentation/project_tab.dart create mode 100644 lib/features/survey/data/survey_api.dart create mode 100644 lib/features/survey/data/survey_models.dart create mode 100644 lib/features/survey/presentation/survey_form_page.dart create mode 100644 lib/features/survey/presentation/survey_list_page.dart create mode 100644 lib/features/visit/data/visit_api.dart create mode 100644 lib/features/visit/data/visit_models.dart create mode 100644 lib/features/visit/presentation/visit_batch_page.dart create mode 100644 lib/features/visit/presentation/visit_detail_page.dart create mode 100644 lib/features/visit/presentation/visit_execute_page.dart create mode 100644 lib/features/visit/presentation/visit_form_page.dart create mode 100644 lib/features/visit/presentation/visit_list_page.dart create mode 100644 lib/features/workbench/presentation/workbench_tab.dart create mode 100644 lib/main.dart create mode 100644 lib/shared/widgets/app_feedback.dart create mode 100644 lib/shared/widgets/x_bottom_nav.dart create mode 100644 lib/shared/widgets/x_card.dart create mode 100644 lib/shared/widgets/x_chip.dart create mode 100644 lib/shared/widgets/x_common.dart create mode 100644 lib/shared/widgets/x_icon.dart create mode 100644 lib/shared/widgets/x_top_bar.dart create mode 100644 pubspec.lock create mode 100644 pubspec.yaml create mode 100644 test/widget_test.dart diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..6738224 --- /dev/null +++ b/.metadata @@ -0,0 +1,33 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "00b0c91f06209d9e4a41f71b7a512d6eb3b9c694" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + base_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + - platform: android + create_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + base_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + - platform: ios + create_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + base_revision: 00b0c91f06209d9e4a41f71b7a512d6eb3b9c694 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/README.md b/README.md new file mode 100644 index 0000000..474ac2e --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# smart_grid_iot_manage_app_flutter + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +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.dev/lints. + # + # 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: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..804cb7a --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "cn.xintong.smart_grid_iot_manage_app_flutter" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // 与 uni-app 版 manifest.json 的 distribute.android.packagename 一致 + applicationId = "cn.xintong.operations" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..f7ceb2b --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/kotlin/cn/xintong/smart_grid_iot_manage_app_flutter/MainActivity.kt b/android/app/src/main/kotlin/cn/xintong/smart_grid_iot_manage_app_flutter/MainActivity.kt new file mode 100644 index 0000000..268692f --- /dev/null +++ b/android/app/src/main/kotlin/cn/xintong/smart_grid_iot_manage_app_flutter/MainActivity.kt @@ -0,0 +1,5 @@ +package cn.xintong.smart_grid_iot_manage_app_flutter + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..db77bb4b7b0906d62b1847e87f15cdcacf6a4f29 GIT binary patch literal 544 zcmeAS@N?(olHy`uVBq!ia0vp^9w5xY3?!3`olAj~WQl7;NpOBzNqJ&XDuZK6ep0G} zXKrG8YEWuoN@d~6R2!h8bpbvhu0Wd6uZuB!w&u2PAxD2eNXD>P5D~Wn-+_Wa#27Xc zC?Zj|6r#X(-D3u$NCt}(Ms06KgJ4FxJVv{GM)!I~&n8Bnc94O7-Hd)cjDZswgC;Qs zO=b+9!WcT8F?0rF7!Uys2bs@gozCP?z~o%U|N3vA*22NaGQG zlg@K`O_XuxvZ&Ks^m&R!`&1=spLvfx7oGDKDwpwW`#iqdw@AL`7MR}m`rwr|mZgU`8P7SBkL78fFf!WnuYWm$5Z0 zNXhDbCv&49sM544K|?c)WrFfiZvCi9h0O)B3Pgg&ebxsLQ05GG~ AQ2+n{ literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..17987b79bb8a35cc66c3c1fd44f5a5526c1b78be GIT binary patch literal 442 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA3?vioaBc-sk|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*D5Xx&nMcT!A!W`0S9QKQy;}1Cl^CgaH=;G9cpY;r$Q>i*pfB zP2drbID<_#qf;rPZx^FqH)F_D#*k@@q03KywUtLX8Ua?`H+NMzkczFPK3lFz@i_kW%1NOn0|D2I9n9wzH8m|-tHjsw|9>@K=iMBhxvkv6m8Y-l zytQ?X=U+MF$@3 zt`~i=@j|6y)RWMK--}M|=T`o&^Ni>IoWKHEbBXz7?A@mgWoL>!*SXo`SZH-*HSdS+ yn*9;$7;m`l>wYBC5bq;=U}IMqLzqbYCidGC!)_gkIk_C@Uy!y&wkt5C($~2D>~)O*cj@FGjOCM)M>_ixfudOh)?xMu#Fs z#}Y=@YDTwOM)x{K_j*Q;dPdJ?Mz0n|pLRx{4n|)f>SXlmV)XB04CrSJn#dS5nK2lM zrZ9#~WelCp7&e13Y$jvaEXHskn$2V!!DN-nWS__6T*l;H&Fopn?A6HZ-6WRLFP=R` zqG+CE#d4|IbyAI+rJJ`&x9*T`+a=p|0O(+s{UBcyZdkhj=yS1>AirP+0R;mf2uMgM zC}@~JfByORAh4SyRgi&!(cja>F(l*O+nd+@4m$|6K6KDn_&uvCpV23&>G9HJp{xgg zoq1^2_p9@|WEo z*X_Uko@K)qYYv~>43eQGMdbiGbo>E~Q& zrYBH{QP^@Sti!`2)uG{irBBq@y*$B zi#&(U-*=fp74j)RyIw49+0MRPMRU)+a2r*PJ$L5roHt2$UjExCTZSbq%V!HeS7J$N zdG@vOZB4v_lF7Plrx+hxo7(fCV&}fHq)$ literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..d5f1c8d34e7a88e3f88bea192c3a370d44689c3c GIT binary patch literal 1031 zcmeAS@N?(olHy`uVBq!ia0vp^6F``Q8Ax83A=Cw=BuiW)N`mv#O3D+9QW+dm@{>{( zJaZG%Q-e|yQz{EjrrIztFa`(sgt!6~Yi|1%a`XoT0ojZ}lNrNjb9xjc(B0U1_% zz5^97Xt*%oq$rQy4?0GKNfJ44uvxI)gC`h-NZ|&0-7(qS@?b!5r36oQ}zyZrNO3 zMO=Or+<~>+A&uN&E!^Sl+>xE!QC-|oJv`ApDhqC^EWD|@=#J`=d#Xzxs4ah}w&Jnc z$|q_opQ^2TrnVZ0o~wh<3t%W&flvYGe#$xqda2bR_R zvPYgMcHgjZ5nSA^lJr%;<&0do;O^tDDh~=pIxA#coaCY>&N%M2^tq^U%3DB@ynvKo}b?yu-bFc-u0JHzced$sg7S3zqI(2 z#Km{dPr7I=pQ5>FuK#)QwK?Y`E`B?nP+}U)I#c1+FM*1kNvWG|a(TpksZQ3B@sD~b zpQ2)*V*TdwjFOtHvV|;OsiDqHi=6%)o4b!)x$)%9pGTsE z-JL={-Ffv+T87W(Xpooq<`r*VzWQcgBN$$`u}f>-ZQI1BB8ykN*=e4rIsJx9>z}*o zo~|9I;xof literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..4d6372eebdb28e45604e46eeda8dd24651419bc0 GIT binary patch literal 1443 zcmb`G{WsKk6vsdJTdFg%tJav9_E4vzrOaqkWF|A724Nly!y+?N9`YV6wZ}5(X(D_N(?!*n3`|_r0Hc?=PQw&*vnU?QTFY zB_MsH|!j$PP;I}?dppoE_gA(4uc!jV&0!l7_;&p2^pxNo>PEcNJv za5_RT$o2Mf!<+r?&EbHH6nMoTsDOa;mN(wv8RNsHpG)`^ymG-S5By8=l9iVXzN_eG%Xg2@Xeq76tTZ*dGh~Lo9vl;Zfs+W#BydUw zCkZ$o1LqWQO$FC9aKlLl*7x9^0q%0}$OMlp@Kk_jHXOjofdePND+j!A{q!8~Jn+s3 z?~~w@4?egS02}8NuulUA=L~QQfm;MzCGd)XhiftT;+zFO&JVyp2mBww?;QByS_1w! zrQlx%{^cMj0|Bo1FjwY@Q8?Hx0cIPF*@-ZRFpPc#bBw{5@tD(5%sClzIfl8WU~V#u zm5Q;_F!wa$BSpqhN>W@2De?TKWR*!ujY;Yylk_X5#~V!L*Gw~;$%4Q8~Mad z@`-kG?yb$a9cHIApZDVZ^U6Xkp<*4rU82O7%}0jjHlK{id@?-wpN*fCHXyXh(bLt* zPc}H-x0e4E&nQ>y%B-(EL=9}RyC%MyX=upHuFhAk&MLbsF0LP-q`XnH78@fT+pKPW zu72MW`|?8ht^tz$iC}ZwLp4tB;Q49K!QCF3@!iB1qOI=?w z7In!}F~ij(18UYUjnbmC!qKhPo%24?8U1x{7o(+?^Zu0Hx81|FuS?bJ0jgBhEMzf< zCgUq7r2OCB(`XkKcN-TL>u5y#dD6D!)5W?`O5)V^>jb)P)GBdy%t$uUMpf$SNV31$ zb||OojAbvMP?T@$h_ZiFLFVHDmbyMhJF|-_)HX3%m=CDI+ID$0^C>kzxprBW)hw(v zr!Gmda);ICoQyhV_oP5+C%?jcG8v+D@9f?Dk*!BxY}dazmrT@64UrP3hlslANK)bq z$67n83eh}OeW&SV@HG95P|bjfqJ7gw$e+`Hxo!4cx`jdK1bJ>YDSpGKLPZ^1cv$ek zIB?0S<#tX?SJCLWdMd{-ME?$hc7A$zBOdIJ)4!KcAwb=VMov)nK;9z>x~rfT1>dS+ zZ6#`2v@`jgbqq)P22H)Tx2CpmM^o1$B+xT6`(v%5xJ(?j#>Q$+rx_R|7TzDZe{J6q zG1*EcU%tE?!kO%^M;3aM6JN*LAKUVb^xz8-Pxo#jR5(-KBeLJvA@-gxNHx0M-ZJLl z;#JwQoh~9V?`UVo#}{6ka@II>++D@%KqGpMdlQ}?9E*wFcf5(#XQnP$Dk5~%iX^>f z%$y;?M0BLp{O3a(-4A?ewryHrrD%cx#Q^%KY1H zNre$ve+vceSLZcNY4U(RBX&)oZn*Py()h)XkE?PL$!bNb{N5FVI2Y%LKEm%yvpyTP z(1P?z~7YxD~Rf<(a@_y` literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..d337529 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,25 @@ +allprojects { + repositories { + // 本机无法访问 maven.google.com / repo.maven.apache.org,仅使用国内镜像,避免长超时。 + maven { url = uri("https://maven.aliyun.com/repository/google") } + maven { url = uri("https://maven.aliyun.com/repository/public") } + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/build/reports/problems/problems-report.html b/android/build/reports/problems/problems-report.html new file mode 100644 index 0000000..4622f69 --- /dev/null +++ b/android/build/reports/problems/problems-report.html @@ -0,0 +1,663 @@ + + + + + + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..38eff2a --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# 源项目目录含中文(智能电网),AGP 默认会拒绝构建非 ASCII 路径,此处按官方提示放行。 +android.overridePathCheck=true +# Kotlin 增量编译在非 ASCII 路径下会因路径转义导致 "different roots" 崩溃,关闭增量编译规避。 +kotlin.incremental=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..2d55f39 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,27 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + // 本机无法访问 maven.google.com / repo.maven.apache.org,仅使用国内镜像,避免长超时。 + maven { url = uri("https://maven.aliyun.com/repository/google") } + maven { url = uri("https://maven.aliyun.com/repository/public") } + maven { url = uri("https://maven.aliyun.com/repository/gradle-plugin") } + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..49a1c86 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,620 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = cn.xintong.operations; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = cn.xintong.operations.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = cn.xintong.operations.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = cn.xintong.operations.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = cn.xintong.operations; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = cn.xintong.operations; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..c30b367 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..dc9ada4725e9b0ddb1deab583e5b5102493aa332 GIT binary patch literal 10932 zcmeHN2~<R zh`|8`A_PQ1nSu(UMFx?8j8PC!!VDphaL#`F42fd#7Vlc`zIE4n%Y~eiz4y1j|NDpi z?<@|pSJ-HM`qifhf@m%MamgwK83`XpBA<+azdF#2QsT{X@z0A9Bq>~TVErigKH1~P zRX-!h-f0NJ4Mh++{D}J+K>~~rq}d%o%+4dogzXp7RxX4C>Km5XEI|PAFDmo;DFm6G zzjVoB`@qW98Yl0Kvc-9w09^PrsobmG*Eju^=3f?0o-t$U)TL1B3;sZ^!++3&bGZ!o-*6w?;oOhf z=A+Qb$scV5!RbG+&2S}BQ6YH!FKb0``VVX~T$dzzeSZ$&9=X$3)_7Z{SspSYJ!lGE z7yig_41zpQ)%5dr4ff0rh$@ky3-JLRk&DK)NEIHecf9c*?Z1bUB4%pZjQ7hD!A0r-@NF(^WKdr(LXj|=UE7?gBYGgGQV zidf2`ZT@pzXf7}!NH4q(0IMcxsUGDih(0{kRSez&z?CFA0RVXsVFw3^u=^KMtt95q z43q$b*6#uQDLoiCAF_{RFc{!H^moH_cmll#Fc^KXi{9GDl{>%+3qyfOE5;Zq|6#Hb zp^#1G+z^AXfRKaa9HK;%b3Ux~U@q?xg<2DXP%6k!3E)PA<#4$ui8eDy5|9hA5&{?v z(-;*1%(1~-NTQ`Is1_MGdQ{+i*ccd96ab$R$T3=% zw_KuNF@vI!A>>Y_2pl9L{9h1-C6H8<)J4gKI6{WzGBi<@u3P6hNsXG=bRq5c+z;Gc3VUCe;LIIFDmQAGy+=mRyF++u=drBWV8-^>0yE9N&*05XHZpPlE zxu@?8(ZNy7rm?|<+UNe0Vs6&o?l`Pt>P&WaL~M&#Eh%`rg@Mbb)J&@DA-wheQ>hRV z<(XhigZAT z>=M;URcdCaiO3d^?H<^EiEMDV+7HsTiOhoaMX%P65E<(5xMPJKxf!0u>U~uVqnPN7T!X!o@_gs3Ct1 zlZ_$5QXP4{Aj645wG_SNT&6m|O6~Tsl$q?nK*)(`{J4b=(yb^nOATtF1_aS978$x3 zx>Q@s4i3~IT*+l{@dx~Hst21fR*+5}S1@cf>&8*uLw-0^zK(+OpW?cS-YG1QBZ5q! zgTAgivzoF#`cSz&HL>Ti!!v#?36I1*l^mkrx7Y|K6L#n!-~5=d3;K<;Zqi|gpNUn_ z_^GaQDEQ*jfzh;`j&KXb66fWEk1K7vxQIMQ_#Wu_%3 z4Oeb7FJ`8I>Px;^S?)}2+4D_83gHEq>8qSQY0PVP?o)zAv3K~;R$fnwTmI-=ZLK`= zTm+0h*e+Yfr(IlH3i7gUclNH^!MU>id$Jw>O?2i0Cila#v|twub21@e{S2v}8Z13( zNDrTXZVgris|qYm<0NU(tAPouG!QF4ZNpZPkX~{tVf8xY690JqY1NVdiTtW+NqyRP zZ&;T0ikb8V{wxmFhlLTQ&?OP7 z;(z*<+?J2~z*6asSe7h`$8~Se(@t(#%?BGLVs$p``;CyvcT?7Y!{tIPva$LxCQ&4W z6v#F*);|RXvI%qnoOY&i4S*EL&h%hP3O zLsrFZhv&Hu5tF$Lx!8(hs&?!Kx5&L(fdu}UI5d*wn~A`nPUhG&Rv z2#ixiJdhSF-K2tpVL=)5UkXRuPAFrEW}7mW=uAmtVQ&pGE-&az6@#-(Te^n*lrH^m@X-ftVcwO_#7{WI)5v(?>uC9GG{lcGXYJ~Q8q zbMFl7;t+kV;|;KkBW2!P_o%Czhw&Q(nXlxK9ak&6r5t_KH8#1Mr-*0}2h8R9XNkr zto5-b7P_auqTJb(TJlmJ9xreA=6d=d)CVbYP-r4$hDn5|TIhB>SReMfh&OVLkMk-T zYf%$taLF0OqYF?V{+6Xkn>iX@TuqQ?&cN6UjC9YF&%q{Ut3zv{U2)~$>-3;Dp)*(? zg*$mu8^i=-e#acaj*T$pNowo{xiGEk$%DusaQiS!KjJH96XZ-hXv+jk%ard#fu=@Q z$AM)YWvE^{%tDfK%nD49=PI|wYu}lYVbB#a7wtN^Nml@CE@{Gv7+jo{_V?I*jkdLD zJE|jfdrmVbkfS>rN*+`#l%ZUi5_bMS<>=MBDNlpiSb_tAF|Zy`K7kcp@|d?yaTmB^ zo?(vg;B$vxS|SszusORgDg-*Uitzdi{dUV+glA~R8V(?`3GZIl^egW{a919!j#>f` znL1o_^-b`}xnU0+~KIFLQ)$Q6#ym%)(GYC`^XM*{g zv3AM5$+TtDRs%`2TyR^$(hqE7Y1b&`Jd6dS6B#hDVbJlUXcG3y*439D8MrK!2D~6gn>UD4Imctb z+IvAt0iaW73Iq$K?4}H`7wq6YkTMm`tcktXgK0lKPmh=>h+l}Y+pDtvHnG>uqBA)l zAH6BV4F}v$(o$8Gfo*PB>IuaY1*^*`OTx4|hM8jZ?B6HY;F6p4{`OcZZ(us-RVwDx zUzJrCQlp@mz1ZFiSZ*$yX3c_#h9J;yBE$2g%xjmGF4ca z&yL`nGVs!Zxsh^j6i%$a*I3ZD2SoNT`{D%mU=LKaEwbN(_J5%i-6Va?@*>=3(dQy` zOv%$_9lcy9+(t>qohkuU4r_P=R^6ME+wFu&LA9tw9RA?azGhjrVJKy&8=*qZT5Dr8g--d+S8zAyJ$1HlW3Olryt`yE zFIph~Z6oF&o64rw{>lgZISC6p^CBer9C5G6yq%?8tC+)7*d+ib^?fU!JRFxynRLEZ zj;?PwtS}Ao#9whV@KEmwQgM0TVP{hs>dg(1*DiMUOKHdQGIqa0`yZnHk9mtbPfoLx zo;^V6pKUJ!5#n`w2D&381#5#_t}AlTGEgDz$^;u;-vxDN?^#5!zN9ngytY@oTv!nc zp1Xn8uR$1Z;7vY`-<*?DfPHB;x|GUi_fI9@I9SVRv1)qETbNU_8{5U|(>Du84qP#7 z*l9Y$SgA&wGbj>R1YeT9vYjZuC@|{rajTL0f%N@>3$DFU=`lSPl=Iv;EjuGjBa$Gw zHD-;%YOE@<-!7-Mn`0WuO3oWuL6tB2cpPw~Nvuj|KM@))ixuDK`9;jGMe2d)7gHin zS<>k@!x;!TJEc#HdL#RF(`|4W+H88d4V%zlh(7#{q2d0OQX9*FW^`^_<3r$kabWAB z$9BONo5}*(%kx zOXi-yM_cmB3>inPpI~)duvZykJ@^^aWzQ=eQ&STUa}2uT@lV&WoRzkUoE`rR0)`=l zFT%f|LA9fCw>`enm$p7W^E@U7RNBtsh{_-7vVz3DtB*y#*~(L9+x9*wn8VjWw|Q~q zKFsj1Yl>;}%MG3=PY`$g$_mnyhuV&~O~u~)968$0b2!Jkd;2MtAP#ZDYw9hmK_+M$ zb3pxyYC&|CuAbtiG8HZjj?MZJBFbt`ryf+c1dXFuC z0*ZQhBzNBd*}s6K_G}(|Z_9NDV162#y%WSNe|FTDDhx)K!c(mMJh@h87@8(^YdK$&d*^WQe8Z53 z(|@MRJ$Lk-&ii74MPIs80WsOFZ(NX23oR-?As+*aq6b?~62@fSVmM-_*cb1RzZ)`5$agEiL`-E9s7{GM2?(KNPgK1(+c*|-FKoy}X(D_b#etO|YR z(BGZ)0Ntfv-7R4GHoXp?l5g#*={S1{u-QzxCGng*oWr~@X-5f~RA14b8~B+pLKvr4 zfgL|7I>jlak9>D4=(i(cqYf7#318!OSR=^`xxvI!bBlS??`xxWeg?+|>MxaIdH1U~#1tHu zB{QMR?EGRmQ_l4p6YXJ{o(hh-7Tdm>TAX380TZZZyVkqHNzjUn*_|cb?T? zt;d2s-?B#Mc>T-gvBmQZx(y_cfkXZO~{N zT6rP7SD6g~n9QJ)8F*8uHxTLCAZ{l1Y&?6v)BOJZ)=R-pY=Y=&1}jE7fQ>USS}xP#exo57uND0i*rEk@$;nLvRB@u~s^dwRf?G?_enN@$t* zbL%JO=rV(3Ju8#GqUpeE3l_Wu1lN9Y{D4uaUe`g>zlj$1ER$6S6@{m1!~V|bYkhZA z%CvrDRTkHuajMU8;&RZ&itnC~iYLW4DVkP<$}>#&(`UO>!n)Po;Mt(SY8Yb`AS9lt znbX^i?Oe9r_o=?})IHKHoQGKXsps_SE{hwrg?6dMI|^+$CeC&z@*LuF+P`7LfZ*yr+KN8B4{Nzv<`A(wyR@!|gw{zB6Ha ziwPAYh)oJ(nlqSknu(8g9N&1hu0$vFK$W#mp%>X~AU1ay+EKWcFdif{% z#4!4aoVVJ;ULmkQf!ke2}3hqxLK>eq|-d7Ly7-J9zMpT`?dxo6HdfJA|t)?qPEVBDv z{y_b?4^|YA4%WW0VZd8C(ZgQzRI5(I^)=Ub`Y#MHc@nv0w-DaJAqsbEHDWG8Ia6ju zo-iyr*sq((gEwCC&^TYBWt4_@|81?=B-?#P6NMff(*^re zYqvDuO`K@`mjm_Jd;mW_tP`3$cS?R$jR1ZN09$YO%_iBqh5ftzSpMQQtxKFU=FYmP zeY^jph+g<4>YO;U^O>-NFLn~-RqlHvnZl2yd2A{Yc1G@Ga$d+Q&(f^tnPf+Z7serIU};17+2DU_f4Z z@GaPFut27d?!YiD+QP@)T=77cR9~MK@bd~pY%X(h%L={{OIb8IQmf-!xmZkm8A0Ga zQSWONI17_ru5wpHg3jI@i9D+_Y|pCqVuHJNdHUauTD=R$JcD2K_liQisqG$(sm=k9;L* z!L?*4B~ql7uioSX$zWJ?;q-SWXRFhz2Jt4%fOHA=Bwf|RzhwqdXGr78y$J)LR7&3T zE1WWz*>GPWKZ0%|@%6=fyx)5rzUpI;bCj>3RKzNG_1w$fIFCZ&UR0(7S?g}`&Pg$M zf`SLsz8wK82Vyj7;RyKmY{a8G{2BHG%w!^T|Njr!h9TO2LaP^_f22Q1=l$QiU84ao zHe_#{S6;qrC6w~7{y(hs-?-j?lbOfgH^E=XcSgnwW*eEz{_Z<_xN#0001NP)t-s|Ns9~ z#rXRE|M&d=0au&!`~QyF`q}dRnBDt}*!qXo`c{v z{Djr|@Adh0(D_%#_&mM$D6{kE_x{oE{l@J5@%H*?%=t~i_`ufYOPkAEn!pfkr2$fs z652Tz0001XNklqeeKN4RM4i{jKqmiC$?+xN>3Apn^ z0QfuZLym_5b<*QdmkHjHlj811{If)dl(Z2K0A+ekGtrFJb?g|wt#k#pV-#A~bK=OT ts8>{%cPtyC${m|1#B1A6#u!Q;umknL1chzTM$P~L002ovPDHLkV1lTfnu!1a literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..797d452e458972bab9d994556c8305db4c827017 GIT binary patch literal 406 zcmV;H0crk;P))>cdjpWt&rLJgVp-t?DREyuq1A%0Z4)6_WsQ7{nzjN zo!X zGXV)2i3kcZIL~_j>uIKPK_zib+3T+Nt3Mb&Br)s)UIaA}@p{wDda>7=Q|mGRp7pqY zkJ!7E{MNz$9nOwoVqpFb)}$IP24Wn2JJ=Cw(!`OXJBr45rP>>AQr$6c7slJWvbpNW z@KTwna6d?PP>hvXCcp=4F;=GR@R4E7{4VU^0p4F>v^#A|>07*qoM6N<$f*5nx ACIA2c literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..6ed2d933e1120817fe9182483a228007b18ab6ae GIT binary patch literal 450 zcmV;z0X_bSP)iGWQ_5NJQ_~rNh*z)}eT%KUb z`7gNk0#AwF^#0T0?hIa^`~Ck;!}#m+_uT050aTR(J!bU#|IzRL%^UsMS#KsYnTF*!YeDOytlP4VhV?b} z%rz_<=#CPc)tU1MZTq~*2=8~iZ!lSa<{9b@2Jl;?IEV8)=fG217*|@)CCYgFze-x? zIFODUIA>nWKpE+bn~n7;-89sa>#DR>TSlqWk*!2hSN6D~Qb#VqbP~4Fk&m`@1$JGr zXPIdeRE&b2Thd#{MtDK$px*d3-Wx``>!oimf%|A-&-q*6KAH)e$3|6JV%HX{Hig)k suLT-RhftRq8b9;(V=235Wa|I=027H2wCDra;{X5v07*qoM6N<$f;9x^2LJ#7 literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..4cd7b0099ca80c806f8fe495613e8d6c69460d76 GIT binary patch literal 282 zcmV+#0p(^bcu7P-R4C8Q z&e;xxFbF_Vrezo%_kH*OKhshZ6BFpG-Y1e10`QXJKbND7AMQ&cMj60B5TNObaZxYybcN07*qoM6N<$g3m;S%K!iX literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..fe730945a01f64a61e2235dbe3f45b08f7729182 GIT binary patch literal 462 zcmV;<0WtoGP)-}iV`2<;=$?g5M=KQbZ{F&YRNy7Nn@%_*5{gvDM0aKI4?ESmw z{NnZg)A0R`+4?NF_RZexyVB&^^ZvN!{I28tr{Vje;QNTz`dG&Jz0~Ek&f2;*Z7>B|cg}xYpxEFY+0YrKLF;^Q+-HreN0P{&i zK~zY`?b7ECf-n?@;d<&orQ*Q7KoR%4|C>{W^h6@&01>0SKS`dn{Q}GT%Qj_{PLZ_& zs`MFI#j-(>?bvdZ!8^xTwlY{qA)T4QLbY@j(!YJ7aXJervHy6HaG_2SB`6CC{He}f zHVw(fJWApwPq!6VY7r1w-Fs)@ox~N+q|w~e;JI~C4Vf^@d>Wvj=fl`^u9x9wd9 zR%3*Q+)t%S!MU_`id^@&Y{y7-r98lZX0?YrHlfmwb?#}^1b{8g&KzmkE(L>Z&)179 zp<)v6Y}pRl100G2FL_t(o!|l{-Q-VMg#&MKg7c{O0 z2wJImOS3Gy*Z2Qifdv~JYOp;v+U)a|nLoc7hNH;I$;lzDt$}rkaFw1mYK5_0Q(Sut zvbEloxON7$+HSOgC9Z8ltuC&0OSF!-mXv5caV>#bc3@hBPX@I$58-z}(ZZE!t-aOG zpjNkbau@>yEzH(5Yj4kZiMH32XI!4~gVXNnjAvRx;Sdg^`>2DpUEwoMhTs_st8pKG z(%SHyHdU&v%f36~uERh!bd`!T2dw;z6PrOTQ7Vt*#9F2uHlUVnb#ev_o^fh}Dzmq} zWtlk35}k=?xj28uO|5>>$yXadTUE@@IPpgH`gJ~Ro4>jd1IF|(+IX>8M4Ps{PNvmI zNj4D+XgN83gPt_Gm}`Ybv{;+&yu-C(Grdiahmo~BjG-l&mWM+{e5M1sm&=xduwgM9 z`8OEh`=F3r`^E{n_;%9weN{cf2%7=VzC@cYj+lg>+3|D|_1C@{hcU(DyQG_BvBWe? zvTv``=%b1zrol#=R`JB)>cdjpWt&rLJgVp-t?DREyuq1A%0Z4)6_WsQ7{nzjN zo!X zGXV)2i3kcZIL~_j>uIKPK_zib+3T+Nt3Mb&Br)s)UIaA}@p{wDda>7=Q|mGRp7pqY zkJ!7E{MNz$9nOwoVqpFb)}$IP24Wn2JJ=Cw(!`OXJBr45rP>>AQr$6c7slJWvbpNW z@KTwna6d?PP>hvXCcp=4F;=GR@R4E7{4VU^0p4F>v^#A|>07*qoM6N<$f*5nx ACIA2c literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..502f463a9bc882b461c96aadf492d1729e49e725 GIT binary patch literal 586 zcmV-Q0=4~#P)+}#`wDE{8-2Mebf5<{{PqV{TgVcv*r8?UZ3{-|G?_}T*&y;@cqf{ z{Q*~+qr%%p!1pS*_Uicl#q9lc(D`!D`LN62sNwq{oYw(Wmhk)k<@f$!$@ng~_5)Ru z0Z)trIA5^j{DIW^c+vT2%lW+2<(RtE2wR;4O@)Tm`Xr*?A(qYoM}7i5Yxw>D(&6ou zxz!_Xr~yNF+waPe00049Nkl*;a!v6h%{rlvIH#gW3s8p;bFr=l}mRqpW2h zw=OA%hdyL~z+UHOzl0eKhEr$YYOL-c-%Y<)=j?(bzDweB7{b+%_ypvm_cG{SvM=DK zhv{K@m>#Bw>2W$eUI#iU)Wdgs8Y3U+A$Gd&{+j)d)BmGKx+43U_!tik_YlN)>$7G! zhkE!s;%oku3;IwG3U^2kw?z+HM)jB{@zFhK8P#KMSytSthr+4!c(5c%+^UBn`0X*2 zy3(k600_CSZj?O$Qu%&$;|TGUJrptR(HzyIx>5E(2r{eA(<6t3e3I0B)7d6s7?Z5J zZ!rtKvA{MiEBm&KFtoifx>5P^Z=vl)95XJn()aS5%ad(s?4-=Tkis9IGu{`Fy8r+H07*qoM6N<$f20Z)wqMt%V?S?~D#06};F zA3KcL`Wb+>5ObvgQIG&ig8(;V04hz?@cqy3{mSh8o!|U|)cI!1_+!fWH@o*8vh^CU z^ws0;(c$gI+2~q^tO#GDHf@=;DncUw00J^eL_t(&-tE|HQ`%4vfZ;WsBqu-$0nu1R zq^Vj;p$clf^?twn|KHO+IGt^q#a3X?w9dXC@*yxhv&l}F322(8Y1&=P&I}~G@#h6; z1CV9ecD9ZEe87{{NtI*)_aJ<`kJa z?5=RBtFF50s;jQLFil-`)m2wrb=6h(&brpj%nG_U&ut~$?8Rokzxi8zJoWr#2dto5 zOX_URcc<1`Iky+jc;A%Vzx}1QU{2$|cKPom2Vf1{8m`vja4{F>HS?^Nc^rp}xo+Nh zxd}eOm`fm3@MQC1< zIk&aCjb~Yh%5+Yq0`)D;q{#-Uqlv*o+Oor zE!I71Z@ASH3grl8&P^L0WpavHoP|UX4e?!igT`4?AZk$hu*@%6WJ;zDOGlw7kj@ zY5!B-0ft0f?Lgb>C;$Ke07*qoM6N<$f~t1N9smFU literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0ec303439225b78712f49115768196d8d76f6790 GIT binary patch literal 862 zcmV-k1EKthP)20Z)wqMt%V?S?~D#06};F zA3KcL`Wb+>5ObvgQIG&ig8(;V04hz?@cqy3{mSh8o!|U|)cI!1_+!fWH@o*8vh^CU z^ws0;(c$gI+2~q^tO#GDHf@=;DncUw00J^eL_t(&-tE|HQ`%4vfZ;WsBqu-$0nu1R zq^Vj;p$clf^?twn|KHO+IGt^q#a3X?w9dXC@*yxhv&l}F322(8Y1&=P&I}~G@#h6; z1CV9ecD9ZEe87{{NtI*)_aJ<`kJa z?5=RBtFF50s;jQLFil-`)m2wrb=6h(&brpj%nG_U&ut~$?8Rokzxi8zJoWr#2dto5 zOX_URcc<1`Iky+jc;A%Vzx}1QU{2$|cKPom2Vf1{8m`vja4{F>HS?^Nc^rp}xo+Nh zxd}eOm`fm3@MQC1< zIk&aCjb~Yh%5+Yq0`)D;q{#-Uqlv*o+Oor zE!I71Z@ASH3grl8&P^L0WpavHoP|UX4e?!igT`4?AZk$hu*@%6WJ;zDOGlw7kj@ zY5!B-0ft0f?Lgb>C;$Ke07*qoM6N<$f~t1N9smFU literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..e9f5fea27c705180eb716271f41b582e76dcbd90 GIT binary patch literal 1674 zcmV;526g#~P){YQnis^a@{&-nmRmq)<&%Mztj67_#M}W?l>kYSliK<%xAp;0j{!}J0!o7b zE>q9${Lb$D&h7k=+4=!ek^n+`0zq>LL1O?lVyea53S5x`Nqqo2YyeuIrQrJj9XjOp z{;T5qbj3}&1vg1VK~#9!?b~^C5-}JC@Pyrv-6dSEqJqT}#j9#dJ@GzT@B8}x zU&J@bBI>f6w6en+CeI)3^kC*U?}X%OD8$Fd$H&LV$H&LV$H&LV#|K5~mLYf|VqzOc zkc7qL~0sOYuM{tG`rYEDV{DWY`Z8&)kW*hc2VkBuY+^Yx&92j&StN}Wp=LD zxoGxXw6f&8sB^u})h@b@z0RBeD`K7RMR9deyL(ZJu#39Z>rT)^>v}Khq8U-IbIvT> z?4pV9qGj=2)TNH3d)=De<+^w;>S7m_eFKTvzeaBeir45xY!^m!FmxnljbSS_3o=g( z->^wC9%qkR{kbGnW8MfFew_o9h3(r55Is`L$8KI@d+*%{=Nx+FXJ98L0PjFIu;rGnnfY zn1R5Qnp<{Jq0M1vX=X&F8gtLmcWv$1*M@4ZfF^9``()#hGTeKeP`1!iED ztNE(TN}M5}3Bbc*d=FIv`DNv&@|C6yYj{sSqUj5oo$#*0$7pu|Dd2TLI>t5%I zIa4Dvr(iayb+5x=j*Vum9&irk)xV1`t509lnPO0%skL8_1c#Xbamh(2@f?4yUI zhhuT5<#8RJhGz4%b$`PJwKPAudsm|at?u;*hGgnA zU1;9gnxVBC)wA(BsB`AW54N{|qmikJR*%x0c`{LGsSfa|NK61pYH(r-UQ4_JXd!Rsz)=k zL{GMc5{h138)fF5CzHEDM>+FqY)$pdN3}Ml+riTgJOLN0F*Vh?{9ESR{SVVg>*>=# zix;VJHPtvFFCRY$Ks*F;VX~%*r9F)W`PmPE9F!(&s#x07n2<}?S{(ygpXgX-&B&OM zONY&BRQ(#%0%jeQs?oJ4P!p*R98>qCy5p8w>_gpuh39NcOlp)(wOoz0sY-Qz55eB~ z7OC-fKBaD1sE3$l-6QgBJO!n?QOTza`!S_YK z_v-lm^7{VO^8Q@M_^8F)09Ki6%=s?2_5eupee(w1FB%aqSweusQ-T+CH0Xt{` zFjMvW{@C&TB)k25()nh~_yJ9coBRL(0oO@HK~z}7?bm5j;y@69;bvlHb2tf!$ReA~x{22wTq550 z?f?Hnw(;m3ip30;QzdV~7pi!wyMYhDtXW#cO7T>|f=bdFhu+F!zMZ2UFj;GUKX7tI z;hv3{q~!*pMj75WP_c}>6)IWvg5_yyg<9Op()eD1hWC19M@?_9_MHec{Z8n3FaF{8 z;u`Mw0ly(uE>*CgQYv{be6ab2LWhlaH1^iLIM{olnag$78^Fd}%dR7;JECQ+hmk|o z!u2&!3MqPfP5ChDSkFSH8F2WVOEf0(E_M(JL17G}Y+fg0_IuW%WQ zG(mG&u?|->YSdk0;8rc{yw2@2Z&GA}z{Wb91Ooz9VhA{b2DYE7RmG zjL}?eq#iX%3#k;JWMx_{^2nNax`xPhByFiDX+a7uTGU|otOvIAUy|dEKkXOm-`aWS z27pUzD{a)Ct<6p{{3)+lq@i`t@%>-wT4r?*S}k)58e09WZYP0{{R3FC5Sl00039P)t-s|Ns9~ z#rP?<_5oL$Q^olD{r_0T`27C={r>*`|Nj71npVa5OTzc(_WfbW_({R{p56NV{r*M2 z_xt?)2V0#0NsfV0u>{42ctGP(8vQj-Btk1n|O0ZD=YLwd&R{Ko41Gr9H= zY@z@@bOAMB5Ltl$E>bJJ{>JP30ZxkmI%?eW{k`b?Wy<&gOo;dS`~CR$Vwb@XWtR|N zi~t=w02?-0&j0TD{>bb6sNwsK*!p?V`RMQUl(*DVjk-9Cx+-z1KXab|Ka2oXhX5f% z`$|e!000AhNklrxs)5QTeTVRiEmz~MKK1WAjCw(c-JK6eox;2O)?`? zTG`AHia671e^vgmp!llKp|=5sVHk#C7=~epA~VAf-~%aPC=%Qw01h8mnSZ|p?hz91 z7p83F3%LVu9;S$tSI$C^%^yud1dfTM_6p2|+5Ejp$bd`GDvbR|xit>i!ZD&F>@CJrPmu*UjD&?DfZs=$@e3FQA(vNiU+$A*%a} z?`XcG2jDxJ_ZQ#Md`H{4Lpf6QBDp81_KWZ6Tk#yCy1)32zO#3<7>b`eT7UyYH1eGz z;O(rH$=QR*L%%ZcBpc=eGua?N55nD^K(8<#gl2+pN_j~b2MHs4#mcLmv%DkspS-3< zpI1F=^9siI0s-;IN_IrA;5xm~3?3!StX}pUv0vkxMaqm+zxrg7X7(I&*N~&dEd0kD z-FRV|g=|QuUsuh>-xCI}vD2imzYIOIdcCVV=$Bz@*u0+Bs<|L^)32nN*=wu3n%Ynw z@1|eLG>!8ruU1pFXUfb`j>(=Gy~?Rn4QJ-c3%3T|(Frd!bI`9u&zAnyFYTqlG#&J7 zAkD(jpw|oZLNiA>;>hgp1KX7-wxC~31II47gc zHcehD6Uxlf%+M^^uN5Wc*G%^;>D5qT{>=uxUhX%WJu^Z*(_Wq9y}npFO{Hhb>s6<9 zNi0pHXWFaVZnb)1+RS&F)xOv6&aeILcI)`k#0YE+?e)5&#r7J#c`3Z7x!LpTc01dx zrdC3{Z;joZ^KN&))zB_i)I9fWedoN>Zl-6_Iz+^G&*ak2jpF07*qoM6N<$f;w%0(f|Me literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0467bf12aa4d28f374bb26596605a46dcbb3e7c8 GIT binary patch literal 1418 zcmV;51$Fv~P)q zKfU)WzW*n(@|xWGCA9ScMt*e9`2kdxPQ&&>|-UCa7_51w+ zLUsW@ZzZSW0y$)Hp~e9%PvP|a03ks1`~K?q{u;6NC8*{AOqIUq{CL&;p56Lf$oQGq z^={4hPQv)y=I|4n+?>7Fim=dxt1 z2H+Dm+1+fh+IF>G0SjJMkQQre1x4|G*Z==(Ot&kCnUrL4I(rf(ucITwmuHf^hXiJT zkdTm&kdTm&kdTm&kdP`esgWG0BcWCVkVZ&2dUwN`cgM8QJb`Z7Z~e<&Yj2(}>Tmf` zm1{eLgw!b{bXkjWbF%dTkTZEJWyWOb##Lfw4EK2}<0d6%>AGS{po>WCOy&f$Tay_> z?NBlkpo@s-O;0V%Y_Xa-G#_O08q5LR*~F%&)}{}r&L%Sbs8AS4t7Y0NEx*{soY=0MZExqA5XHQkqi#4gW3 zqODM^iyZl;dvf)-bOXtOru(s)Uc7~BFx{w-FK;2{`VA?(g&@3z&bfLFyctOH!cVsF z7IL=fo-qBndRUm;kAdXR4e6>k-z|21AaN%ubeVrHl*<|s&Ax@W-t?LR(P-24A5=>a z*R9#QvjzF8n%@1Nw@?CG@6(%>+-0ASK~jEmCV|&a*7-GKT72W<(TbSjf)&Eme6nGE z>Gkj4Sq&2e+-G%|+NM8OOm5zVl9{Z8Dd8A5z3y8mZ=4Bv4%>as_{9cN#bm~;h>62( zdqY93Zy}v&c4n($Vv!UybR8ocs7#zbfX1IY-*w~)p}XyZ-SFC~4w>BvMVr`dFbelV{lLL0bx7@*ZZdebr3`sP;? zVImji)kG)(6Juv0lz@q`F!k1FE;CQ(D0iG$wchPbKZQELlsZ#~rt8#90Y_Xh&3U-< z{s<&cCV_1`^TD^ia9!*mQDq& zn2{r`j};V|uV%_wsP!zB?m%;FeaRe+X47K0e+KE!8C{gAWF8)lCd1u1%~|M!XNRvw zvtqy3iz0WSpWdhn6$hP8PaRBmp)q`#PCA`Vd#Tc$@f1tAcM>f_I@bC)hkI9|o(Iqv zo}Piadq!j76}004RBio<`)70k^`K1NK)q>w?p^C6J2ZC!+UppiK6&y3Kmbv&O!oYF z34$0Z;QO!JOY#!`qyGH<3Pd}Pt@q*A0V=3SVtWKRR8d8Z&@)3qLPA19LPA19LPEUC YUoZo%k(ykuW&i*H07*qoM6N<$f+CH{y8r+H literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..6d285b9 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,84 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + 鑫潼智电运营管理 + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + smart_grid_iot_manage_app_flutter + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + NSCameraUsageDescription + 用于拍摄勘测现场照片与拜访取证照片 + NSPhotoLibraryUsageDescription + 用于选择勘测现场照片与拜访取证照片 + NSLocationWhenInUseUsageDescription + 用于拜访签到时记录当前位置 + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + NSLocalNetworkUsageDescription + 用于访问局域网内的运营管理后端服务 + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/app/app.dart b/lib/app/app.dart new file mode 100644 index 0000000..3678156 --- /dev/null +++ b/lib/app/app.dart @@ -0,0 +1,37 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../core/app_keys.dart'; +import '../core/theme/app_theme.dart'; +import '../core/theme/app_typography.dart'; +import 'router.dart'; + +class SmartGridApp extends ConsumerWidget { + const SmartGridApp({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final router = ref.watch(routerProvider); + + return MaterialApp.router( + title: '鑫潼智电运营管理', + debugShowCheckedModeBanner: false, + theme: AppTheme.build(), + routerConfig: router, + scaffoldMessengerKey: AppKeys.scaffoldMessenger, + locale: const Locale('zh', 'CN'), + supportedLocales: const [Locale('zh', 'CN'), Locale('en', 'US')], + localizationsDelegates: const [ + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + // 对应 App.vue 中挂在 `page` 上的全局字体设置:15px / 行高 1.6 / on-surface。 + builder: (context, child) => DefaultTextStyle( + style: appDefaultTextStyle, + child: child ?? const SizedBox.shrink(), + ), + ); + } +} \ No newline at end of file diff --git a/lib/app/router.dart b/lib/app/router.dart new file mode 100644 index 0000000..1255bad --- /dev/null +++ b/lib/app/router.dart @@ -0,0 +1,109 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../core/app_keys.dart'; +import '../features/auth/application/session_controller.dart'; +import '../features/auth/presentation/login_page.dart'; +import '../features/customer/presentation/customer_detail_page.dart'; +import '../features/customer/presentation/customer_edit_page.dart'; +import '../features/project/presentation/project_detail_page.dart'; +import '../features/survey/presentation/survey_form_page.dart'; +import '../features/survey/presentation/survey_list_page.dart'; +import '../features/visit/presentation/visit_batch_page.dart'; +import '../features/visit/presentation/visit_detail_page.dart'; +import '../features/visit/presentation/visit_execute_page.dart'; +import '../features/visit/presentation/visit_form_page.dart'; +import '../features/visit/presentation/visit_list_page.dart'; +import 'tabs_page.dart'; + +/// 会话语义变化时驱动 go_router 重新执行 `redirect`。 +class _SessionRefresh extends ChangeNotifier { + void bump() => notifyListeners(); +} + +/// 路由表,对应 uni-app 版 `pages.json` 的 12 个页面。 +/// +/// 除登录页与 Tab 容器页外,其余均为二级页,统一使用主题里的 +/// `CupertinoPageTransitionsBuilder`(新页面从右侧滑入), +/// 与源项目 `animationType: slide-in-right` 的表现一致。 +final routerProvider = Provider((ref) { + final refresh = _SessionRefresh(); + ref.listen(sessionProvider, (_, _) => refresh.bump()); + ref.onDispose(refresh.dispose); + + int? queryId(GoRouterState state) => + int.tryParse(state.uri.queryParameters['id'] ?? ''); + + return GoRouter( + navigatorKey: AppKeys.rootNavigator, + initialLocation: '/login', + refreshListenable: refresh, + redirect: (context, state) { + final loggedIn = ref.read(sessionProvider).isLoggedIn; + final atLogin = state.matchedLocation == '/login'; + if (!loggedIn) return atLogin ? null : '/login'; + if (atLogin) return '/tabs'; + return null; + }, + routes: [ + GoRoute(path: '/login', builder: (context, state) => const LoginPage()), + GoRoute(path: '/tabs', builder: (context, state) => const TabsPage()), + + // 客户模块 + GoRoute( + path: '/customer/detail/:id', + builder: (context, state) => + CustomerDetailPage(id: int.parse(state.pathParameters['id']!)), + ), + GoRoute( + path: '/customer/edit', + builder: (context, state) => CustomerEditPage(id: queryId(state)), + ), + + // 拜访模块 + GoRoute( + path: '/visit', + builder: (context, state) => const VisitListPage(), + ), + GoRoute( + path: '/visit/detail/:id', + builder: (context, state) => + VisitDetailPage(id: int.parse(state.pathParameters['id']!)), + ), + GoRoute( + path: '/visit/form', + builder: (context, state) => VisitFormPage(id: queryId(state)), + ), + GoRoute( + path: '/visit/execute/:id', + builder: (context, state) => + VisitExecutePage(id: int.parse(state.pathParameters['id']!)), + ), + GoRoute( + path: '/visit/batch', + builder: (context, state) => const VisitBatchPage(), + ), + + // 勘测模块 + GoRoute( + path: '/survey', + builder: (context, state) => const SurveyListPage(), + ), + GoRoute( + path: '/survey/form', + builder: (context, state) => SurveyFormPage( + id: queryId(state), + customerId: int.tryParse(state.uri.queryParameters['customerId'] ?? ''), + ), + ), + + // 项目模块(按后端 project-plans 真实字段重做) + GoRoute( + path: '/project/detail/:id', + builder: (context, state) => + ProjectDetailPage(id: int.parse(state.pathParameters['id']!)), + ), + ], + ); +}); \ No newline at end of file diff --git a/lib/app/tab_index.dart b/lib/app/tab_index.dart new file mode 100644 index 0000000..3ea9466 --- /dev/null +++ b/lib/app/tab_index.dart @@ -0,0 +1,31 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +/// 底部导航的四个 Tab,对应 `components/XBottomNav.vue` 的 4 个入口。 +enum AppTab { workbench, customer, project, mine } + +extension AppTabKey on AppTab { + /// 与 `XBottomNav.items` 中的 key 一致。 + String get key => switch (this) { + AppTab.workbench => 'workbench', + AppTab.customer => 'customer', + AppTab.project => 'project', + AppTab.mine => 'mine', + }; +} + +/// 当前 Tab。对应 uni-app 版 `utils/tabs.ts` 的 `currentTab` ref + `switchTab`。 +class TabIndexController extends Notifier { + @override + AppTab build() => AppTab.workbench; + + void select(AppTab tab) => state = tab; + + /// 按 `XBottomNav` 回传的字符串 key 切换。 + void selectByKey(String key) { + state = AppTab.values.firstWhere((t) => t.key == key, orElse: () => state); + } +} + +final tabIndexProvider = NotifierProvider( + TabIndexController.new, +); \ No newline at end of file diff --git a/lib/app/tabs_page.dart b/lib/app/tabs_page.dart new file mode 100644 index 0000000..fc429ff --- /dev/null +++ b/lib/app/tabs_page.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../core/theme/app_colors.dart'; +import '../features/customer/presentation/customer_tab.dart'; +import '../features/mine/presentation/mine_tab.dart'; +import '../features/project/presentation/project_tab.dart'; +import '../features/workbench/presentation/workbench_tab.dart'; +import '../shared/widgets/x_bottom_nav.dart'; +import 'tab_index.dart'; + +/// 4 个 Tab 的常驻容器,对应 `pages/tabs/index.vue`。 +/// +/// 源项目用 `v-show` 切换,不销毁重建、保留滚动位置与内部状态; +/// 这里用 [IndexedStack] 达到同样效果。 +class TabsPage extends ConsumerWidget { + const TabsPage({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final current = ref.watch(tabIndexProvider); + + return Scaffold( + backgroundColor: AppColors.bgPage, + body: Stack( + children: [ + Positioned.fill( + child: IndexedStack( + index: current.index, + children: const [ + WorkbenchTab(), + CustomerTab(), + ProjectTab(), + MineTab(), + ], + ), + ), + Positioned( + left: 0, + right: 0, + bottom: 0, + child: XBottomNav( + current: current.key, + onChanged: (key) => + ref.read(tabIndexProvider.notifier).selectByKey(key), + ), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/core/app_keys.dart b/lib/core/app_keys.dart new file mode 100644 index 0000000..d53bc27 --- /dev/null +++ b/lib/core/app_keys.dart @@ -0,0 +1,7 @@ +import 'package:flutter/material.dart'; + +/// 全局 Key:供非 Widget 层(拦截器、工具函数)访问 Navigator / ScaffoldMessenger。 +abstract final class AppKeys { + static final rootNavigator = GlobalKey(); + static final scaffoldMessenger = GlobalKey(); +} \ No newline at end of file diff --git a/lib/core/env.dart b/lib/core/env.dart new file mode 100644 index 0000000..88fe981 --- /dev/null +++ b/lib/core/env.dart @@ -0,0 +1,10 @@ +/// 运行期配置。 +/// +/// 与 uni-app 版 `utils/request.ts` 的地址策略一致:App 端直连后端。 +/// 真机联调时用 `--dart-define=API_BASE_URL=http://<局域网IP>:7001/api` 覆盖默认值。 +abstract final class Env { + static const String apiBaseUrl = String.fromEnvironment( + 'API_BASE_URL', + defaultValue: 'http://192.168.3.29:7001/api', + ); +} \ No newline at end of file diff --git a/lib/core/network/api_client.dart b/lib/core/network/api_client.dart new file mode 100644 index 0000000..5d63a71 --- /dev/null +++ b/lib/core/network/api_client.dart @@ -0,0 +1,242 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:dio/dio.dart'; + +import '../env.dart'; +import '../storage/token_storage.dart'; +import 'api_response.dart'; + +/// 图片上传结果,对应 uni-app 版 `api/upload.ts` 的 `UploadResult`。 +class UploadResult { + const UploadResult({ + required this.key, + required this.url, + required this.name, + required this.size, + }); + + /// 对象存储 key,用于持久化到业务表 + final String key; + + /// 预签名访问 URL,用于即时预览 + final String url; + final String name; + final int size; + + factory UploadResult.fromJson(Map json) => UploadResult( + key: json['key'] as String? ?? '', + url: json['url'] as String? ?? '', + name: json['name'] as String? ?? '', + size: (json['size'] as num?)?.toInt() ?? 0, + ); +} + +/// 统一请求封装,等价于 uni-app 版 `utils/request.ts`: +/// - 自动注入 `Authorization: Bearer ` +/// - 解析 `{ code, message, data }`,非 200 也照常返回给调用方判断 +/// - 401 且提示「过期」时刷新 token 并重试一次,其余 401 直接登出 +class ApiClient { + ApiClient({required TokenStorage storage, Dio? dio}) + : _storage = storage, + _dio = + dio ?? + Dio( + BaseOptions( + baseUrl: Env.apiBaseUrl, + connectTimeout: const Duration(seconds: 15), + receiveTimeout: const Duration(seconds: 30), + sendTimeout: const Duration(seconds: 30), + // 自行判断业务 code,不因 HTTP 状态码抛异常 + validateStatus: (_) => true, + ), + ); + + final TokenStorage _storage; + final Dio _dio; + + final _unauthorizedController = StreamController.broadcast(); + + /// 会话失效事件:刷新失败或非过期类 401 时触发,由会话层订阅后跳转登录页。 + Stream get onUnauthorized => _unauthorizedController.stream; + + Dio get raw => _dio; + + // ---- 对外请求方法 ---- + + Future> get( + String url, { + Map? query, + T Function(dynamic data)? parse, + bool needAuth = true, + }) => _send( + 'GET', + url, + query: _compact(query), + parse: parse, + needAuth: needAuth, + ); + + Future> post( + String url, { + Object? body, + T Function(dynamic data)? parse, + bool needAuth = true, + }) => _send('POST', url, body: body, parse: parse, needAuth: needAuth); + + Future> put( + String url, { + Object? body, + T Function(dynamic data)? parse, + bool needAuth = true, + }) => _send('PUT', url, body: body, parse: parse, needAuth: needAuth); + + Future> delete( + String url, { + T Function(dynamic data)? parse, + bool needAuth = true, + }) => _send('DELETE', url, parse: parse, needAuth: needAuth); + + /// 上传现场照片到对象存储(multipart/form-data,字段名 `file`)。 + /// 严格依赖对象存储:失败直接抛异常,由调用方阻断保存并提示用户。 + Future uploadImage(String filePath) async { + try { + final form = FormData.fromMap({ + 'file': await MultipartFile.fromFile(filePath), + }); + final res = await _dio.post( + '/upload/image', + data: form, + options: Options(headers: _authHeader()), + ); + final json = _asMap(res.data); + final code = (json['code'] as num?)?.toInt(); + final data = json['data']; + if (code == 200 && data is Map) { + return UploadResult.fromJson(data.cast()); + } + throw ApiException( + (json['message'] as String?) ?? '图片上传失败', + code: code, + ); + } on ApiException { + rethrow; + } catch (_) { + throw const ApiException('图片上传失败:网络异常'); + } + } + + void dispose() => _unauthorizedController.close(); + + // ---- 内部实现 ---- + + Future> _send( + String method, + String url, { + Map? query, + Object? body, + T Function(dynamic data)? parse, + required bool needAuth, + bool allowRetry = true, + }) async { + late Response res; + try { + res = await _dio.request( + url, + data: body, + queryParameters: query, + options: Options( + method: method, + headers: needAuth ? _authHeader() : null, + ), + ); + } on DioException catch (e) { + throw ApiException(e.message ?? '网络请求失败'); + } + + final json = _asMap(res.data); + final response = ApiResponse.fromJson(json, parse); + + if (response.code == 401) { + final expired = response.message.contains('过期'); + if (expired && allowRetry) { + final refreshed = await _refreshToken(); + if (refreshed) { + return _send( + method, + url, + query: query, + body: body, + parse: parse, + needAuth: needAuth, + allowRetry: false, + ); + } + } + _unauthorizedController.add(null); + throw const ApiException('登录已失效,请重新登录', code: 401); + } + + return response; + } + + Map _authHeader() { + final token = _storage.accessToken; + return token.isEmpty ? const {} : {'Authorization': 'Bearer $token'}; + } + + Future? _refreshing; + + /// 刷新 accessToken;并发调用共用同一个请求,避免刷新风暴。 + Future _refreshToken() { + return _refreshing ??= _doRefresh().whenComplete(() => _refreshing = null); + } + + Future _doRefresh() async { + final refreshToken = _storage.refreshToken; + if (refreshToken.isEmpty) return false; + try { + final res = await _dio.post( + '/auth/refresh', + data: {'refreshToken': refreshToken}, + ); + final json = _asMap(res.data); + final data = json['data']; + if ((json['code'] as num?)?.toInt() == 200 && data is Map) { + final token = data['accessToken'] as String?; + if (token != null && token.isNotEmpty) { + await _storage.setAccessToken(token); + return true; + } + } + } catch (_) { + // 刷新失败按会话失效处理 + } + return false; + } + + static Map _asMap(dynamic data) { + if (data is Map) return data.cast(); + if (data is String && data.isNotEmpty) { + try { + final decoded = jsonDecode(data); + if (decoded is Map) return decoded.cast(); + } catch (_) {} + } + return const {'code': -1, 'message': '响应解析失败'}; + } + + /// 去掉 null / 空串查询条件。 + /// uni-app 会把 undefined 序列化成空串(如 `status=`),后端对空串查询条件会 500, + /// 因此这里同样只在有值时才拼接参数。 + static Map? _compact(Map? src) { + if (src == null || src.isEmpty) return null; + final out = {}; + src.forEach((k, v) { + if (v == null) return; + if (v is String && v.isEmpty) return; + out[k] = v; + }); + return out.isEmpty ? null : out; + } +} \ No newline at end of file diff --git a/lib/core/network/api_response.dart b/lib/core/network/api_response.dart new file mode 100644 index 0000000..a770b54 --- /dev/null +++ b/lib/core/network/api_response.dart @@ -0,0 +1,33 @@ +/// 后端统一响应体:`{ code, message, data }`。 +class ApiResponse { + const ApiResponse({required this.code, required this.message, this.data}); + + final int code; + final String message; + final T? data; + + bool get isOk => code == 200; + + factory ApiResponse.fromJson( + Map json, + T Function(dynamic data)? parse, + ) { + final raw = json['data']; + return ApiResponse( + code: (json['code'] as num?)?.toInt() ?? -1, + message: (json['message'] as String?) ?? '', + data: (raw == null || parse == null) ? null : parse(raw), + ); + } +} + +/// 网络/协议层异常。调用方捕获后用 `message` 提示用户。 +class ApiException implements Exception { + const ApiException(this.message, {this.code}); + + final String message; + final int? code; + + @override + String toString() => message; +} \ No newline at end of file diff --git a/lib/core/providers.dart b/lib/core/providers.dart new file mode 100644 index 0000000..3c06152 --- /dev/null +++ b/lib/core/providers.dart @@ -0,0 +1,15 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'network/api_client.dart'; +import 'storage/token_storage.dart'; + +/// 在 `main()` 中读取 SharedPreferences 后通过 override 注入。 +final tokenStorageProvider = Provider( + (ref) => throw UnimplementedError('tokenStorageProvider 必须在 ProviderScope 中 override'), +); + +final apiClientProvider = Provider((ref) { + final client = ApiClient(storage: ref.watch(tokenStorageProvider)); + ref.onDispose(client.dispose); + return client; +}); \ No newline at end of file diff --git a/lib/core/storage/token_storage.dart b/lib/core/storage/token_storage.dart new file mode 100644 index 0000000..1630b97 --- /dev/null +++ b/lib/core/storage/token_storage.dart @@ -0,0 +1,49 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +/// 本地持久化。键名与 uni-app 版 `uni.getStorageSync` 使用的键完全一致, +/// 便于两端在真机上迁移/对拍时理解同一份数据。 +class TokenStorage { + TokenStorage(this._prefs); + + final SharedPreferences _prefs; + + static const _kAccessToken = 'accessToken'; + static const _kRefreshToken = 'refreshToken'; + static const _kUserInfo = 'userInfo'; + + static Future open() async => + TokenStorage(await SharedPreferences.getInstance()); + + String get accessToken => _prefs.getString(_kAccessToken) ?? ''; + + String get refreshToken => _prefs.getString(_kRefreshToken) ?? ''; + + Map? get userInfo { + final raw = _prefs.getString(_kUserInfo); + if (raw == null || raw.isEmpty) return null; + try { + return jsonDecode(raw) as Map; + } catch (_) { + return null; + } + } + + Future setAccessToken(String token) => + _prefs.setString(_kAccessToken, token); + + Future setRefreshToken(String token) => + _prefs.setString(_kRefreshToken, token); + + Future setUserInfo(Map info) => + _prefs.setString(_kUserInfo, jsonEncode(info)); + + Future clearSession() async { + await _prefs.remove(_kAccessToken); + await _prefs.remove(_kRefreshToken); + await _prefs.remove(_kUserInfo); + } + + bool get hasSession => accessToken.isNotEmpty; +} \ No newline at end of file diff --git a/lib/core/theme/app_colors.dart b/lib/core/theme/app_colors.dart new file mode 100644 index 0000000..f4663da --- /dev/null +++ b/lib/core/theme/app_colors.dart @@ -0,0 +1,103 @@ +import 'package:flutter/material.dart'; + +/// 设计令牌 - 色彩。 +/// 逐项对应 uni-app 版 `src/styles/variables.scss` 中的 `:root` CSS 变量。 +abstract final class AppColors { + // Primary + static const primary = Color(0xFF0054CD); + static const primaryContainer = Color(0xFF136BFB); + static const onPrimary = Color(0xFFFFFFFF); + static const primaryFixed = Color(0xFFDAE2FF); + static const primaryFixedDim = Color(0xFFB2C5FF); + static const onPrimaryFixed = Color(0xFF001847); + static const onPrimaryFixedVariant = Color(0xFF0040A1); + + // Secondary + static const secondary = Color(0xFF712AE2); + static const secondaryContainer = Color(0xFF8A4CFC); + static const onSecondary = Color(0xFFFFFFFF); + static const secondaryFixed = Color(0xFFEADDFF); + static const secondaryFixedDim = Color(0xFFD2BBFF); + static const onSecondaryFixed = Color(0xFF25005A); + static const onSecondaryFixedVariant = Color(0xFF5A00C6); + + // Tertiary + static const tertiary = Color(0xFF00685F); + static const tertiaryContainer = Color(0xFF008378); + static const onTertiary = Color(0xFFFFFFFF); + static const tertiaryFixed = Color(0xFF89F5E7); + static const tertiaryFixedDim = Color(0xFF6BD8CB); + static const onTertiaryFixed = Color(0xFF00201D); + static const onTertiaryFixedVariant = Color(0xFF005049); + + // Error + static const error = Color(0xFFBA1A1A); + static const errorContainer = Color(0xFFFFDAD6); + static const onError = Color(0xFFFFFFFF); + static const onErrorContainer = Color(0xFF93000A); + + // Surface + static const surface = Color(0xFFFFFFFF); + static const surfaceBright = Color(0xFFF8F9FF); + static const surfaceDim = Color(0xFFCCDBF1); + static const surfaceContainer = Color(0xFFE5EFFF); + static const surfaceContainerLowest = Color(0xFFFFFFFF); + static const surfaceContainerLow = Color(0xFFEEF4FF); + static const surfaceContainerHigh = Color(0xFFDBE9FF); + static const surfaceContainerHighest = Color(0xFFD5E4FA); + static const surfaceVariant = Color(0xFFD5E4FA); + + // Background + static const bgPage = Color(0xFFEEF3F8); + static const background = Color(0xFFF8F9FF); + + // Text + static const onSurface = Color(0xFF0D1C2C); + static const onSurfaceVariant = Color(0xFF424655); + static const textMuted = Color(0xFF5B6B7E); + static const textPlaceholder = Color(0xFF9AA3B2); + + // Outline + static const outline = Color(0xFF727787); + static const outlineVariant = Color(0xFFC2C6D8); + static const borderRule = Color(0xFFDBE4EE); + + // Status + static const statusWarn = Color(0xFFE0852B); + static const statusError = Color(0xFFDC2626); + + // Inverse + static const inverseSurface = Color(0xFF233142); + static const inverseOnSurface = Color(0xFFE9F1FF); + static const inversePrimary = Color(0xFFB2C5FF); + + // Accent + static const accentSubtle = Color(0x141D6FFF); + + // 登录页品牌图标渐变 + static const brandGradientStart = Color(0xFF1D6FFF); + static const brandGradientEnd = Color(0xFF2563EB); +} + +/// chip 语义样式:背景色 + 前景色,对应全局样式 `.chip-*` 系列。 +enum ChipTone { primary, secondary, tertiary, warn, error, muted } + +extension ChipToneStyle on ChipTone { + Color get foreground => switch (this) { + ChipTone.primary => AppColors.primary, + ChipTone.secondary => AppColors.secondary, + ChipTone.tertiary => AppColors.tertiary, + ChipTone.warn => AppColors.statusWarn, + ChipTone.error => AppColors.statusError, + ChipTone.muted => AppColors.onSurfaceVariant, + }; + + Color get background => switch (this) { + ChipTone.primary => AppColors.accentSubtle, + ChipTone.secondary => const Color(0x14712AE2), + ChipTone.tertiary => const Color(0x1400685F), + ChipTone.warn => const Color(0x14E0852B), + ChipTone.error => const Color(0x14DC2626), + ChipTone.muted => AppColors.surfaceVariant, + }; +} \ No newline at end of file diff --git a/lib/core/theme/app_dimens.dart b/lib/core/theme/app_dimens.dart new file mode 100644 index 0000000..b2b1512 --- /dev/null +++ b/lib/core/theme/app_dimens.dart @@ -0,0 +1,32 @@ +import 'package:flutter/painting.dart'; + +/// 设计令牌 - 间距与圆角。对应 `variables.scss` 的 `--spacing-*` / `--radius-*`。 +abstract final class AppSpacing { + static const double base = 4; + static const double xs = 8; + static const double sm = 12; + static const double md = 16; + static const double lg = 24; + static const double xl = 40; + static const double gutter = 16; +} + +abstract final class AppRadius { + static const double sm = 4; + static const double regular = 8; + static const double lg = 12; + static const double xl = 24; + static const double full = 9999; +} + +abstract final class AppShadows { + /// 全局 `.card` 阴影:0 4px 14px rgba(0,0,0,0.07) + static const card = [ + BoxShadow(color: Color(0x12000000), blurRadius: 14, offset: Offset(0, 4)), + ]; + + /// 底部导航条:0 8px 24px rgba(0,0,0,0.10) + static const bottomNav = [ + BoxShadow(color: Color(0x1A000000), blurRadius: 24, offset: Offset(0, 8)), + ]; +} \ No newline at end of file diff --git a/lib/core/theme/app_theme.dart b/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..280f9df --- /dev/null +++ b/lib/core/theme/app_theme.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'app_colors.dart'; + +abstract final class AppTheme { + /// 全平台统一使用 iOS 风格「新页面从右侧滑入」转场,与 uni-app 版 + /// pages.json 中 `animationType: slide-in-right` 的表现对齐。 + static const _transitions = PageTransitionsTheme( + builders: { + TargetPlatform.android: CupertinoPageTransitionsBuilder(), + TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.macOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.windows: CupertinoPageTransitionsBuilder(), + TargetPlatform.linux: CupertinoPageTransitionsBuilder(), + TargetPlatform.fuchsia: CupertinoPageTransitionsBuilder(), + }, + ); + + static ThemeData build() { + final base = ThemeData.light(useMaterial3: true); + + return base.copyWith( + scaffoldBackgroundColor: AppColors.bgPage, + pageTransitionsTheme: _transitions, + colorScheme: base.colorScheme.copyWith( + primary: AppColors.primary, + onPrimary: AppColors.onPrimary, + secondary: AppColors.secondary, + onSecondary: AppColors.onSecondary, + tertiary: AppColors.tertiary, + onTertiary: AppColors.onTertiary, + error: AppColors.error, + onError: AppColors.onError, + surface: AppColors.surface, + onSurface: AppColors.onSurface, + outline: AppColors.outline, + outlineVariant: AppColors.outlineVariant, + ), + textTheme: base.textTheme.apply( + bodyColor: AppColors.onSurface, + displayColor: AppColors.onSurface, + ), + dividerTheme: const DividerThemeData( + color: AppColors.borderRule, + thickness: 1, + space: 1, + ), + appBarTheme: const AppBarTheme( + backgroundColor: AppColors.surface, + foregroundColor: AppColors.onSurface, + elevation: 0, + scrolledUnderElevation: 0, + centerTitle: true, + systemOverlayStyle: SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: Brightness.dark, + statusBarBrightness: Brightness.light, + ), + titleTextStyle: TextStyle( + fontSize: 20, + height: 26 / 20, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + splashFactory: InkSparkle.splashFactory, + tooltipTheme: const TooltipThemeData(waitDuration: Duration(milliseconds: 400)), + ); + } +} \ No newline at end of file diff --git a/lib/core/theme/app_typography.dart b/lib/core/theme/app_typography.dart new file mode 100644 index 0000000..af3d786 --- /dev/null +++ b/lib/core/theme/app_typography.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; + +import 'app_colors.dart'; + +/// 设计令牌 - 字号 / 行高 / 字重。 +/// 逐项对应 uni-app 版 `src/styles/variables.scss` 中的 `$font-*` 变量, +/// 行高统一换算成 Flutter 的 `height`(行高 ÷ 字号)。 +abstract final class AppTypography { + static const _sansFallback = [ + 'PingFang SC', + 'Microsoft YaHei', + 'Noto Sans CJK SC', + ]; + + static const _monoFallback = [ + 'JetBrains Mono', + 'SF Mono', + 'Menlo', + 'Consolas', + ]; + + /// 12 / 14 / w700 + static const captionSm = TextStyle( + fontSize: 12, + height: 14 / 12, + fontWeight: FontWeight.w700, + fontFamilyFallback: _sansFallback, + ); + + /// 17 / 24 / w700 + static const titleSm = TextStyle( + fontSize: 17, + height: 24 / 17, + fontWeight: FontWeight.w700, + fontFamilyFallback: _sansFallback, + ); + + /// 15 / 24 / w400 + static const bodyMd = TextStyle( + fontSize: 15, + height: 24 / 15, + fontWeight: FontWeight.w400, + fontFamilyFallback: _sansFallback, + ); + + /// 13 / 16 / w700 + static const labelBold = TextStyle( + fontSize: 13, + height: 16 / 13, + fontWeight: FontWeight.w700, + fontFamilyFallback: _sansFallback, + ); + + /// 12 / 16 / w500,等宽数字场景(编号、金额、时间) + static const dataMono = TextStyle( + fontSize: 12, + height: 16 / 12, + fontWeight: FontWeight.w500, + fontFamilyFallback: _monoFallback, + ); + + /// 23 / 28 / w700 + static const headlineMd = TextStyle( + fontSize: 23, + height: 28 / 23, + fontWeight: FontWeight.w700, + fontFamilyFallback: _sansFallback, + ); + + /// 20 / 26 / w700 + static const headlineMdMobile = TextStyle( + fontSize: 20, + height: 26 / 20, + fontWeight: FontWeight.w700, + fontFamilyFallback: _sansFallback, + ); + + /// 32 / 40 / w700 + static const displayLg = TextStyle( + fontSize: 32, + height: 40 / 32, + fontWeight: FontWeight.w700, + fontFamilyFallback: _sansFallback, + ); +} + +/// 全局默认文字样式,对应 App.vue 里 `page` 上的字体设置。 +TextStyle get appDefaultTextStyle => const TextStyle( + fontSize: 15, + height: 1.6, + color: AppColors.onSurface, + fontFamilyFallback: AppTypography._sansFallback, +); \ No newline at end of file diff --git a/lib/core/utils/format_util.dart b/lib/core/utils/format_util.dart new file mode 100644 index 0000000..d223e6a --- /dev/null +++ b/lib/core/utils/format_util.dart @@ -0,0 +1,46 @@ +/// 日期格式化工具,对应 uni-app 版 `utils/format.ts`(拜访模块多页面复用)。 +String _pad(int n) => n.toString().padLeft(2, '0'); + +/// 统一转 DateTime:兼容 `YYYY-MM-DD`、ISO 字符串与时间戳。 +DateTime? parseDate(Object? v) { + if (v == null) return null; + if (v is DateTime) return v; + if (v is num) return DateTime.fromMillisecondsSinceEpoch(v.toInt()); + final s = v.toString(); + if (s.isEmpty) return null; + return DateTime.tryParse(s) ?? DateTime.tryParse(s.replaceAll('-', '/')); +} + +/// `YYYY-MM-DD` +String formatDate(Object? v) { + final d = parseDate(v); + if (d == null) return '-'; + return '${d.year}-${_pad(d.month)}-${_pad(d.day)}'; +} + +/// `YYYY-MM-DD HH:mm` +String formatDateTime(Object? v) { + final d = parseDate(v); + if (d == null) return '-'; + return '${formatDate(d)} ${_pad(d.hour)}:${_pad(d.minute)}'; +} + +/// 相对日期标签:今日 / 明日 / 昨日 / `YYYY-MM-DD` +String formatDateLabel(Object? v) { + final d = parseDate(v); + if (d == null) return '-'; + final now = DateTime.now(); + final a = DateTime(d.year, d.month, d.day); + final b = DateTime(now.year, now.month, now.day); + final diff = a.difference(b).inDays; + if (diff == 0) return '今日'; + if (diff == 1) return '明日'; + if (diff == -1) return '昨日'; + return formatDate(d); +} + +/// 今天的 `YYYY-MM-DD` +String todayStr() => formatDate(DateTime.now()); + +/// 当前时刻的 `YYYY-MM-DD HH:mm` +String nowDateTimeStr() => formatDateTime(DateTime.now()); \ No newline at end of file diff --git a/lib/core/utils/id_util.dart b/lib/core/utils/id_util.dart new file mode 100644 index 0000000..a93260e --- /dev/null +++ b/lib/core/utils/id_util.dart @@ -0,0 +1,17 @@ +/// 后端主键为 BIGINT,经 JSON 序列化后是字符串(如 `"1"`)。 +/// 统一归一化为 int,避免与表单/路由里的 int 型 id 做比较时失效。 +/// 对应 uni-app 版 `utils/request.ts` 的 `toNumId`。 +Object? toNumId(Object? v) { + if (v == null || v == '') return v; + if (v is int) return v; + if (v is num) return v.toInt(); + final n = int.tryParse(v.toString()); + return n ?? v; +} + +int? toIntOrNull(Object? v) { + final n = toNumId(v); + return n is int ? n : null; +} + +int toIntOr(Object? v, int fallback) => toIntOrNull(v) ?? fallback; \ No newline at end of file diff --git a/lib/features/auth/application/session_controller.dart b/lib/features/auth/application/session_controller.dart new file mode 100644 index 0000000..1010e89 --- /dev/null +++ b/lib/features/auth/application/session_controller.dart @@ -0,0 +1,95 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/providers.dart'; +import '../../../core/storage/token_storage.dart'; +import '../data/auth_api.dart'; +import '../data/auth_models.dart'; + +final authApiProvider = Provider( + (ref) => AuthApi(ref.watch(apiClientProvider)), +); + +class SessionState { + const SessionState({this.user, required this.isLoggedIn}); + + final UserInfo? user; + final bool isLoggedIn; + + SessionState copyWith({UserInfo? user, bool? isLoggedIn, bool clearUser = false}) => + SessionState( + user: clearUser ? null : (user ?? this.user), + isLoggedIn: isLoggedIn ?? this.isLoggedIn, + ); +} + +/// 登录态,对应 uni-app 版 `store/user.ts`。 +class SessionController extends Notifier { + TokenStorage get _storage => ref.read(tokenStorageProvider); + + @override + SessionState build() { + // 拦截器判定会话失效(刷新失败或非过期类 401)时,清空本地会话并回到登录页。 + final sub = ref + .watch(apiClientProvider) + .onUnauthorized + .listen((_) => clearLocal()); + ref.onDispose(sub.cancel); + + final cached = _storage.userInfo; + return SessionState( + user: cached == null ? null : UserInfo.fromJson(cached), + isLoggedIn: _storage.hasSession, + ); + } + + Future login({ + required String username, + required String password, + }) async { + final res = await ref + .read(authApiProvider) + .login(username: username, password: password); + if (!res.isOk || res.data == null) return false; + + final data = res.data!; + await _storage.setAccessToken(data.accessToken); + if (data.refreshToken.isNotEmpty) { + await _storage.setRefreshToken(data.refreshToken); + } + final user = UserInfo( + id: data.userInfo.id, + username: data.userInfo.username, + realName: data.userInfo.realName, + roles: data.roles, + ); + await _storage.setUserInfo(user.toJson()); + state = SessionState(user: user, isLoggedIn: true); + return true; + } + + Future fetchUserInfo() async { + try { + final res = await ref.read(authApiProvider).currentUser(); + if (res.isOk && res.data != null) { + await _storage.setUserInfo(res.data!.toJson()); + state = SessionState(user: res.data, isLoggedIn: true); + return true; + } + } catch (_) { + // 拉取失败保持原状态 + } + return false; + } + + Future logout() async { + await _storage.clearSession(); + state = const SessionState(isLoggedIn: false, user: null); + } + + /// 清空本地会话但不触发网络请求(被拦截器判定会话失效时调用)。 + Future clearLocal() => logout(); +} + +final sessionProvider = NotifierProvider( + SessionController.new, +); \ No newline at end of file diff --git a/lib/features/auth/data/auth_api.dart b/lib/features/auth/data/auth_api.dart new file mode 100644 index 0000000..b5a7573 --- /dev/null +++ b/lib/features/auth/data/auth_api.dart @@ -0,0 +1,27 @@ +import '../../../core/network/api_client.dart'; +import '../../../core/network/api_response.dart'; +import 'auth_models.dart'; + +/// 认证相关接口,对应 uni-app 版 `api/auth.ts`。 +class AuthApi { + AuthApi(this._client); + + final ApiClient _client; + + Future> login({ + required String username, + required String password, + }) => _client.post( + '/auth/login', + body: {'username': username, 'password': password}, + parse: (d) => LoginResult.fromJson((d as Map).cast()), + needAuth: false, + ); + + Future> currentUser() => _client.get( + '/auth/currentUser', + parse: (d) => UserInfo.fromJson((d as Map).cast()), + ); + + Future> logout() => _client.post('/auth/logout'); +} \ No newline at end of file diff --git a/lib/features/auth/data/auth_models.dart b/lib/features/auth/data/auth_models.dart new file mode 100644 index 0000000..af083fe --- /dev/null +++ b/lib/features/auth/data/auth_models.dart @@ -0,0 +1,80 @@ +import '../../../core/utils/id_util.dart'; + +/// 登录态用户信息,对应 `types/auth.ts` 的 `UserInfo`。 +class UserInfo { + const UserInfo({ + required this.id, + required this.username, + required this.realName, + required this.roles, + }); + + final int id; + final String username; + final String realName; + final List roles; + + String get displayName => realName.isNotEmpty ? realName : username; + + /// 头像占位文字:取显示名首个字符(按 Unicode 码点截取,兼容中文)。 + String get avatarText { + if (displayName.isEmpty) return '?'; + return String.fromCharCode(displayName.runes.first); + } + + bool get isAdmin => roles.contains('ADMIN'); + + factory UserInfo.fromJson(Map json) => UserInfo( + id: toIntOr(json['id'], 0), + username: json['username'] as String? ?? '', + realName: json['realName'] as String? ?? '', + roles: (json['roles'] as List?)?.map((e) => e.toString()).toList() ?? const [], + ); + + Map toJson() => { + 'id': id, + 'username': username, + 'realName': realName, + 'roles': roles, + }; +} + +/// 登录接口返回体,对应 `types/auth.ts` 的 `LoginResponse`。 +class LoginResult { + const LoginResult({ + required this.accessToken, + required this.refreshToken, + required this.userInfo, + required this.roles, + }); + + final String accessToken; + final String refreshToken; + final UserInfo userInfo; + final List roles; + + factory LoginResult.fromJson(Map json) => LoginResult( + accessToken: json['accessToken'] as String? ?? '', + refreshToken: json['refreshToken'] as String? ?? '', + userInfo: UserInfo.fromJson( + (json['userInfo'] as Map?)?.cast() ?? const {}, + ), + roles: (json['roles'] as List?)?.map((e) => e.toString()).toList() ?? const [], + ); +} + +/// 后端角色编码 → 中文名称映射。 +const roleLabelMap = { + 'ADMIN': '运营管理员', + 'SALESMAN': '业务员', + 'WORKER': '共享电工', + 'CUSTOMER': '客户', +}; + +/// 将角色编码数组映射为可读文本(多个角色以 / 分隔)。 +String roleLabel(List? roles) { + if (roles != null && roles.isNotEmpty) { + return roles.map((r) => roleLabelMap[r] ?? r).join(' / '); + } + return '运营管理员'; +} \ No newline at end of file diff --git a/lib/features/auth/presentation/login_page.dart b/lib/features/auth/presentation/login_page.dart new file mode 100644 index 0000000..3351a12 --- /dev/null +++ b/lib/features/auth/presentation/login_page.dart @@ -0,0 +1,279 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../application/session_controller.dart'; + +/// 登录页,对应 `pages/login/index.vue`。 +class LoginPage extends ConsumerStatefulWidget { + const LoginPage({super.key}); + + @override + ConsumerState createState() => _LoginPageState(); +} + +class _LoginPageState extends ConsumerState { + final _username = TextEditingController(); + final _password = TextEditingController(); + + bool _loading = false; + String _errorMsg = ''; + + @override + void dispose() { + _username.dispose(); + _password.dispose(); + super.dispose(); + } + + Future _handleLogin() async { + final username = _username.text.trim(); + final password = _password.text; + + if (username.isEmpty || password.isEmpty) { + setState(() => _errorMsg = '请输入账号和密码'); + return; + } + + setState(() { + _loading = true; + _errorMsg = ''; + }); + + try { + final ok = await ref + .read(sessionProvider.notifier) + .login(username: username, password: password); + if (!mounted) return; + if (ok) { + context.go('/tabs'); + } else { + setState(() => _errorMsg = '登录失败,请检查账号密码'); + } + } catch (e) { + if (!mounted) return; + setState(() => _errorMsg = e.toString()); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.bgPage, + body: Stack( + children: [ + // 源页面右上/左下的两处柔光渐变 + const Positioned( + right: -80, + top: -80, + child: _SoftBlob(color: Color(0x0F0054CD), size: 280), + ), + const Positioned( + left: -80, + bottom: -80, + child: _SoftBlob(color: Color(0x0D712AE2), size: 280), + ), + LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 40), + child: ConstrainedBox( + constraints: BoxConstraints( + minHeight: (constraints.maxHeight - 80).clamp(0, double.infinity), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _buildBrand(), + const SizedBox(height: 40), + _buildForm(), + const SizedBox(height: 40), + Text( + '© 鑫潼智电 · 运营管理', + style: const TextStyle( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + ], + ), + ), + ), + ), + ], + ), + ); + } + + Widget _buildBrand() { + return Column( + children: [ + Container( + width: 64, + height: 64, + decoration: BoxDecoration( + gradient: const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [AppColors.brandGradientStart, AppColors.brandGradientEnd], + ), + borderRadius: BorderRadius.circular(20), + boxShadow: const [ + BoxShadow( + color: Color(0x401D6FFF), + blurRadius: 20, + offset: Offset(0, 8), + ), + ], + ), + alignment: Alignment.center, + child: const XIcon('bolt', size: 34, color: Colors.white), + ), + const SizedBox(height: 16), + Text( + '鑫潼智电', + style: AppTypography.headlineMd.copyWith( + fontSize: 26, + letterSpacing: 2, + ), + ), + const SizedBox(height: 4), + const Text( + '鑫潼智电运营管理平台', + style: TextStyle(fontSize: 14, color: AppColors.textMuted), + ), + ], + ); + } + + Widget _buildForm() { + return XCard( + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildField( + label: '账号', + icon: 'person', + controller: _username, + hintText: '请输入账号', + obscure: false, + ), + const SizedBox(height: 18), + _buildField( + label: '密码', + icon: 'more', + controller: _password, + hintText: '请输入密码', + obscure: true, + ), + const SizedBox(height: 8), + XPrimaryButton( + label: '登 录', + loading: _loading, + onPressed: _handleLogin, + ), + if (_errorMsg.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 14), + child: Text( + _errorMsg, + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 13, + color: AppColors.statusError, + ), + ), + ), + ], + ), + ); + } + + Widget _buildField({ + required String label, + required String icon, + required TextEditingController controller, + required String hintText, + required bool obscure, + }) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: AppTypography.labelBold.copyWith( + color: AppColors.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + Container( + height: 48, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(AppRadius.lg), + ), + child: Row( + children: [ + XIcon(icon, size: 20, color: AppColors.textMuted), + const SizedBox(width: 10), + Expanded( + child: TextField( + controller: controller, + obscureText: obscure, + style: const TextStyle( + fontSize: 15, + color: AppColors.onSurface, + ), + cursorColor: AppColors.primary, + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + hintText: hintText, + hintStyle: const TextStyle( + fontSize: 15, + color: AppColors.textPlaceholder, + ), + ), + ), + ), + ], + ), + ), + ], + ); + } +} + +/// 登录页背景的柔光圆斑(对应源页面两处 radial-gradient)。 +class _SoftBlob extends StatelessWidget { + const _SoftBlob({required this.color, required this.size}); + + final Color color; + final double size; + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: Container( + width: size, + height: size, + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: RadialGradient( + colors: [color, color.withValues(alpha: 0)], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/customer/data/customer_api.dart b/lib/features/customer/data/customer_api.dart new file mode 100644 index 0000000..98f1457 --- /dev/null +++ b/lib/features/customer/data/customer_api.dart @@ -0,0 +1,77 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/network/api_client.dart'; +import '../../../core/network/api_response.dart'; +import '../../../core/providers.dart'; +import 'customer_models.dart'; + +final customerApiProvider = Provider( + (ref) => CustomerApi(ref.watch(apiClientProvider)), +); + +/// 客户档案接口,对应 uni-app 版 `api/customer.ts`。 +class CustomerApi { + CustomerApi(this._client); + + final ApiClient _client; + + Future> list({ + int page = 1, + int pageSize = 100, + String? keyword, + int? status, + int? salesmanId, + }) => _client.get( + '/customers', + query: { + 'page': page, + 'pageSize': pageSize, + 'keyword': keyword, + 'status': status, + 'salesmanId': salesmanId, + }, + parse: (d) { + final m = (d as Map).cast(); + return CustomerPage( + list: (m['list'] as List? ?? []) + .map((e) => Customer.fromJson((e as Map).cast())) + .toList(), + total: (m['total'] as num?)?.toInt() ?? 0, + page: (m['page'] as num?)?.toInt() ?? 1, + pageSize: (m['pageSize'] as num?)?.toInt() ?? pageSize, + ); + }, + ); + + Future> detail(int id) => _client.get( + '/customers/$id', + parse: (d) => Customer.fromJson((d as Map).cast()), + ); + + Future> create(Map body) => + _client.post( + '/customers', + body: body, + parse: (d) => Customer.fromJson((d as Map).cast()), + ); + + Future> update(int id, Map body) => + _client.put( + '/customers/$id', + body: body, + parse: (d) => Customer.fromJson((d as Map).cast()), + ); + + Future> delete(int id) => _client.delete('/customers/$id'); + + Future> updateStatus(int id, int status) => + _client.put('/customers/$id/status', body: {'status': status}); + + Future>> options() => + _client.get>( + '/customers/options/all', + parse: (d) => (d as List) + .map((e) => CustomerOption.fromJson((e as Map).cast())) + .toList(), + ); +} \ No newline at end of file diff --git a/lib/features/customer/data/customer_models.dart b/lib/features/customer/data/customer_models.dart new file mode 100644 index 0000000..0a411c5 --- /dev/null +++ b/lib/features/customer/data/customer_models.dart @@ -0,0 +1,143 @@ +import 'package:flutter/painting.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/utils/id_util.dart'; + +/// 客户档案,与后端 `/api/customers` 契约对齐(`types/customer.ts`)。 +class Customer { + const Customer({ + required this.id, + required this.customerNo, + required this.customerName, + required this.province, + required this.city, + required this.district, + required this.address, + required this.contactPerson, + required this.contactPhone, + required this.postalCode, + required this.fax, + required this.customerLevel, + required this.status, + this.salesmanId, + this.createdAt, + this.updatedAt, + }); + + final int id; + final String customerNo; + final String customerName; + final String province; + final String city; + final String district; + final String address; + final String contactPerson; + final String contactPhone; + final String postalCode; + final String fax; + final String customerLevel; + final int status; + final int? salesmanId; + final String? createdAt; + final String? updatedAt; + + factory Customer.fromJson(Map json) => Customer( + id: toIntOr(json['id'], 0), + customerNo: json['customerNo'] as String? ?? '', + customerName: json['customerName'] as String? ?? '', + province: json['province'] as String? ?? '', + city: json['city'] as String? ?? '', + district: json['district'] as String? ?? '', + address: json['address'] as String? ?? '', + contactPerson: json['contactPerson'] as String? ?? '', + contactPhone: json['contactPhone'] as String? ?? '', + postalCode: json['postalCode'] as String? ?? '', + fax: json['fax'] as String? ?? '', + customerLevel: json['customerLevel'] as String? ?? '', + status: toIntOr(json['status'], 1), + salesmanId: toIntOrNull(json['salesmanId']), + createdAt: json['created_at'] as String?, + updatedAt: json['updated_at'] as String?, + ); + + Map toJson() => { + 'id': id, + 'customerNo': customerNo, + 'customerName': customerName, + 'province': province, + 'city': city, + 'district': district, + 'address': address, + 'contactPerson': contactPerson, + 'contactPhone': contactPhone, + 'postalCode': postalCode, + 'fax': fax, + 'customerLevel': customerLevel, + 'status': status, + if (salesmanId != null) 'salesmanId': salesmanId, + }; + + /// 列表卡片右侧的「地区」展示:省市拼接,缺失时提示未填写。 + String get locationText { + final text = '$province$city'; + return text.isEmpty ? '未填写地区' : text; + } +} + +/// 客户下拉选项(拜访/客户关系选择用)。 +class CustomerOption { + const CustomerOption({ + required this.id, + required this.customerNo, + required this.customerName, + required this.status, + }); + + final int id; + final String customerNo; + final String customerName; + final int status; + + factory CustomerOption.fromJson(Map json) => CustomerOption( + id: toIntOr(json['id'], 0), + customerNo: json['customerNo'] as String? ?? '', + customerName: json['customerName'] as String? ?? '', + status: toIntOr(json['status'], 1), + ); +} + +class CustomerPage { + const CustomerPage({ + required this.list, + required this.total, + required this.page, + required this.pageSize, + }); + + final List list; + final int total; + final int page; + final int pageSize; +} + +/// 客户状态:1 意向 2 签约 3 运维中 4 终止 +const customerStatusMap = { + 1: (text: '意向', tone: ChipTone.warn), + 2: (text: '签约', tone: ChipTone.primary), + 3: (text: '运维中', tone: ChipTone.tertiary), + 4: (text: '终止', tone: ChipTone.error), +}; + +String customerStatusText(int status) => customerStatusMap[status]?.text ?? '未知'; + +ChipTone customerStatusTone(int status) => + customerStatusMap[status]?.tone ?? ChipTone.muted; + +/// 列表卡片左侧色条颜色。 +Color customerStatusBarColor(int status) => switch (status) { + 1 => AppColors.statusWarn, + 2 => AppColors.primary, + 3 => AppColors.tertiaryContainer, + 4 => AppColors.statusError, + _ => AppColors.borderRule, +}; \ No newline at end of file diff --git a/lib/features/customer/data/user_api.dart b/lib/features/customer/data/user_api.dart new file mode 100644 index 0000000..591c1df --- /dev/null +++ b/lib/features/customer/data/user_api.dart @@ -0,0 +1,99 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/network/api_client.dart'; +import '../../../core/network/api_response.dart'; +import '../../../core/providers.dart'; +import '../../../core/utils/id_util.dart'; + +final userApiProvider = Provider( + (ref) => UserApi(ref.watch(apiClientProvider)), +); + +class SysRole { + const SysRole({required this.id, required this.roleCode, required this.roleName}); + + final int id; + final String roleCode; + final String roleName; + + factory SysRole.fromJson(Map json) => SysRole( + id: toIntOr(json['id'], 0), + roleCode: json['roleCode'] as String? ?? '', + roleName: json['roleName'] as String? ?? '', + ); +} + +class SysUser { + const SysUser({ + required this.id, + required this.username, + required this.realName, + this.phone, + this.email, + this.status, + }); + + final int id; + final String username; + final String realName; + final String? phone; + final String? email; + final int? status; + + /// 下拉项展示文本:姓名 · 手机号 + String get optionLabel { + final name = realName.isNotEmpty ? realName : username; + return phone == null || phone!.isEmpty ? name : '$name · $phone'; + } + + factory SysUser.fromJson(Map json) => SysUser( + id: toIntOr(json['id'], 0), + username: json['username'] as String? ?? '', + realName: json['realName'] as String? ?? '', + phone: json['phone'] as String?, + email: json['email'] as String?, + status: toIntOrNull(json['status']), + ); +} + +/// 用户/角色接口,对应 uni-app 版 `api/user.ts`。 +class UserApi { + UserApi(this._client); + + final ApiClient _client; + + Future>> roles() => _client.get>( + '/users/roles', + parse: (d) => (d as List) + .map((e) => SysRole.fromJson((e as Map).cast())) + .toList(), + ); + + Future>> list({ + int page = 1, + int pageSize = 100, + int? status, + int? roleId, + }) => _client.get>( + '/users', + query: {'page': page, 'pageSize': pageSize, 'status': status, 'roleId': roleId}, + parse: (d) { + final m = (d as Map).cast(); + return (m['list'] as List? ?? []) + .map((e) => SysUser.fromJson((e as Map).cast())) + .toList(); + }, + ); + + /// 业务员下拉选项:先按 roleCode 解析 SALESMAN 角色 id,再取其启用状态的用户。 + Future> salesmanOptions() async { + final roleRes = await roles(); + final salesmanRole = (roleRes.data ?? []) + .where((r) => r.roleCode == 'SALESMAN') + .firstOrNull; + if (salesmanRole == null) return const []; + + final userRes = await list(page: 1, pageSize: 100, status: 1, roleId: salesmanRole.id); + return userRes.data ?? const []; + } +} \ No newline at end of file diff --git a/lib/features/customer/presentation/customer_detail_page.dart b/lib/features/customer/presentation/customer_detail_page.dart new file mode 100644 index 0000000..650643e --- /dev/null +++ b/lib/features/customer/presentation/customer_detail_page.dart @@ -0,0 +1,443 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/format_util.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../visit/data/visit_api.dart'; +import '../../visit/data/visit_models.dart'; +import '../data/customer_api.dart'; +import '../data/customer_models.dart'; + +/// 信息卡里的等宽数值(联系电话 / 传真 / 邮编)。 +/// 源页面 `.info-value.font-data-mono`:字号 15 覆盖全局 12,字重 500、行高 16、等宽字体。 +const _monoFallback = ['JetBrains Mono', 'SF Mono', 'Menlo', 'Consolas']; +const _infoMonoStyle = TextStyle( + fontSize: 15, + height: 16 / 15, + fontWeight: FontWeight.w500, + fontFamilyFallback: _monoFallback, +); + +/// 客户详情页,对应 `pages/customer/detail.vue`。 +class CustomerDetailPage extends ConsumerStatefulWidget { + const CustomerDetailPage({super.key, required this.id}); + + final int id; + + @override + ConsumerState createState() => _CustomerDetailPageState(); +} + +class _CustomerDetailPageState extends ConsumerState { + Customer? _customer; + bool _loading = true; + List _visits = const []; + int _visitTotal = 0; + bool _visitLoading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + await Future.wait([_loadCustomer(), _loadVisits()]); + } + + Future _loadCustomer() async { + setState(() => _loading = true); + try { + final res = await ref.read(customerApiProvider).detail(widget.id); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() => _customer = res.data); + } else { + showAppToast(res.message.isEmpty ? '客户不存在' : res.message); + } + } catch (_) { + if (mounted) showAppToast('加载失败'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + Future _loadVisits() async { + setState(() => _visitLoading = true); + try { + final res = await ref + .read(visitApiProvider) + .list(customerId: widget.id, page: 1, pageSize: 5); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() { + _visits = res.data!.list; + _visitTotal = res.data!.total; + }); + } + } catch (_) { + // 拜访记录加载失败不影响客户详情展示 + } finally { + if (mounted) setState(() => _visitLoading = false); + } + } + + Future _goEdit() async { + await context.push('/customer/edit?id=${widget.id}'); + if (!mounted) return; + _load(); + } + + Future _onDelete() async { + final confirmed = await showAppConfirm( + title: '删除客户', + content: '确定删除该客户吗?此操作不可恢复。', + destructive: true, + ); + if (!confirmed) return; + try { + final res = await ref.read(customerApiProvider).delete(widget.id); + if (res.isOk) { + showAppToast('已删除', success: true); + if (mounted) context.pop(); + } else { + showAppToast(res.message.isEmpty ? '删除失败' : res.message); + } + } catch (_) { + showAppToast('删除失败'); + } + } + + @override + Widget build(BuildContext context) { + return XPageShell( + topBar: XTopBar.nav( + title: '客户详情', + onBack: () => context.pop(), + trailing: GestureDetector( + onTap: _goEdit, + behavior: HitTestBehavior.opaque, + child: const XIcon('edit', size: 20, color: AppColors.primary), + ), + ), + child: _buildBody(), + ); + } + + Widget _buildBody() { + final c = _customer; + if (c == null) { + if (_loading) { + return Center( + child: Text( + '加载中...', + style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted), + ), + ); + } + return const SizedBox.shrink(); + } + + return SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 60), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildHeaderCard(c), + _buildInfoCard(c), + _buildSectionHead(), + if (_visits.isNotEmpty) _buildVisitCard() else _buildEmptyBlock(), + XPrimaryButton( + label: '删除客户', + onPressed: _onDelete, + height: 46, + margin: const EdgeInsets.fromLTRB(16, 28, 16, 0), + background: AppColors.surface, + foreground: AppColors.statusError, + borderColor: AppColors.statusError, + fontSize: 15, + pill: false, + ), + ], + ), + ); + } + + Widget _buildHeaderCard(Customer c) { + return XCard( + padding: const EdgeInsets.all(16), + margin: const EdgeInsets.only(bottom: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 6, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + c.customerName, + style: AppTypography.headlineMdMobile.copyWith( + color: AppColors.onSurface, + ), + ), + XChip( + customerStatusText(c.status), + tone: customerStatusTone(c.status), + ), + if (c.customerLevel.isNotEmpty) + XChip(c.customerLevel, tone: ChipTone.muted), + ], + ), + const SizedBox(height: 10), + Row( + children: [ + Text( + '客户编号', + style: AppTypography.bodyMd.copyWith( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + const SizedBox(width: 8), + Text( + c.customerNo, + style: AppTypography.dataMono.copyWith( + color: AppColors.onSurface, + ), + ), + ], + ), + ], + ), + ); + } + + Widget _buildInfoCard(Customer c) { + final region = [c.province, c.city, c.district] + .where((e) => e.isNotEmpty) + .toList(); + final items = [ + _infoItem('location', '地区', region.isEmpty ? '-' : region.join(' ')), + _infoItem('business', '详细地址', c.address.isEmpty ? '-' : c.address), + _infoItem('person', '联系人', c.contactPerson.isEmpty ? '-' : c.contactPerson), + _infoItem( + 'call', + '联系电话', + c.contactPhone.isEmpty ? '-' : c.contactPhone, + mono: true, + ), + _infoItem('category', '传真', c.fax.isEmpty ? '-' : c.fax, mono: true), + _infoItem('category', '邮编', c.postalCode.isEmpty ? '-' : c.postalCode, mono: true), + _infoItem('clock', '创建时间', formatDateTime(c.createdAt)), + ]; + + return XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Column( + children: [ + for (var i = 0; i < items.length; i++) ...[ + if (i > 0) Container(height: 1, color: AppColors.borderRule), + items[i], + ], + ], + ), + ); + } + + Widget _infoItem(String icon, String label, String value, {bool mono = false}) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 13), + child: Row( + children: [ + XIcon(icon, size: 18, color: AppColors.textMuted), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: AppTypography.bodyMd.copyWith( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + Text( + value, + style: mono + ? _infoMonoStyle.copyWith(color: AppColors.onSurface) + : AppTypography.bodyMd.copyWith( + color: AppColors.onSurface, + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildSectionHead() { + return Padding( + padding: const EdgeInsets.only(top: 22, bottom: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + const XIcon('schedule', size: 17, color: AppColors.primary), + const SizedBox(width: 6), + Text( + '拜访记录', + style: AppTypography.titleSm.copyWith( + fontSize: 16, + color: AppColors.onSurface, + ), + ), + ], + ), + GestureDetector( + onTap: () => context.push('/visit/form?customerId=${widget.id}'), + behavior: HitTestBehavior.opaque, + child: Row( + children: [ + const XIcon('add', size: 15, color: AppColors.primary), + const SizedBox(width: 2), + Text( + '发起拜访', + style: AppTypography.labelBold.copyWith( + color: AppColors.primary, + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildVisitCard() { + final items = []; + for (var i = 0; i < _visits.length; i++) { + if (i > 0) items.add(Container(height: 1, color: AppColors.borderRule)); + items.add(_visitItem(_visits[i])); + } + if (_visitTotal > _visits.length) { + items.add( + Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Text( + '共 $_visitTotal 条拜访,仅显示最近 ${_visits.length} 条', + textAlign: TextAlign.center, + style: AppTypography.bodyMd.copyWith( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + ), + ); + } + + return XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Column(children: items), + ); + } + + Widget _visitItem(VisitInfo v) { + return GestureDetector( + onTap: () => context.push('/visit/detail/${v.id}'), + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.fromLTRB(10, 13, 0, 13), + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned( + left: -10, + top: 1, + bottom: 1, + child: Container( + width: 3, + decoration: BoxDecoration( + color: visitStatusBarColor(v.status), + borderRadius: BorderRadius.circular(2), + ), + ), + ), + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 6, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + (v.subject == null || v.subject!.isEmpty) + ? '客户拜访' + : v.subject!, + style: AppTypography.bodyMd.copyWith( + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + XChip( + visitStatusText(v.status), + tone: visitStatusTone(v.status), + ), + ], + ), + const SizedBox(height: 4), + Text( + '${v.visitNo} · ${formatDate(v.planTime)}', + style: AppTypography.dataMono.copyWith( + color: AppColors.textMuted, + ), + ), + ], + ), + ), + const SizedBox(width: 10), + const XIcon('forward', size: 16, color: AppColors.textPlaceholder), + ], + ), + ], + ), + ), + ); + } + + Widget _buildEmptyBlock() { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20), + alignment: Alignment.center, + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + _visitLoading ? '加载中...' : '暂无拜访记录', + style: AppTypography.bodyMd.copyWith( + fontSize: 13, + color: AppColors.textMuted, + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/customer/presentation/customer_edit_page.dart b/lib/features/customer/presentation/customer_edit_page.dart new file mode 100644 index 0000000..c04503c --- /dev/null +++ b/lib/features/customer/presentation/customer_edit_page.dart @@ -0,0 +1,653 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/network/api_response.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../auth/application/session_controller.dart'; +import '../data/customer_api.dart'; +import '../data/customer_models.dart'; +import '../data/user_api.dart'; + +/// 设施类型下拉项,照抄源页面 `levelOptions`。 +const _levelOptions = ['医院', '学校', '企业', '其他']; + +/// 状态下拉的可选值,照抄源页面 `statusOptions`。 +const _statusValues = [1, 2, 3, 4]; + +/// 省市区三级选择器的内置示例数据(源页面用 uni 的 region picker)。 +const _regionData = >>{ + '北京市': { + '北京市': ['东城区', '西城区', '朝阳区', '海淀区', '丰台区', '石景山区', '通州区'], + }, + '上海市': { + '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '浦东新区', '闵行区'], + }, + '广东省': { + '广州市': ['越秀区', '天河区', '海珠区', '白云区', '番禺区'], + '深圳市': ['福田区', '南山区', '罗湖区', '宝安区', '龙岗区'], + '珠海市': ['香洲区', '金湾区', '斗门区'], + }, + '浙江省': { + '杭州市': ['上城区', '拱墅区', '西湖区', '滨江区', '余杭区'], + '宁波市': ['海曙区', '江北区', '鄞州区', '北仑区'], + '温州市': ['鹿城区', '龙湾区', '瓯海区'], + }, + '江苏省': { + '南京市': ['玄武区', '秦淮区', '鼓楼区', '江宁区'], + '苏州市': ['姑苏区', '吴中区', '相城区', '工业园区'], + '无锡市': ['梁溪区', '滨湖区', '新吴区'], + }, + '四川省': { + '成都市': ['锦江区', '青羊区', '武侯区', '成华区', '高新区'], + '绵阳市': ['涪城区', '游仙区', '安州区'], + }, +}; + +/// 客户编辑页(新增 / 编辑),对应 `pages/customer/edit.vue`。 +class CustomerEditPage extends ConsumerStatefulWidget { + const CustomerEditPage({super.key, this.id}); + + /// 为 null 表示新增。 + final int? id; + + @override + ConsumerState createState() => _CustomerEditPageState(); +} + +class _CustomerEditPageState extends ConsumerState { + final _customerName = TextEditingController(); + final _customerNo = TextEditingController(); + final _address = TextEditingController(); + final _contactPerson = TextEditingController(); + final _contactPhone = TextEditingController(); + final _postalCode = TextEditingController(); + final _fax = TextEditingController(); + + late final bool _isEdit = widget.id != null; + bool _isAdmin = false; + bool _saving = false; + + String _province = ''; + String _city = ''; + String _district = ''; + String _customerLevel = ''; + int _status = 1; + List _salesmen = const []; + int _salesmanIndex = 0; + + List get _salesmanLabels => + ['未指定', ..._salesmen.map((s) => s.optionLabel)]; + + @override + void initState() { + super.initState(); + _isAdmin = ref.read(sessionProvider).user?.isAdmin ?? false; + _load(); + } + + @override + void dispose() { + _customerName.dispose(); + _customerNo.dispose(); + _address.dispose(); + _contactPerson.dispose(); + _contactPhone.dispose(); + _postalCode.dispose(); + _fax.dispose(); + super.dispose(); + } + + Future _load() async { + if (_isAdmin) { + try { + final list = await ref.read(userApiProvider).salesmanOptions(); + if (mounted) setState(() => _salesmen = list); + } catch (_) { + if (mounted) setState(() => _salesmen = const []); + } + } + + final id = widget.id; + if (id == null) return; + try { + final res = await ref.read(customerApiProvider).detail(id); + if (!mounted) return; + final d = res.data; + if (res.isOk && d != null) { + setState(() { + _customerName.text = d.customerName; + _customerNo.text = d.customerNo; + _province = d.province; + _city = d.city; + _district = d.district; + _address.text = d.address; + _contactPerson.text = d.contactPerson; + _contactPhone.text = d.contactPhone; + _postalCode.text = d.postalCode; + _fax.text = d.fax; + _customerLevel = d.customerLevel; + _status = d.status; + final si = _salesmen.indexWhere((s) => s.id == d.salesmanId); + _salesmanIndex = si >= 0 ? si + 1 : 0; + }); + } + } catch (_) { + // 详情加载失败保持空表单 + } + } + + Future _onSave() async { + if (_customerName.text.trim().isEmpty) { + showAppToast('请输入客户名称'); + return; + } + setState(() => _saving = true); + + final payload = { + 'customerName': _customerName.text, + if (_isEdit) 'customerNo': _customerNo.text, + 'province': _province, + 'city': _city, + 'district': _district, + 'address': _address.text, + 'contactPerson': _contactPerson.text, + 'contactPhone': _contactPhone.text, + 'postalCode': _postalCode.text, + 'fax': _fax.text, + 'customerLevel': _customerLevel, + 'status': _status, + }; + // ADMIN 可指定负责业务员;未指定时传 null 以清空。 + if (_isAdmin) { + payload['salesmanId'] = + _salesmanIndex > 0 ? _salesmen[_salesmanIndex - 1].id : null; + } + + try { + final api = ref.read(customerApiProvider); + final ApiResponse res; + if (_isEdit) { + res = await api.update(widget.id!, payload); + } else { + payload.remove('customerNo'); + res = await api.create(payload); + } + if (res.isOk) { + showAppToast('保存成功', success: true); + if (mounted) context.pop(); + } else { + showAppToast(res.message.isEmpty ? '保存失败' : res.message); + } + } catch (_) { + showAppToast('保存失败,请重试'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + String get _regionText => _province.isEmpty + ? '请选择省市区' + : [_province, _city, _district].where((e) => e.isNotEmpty).join(' '); + + Future _pickRegion() async { + final res = await showModalBottomSheet<({String province, String city, String district})>( + context: context, + backgroundColor: Colors.transparent, + builder: (_) => const _RegionPickerSheet(), + ); + if (res == null) return; + setState(() { + _province = res.province; + _city = res.city; + _district = res.district; + }); + } + + Future _pickLevel() async { + final index = await _pickIndex( + '选择设施类型', + _levelOptions, + selected: _levelOptions.indexOf(_customerLevel), + ); + if (index == null) return; + setState(() => _customerLevel = _levelOptions[index]); + } + + Future _pickStatus() async { + final index = await _pickIndex( + '选择状态', + _statusValues.map(customerStatusText).toList(), + selected: _statusValues.indexOf(_status), + ); + if (index == null) return; + setState(() => _status = _statusValues[index]); + } + + Future _pickSalesman() async { + final index = await _pickIndex( + '选择负责业务员', + _salesmanLabels, + selected: _salesmanIndex, + ); + if (index == null) return; + setState(() => _salesmanIndex = index); + } + + Future _pickIndex( + String title, + List options, { + int? selected, + }) { + return showModalBottomSheet( + context: context, + backgroundColor: AppColors.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.xl)), + ), + builder: (ctx) => SafeArea( + top: false, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Row( + children: [ + Expanded( + child: Text( + title, + style: AppTypography.titleSm.copyWith(fontSize: 16), + ), + ), + GestureDetector( + onTap: () => Navigator.of(ctx).pop(), + behavior: HitTestBehavior.opaque, + child: const XIcon('close', size: 20, color: AppColors.textMuted), + ), + ], + ), + ), + Container(height: 1, color: AppColors.borderRule), + Flexible( + child: ListView.builder( + shrinkWrap: true, + itemCount: options.length, + itemBuilder: (_, i) { + final sel = selected == i; + return InkWell( + onTap: () => Navigator.of(ctx).pop(i), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 14, + ), + decoration: const BoxDecoration( + border: Border( + bottom: BorderSide(color: AppColors.borderRule), + ), + ), + child: Row( + children: [ + Expanded( + child: Text( + options[i], + style: AppTypography.bodyMd.copyWith( + color: sel + ? AppColors.primary + : AppColors.onSurface, + ), + ), + ), + if (sel) + const XIcon('check', size: 18, color: AppColors.primary), + ], + ), + ), + ); + }, + ), + ), + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return XPageShell( + topBar: XTopBar.nav( + title: _isEdit ? '编辑客户' : '新增客户', + onBack: () => context.pop(), + ), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 60), + child: Column( + children: [ + _buildForm(), + XPrimaryButton( + label: '保存', + loading: _saving, + onPressed: _onSave, + margin: const EdgeInsets.fromLTRB(16, 24, 16, 40), + ), + ], + ), + ), + ); + } + + Widget _buildForm() { + final fields = [ + _field( + '客户名称', + required: true, + control: _input(_customerName, '请输入客户名称'), + ), + _field( + '客户编号', + control: _input(_customerNo, '保存后自动生成', enabled: !_isEdit), + ), + _field( + '省市区', + control: _picker( + text: _regionText, + placeholder: _province.isEmpty, + onTap: _pickRegion, + ), + ), + _field('详细地址', control: _input(_address, '请输入详细地址')), + _field('联系人', control: _input(_contactPerson, '请输入联系人')), + _field( + '联系电话', + control: _input(_contactPhone, '请输入联系电话', number: true), + ), + _field('邮编', control: _input(_postalCode, '选填', number: true)), + _field('传真', control: _input(_fax, '选填')), + _field( + '设施类型', + control: _picker( + text: _customerLevel.isEmpty ? '请选择设施类型' : _customerLevel, + placeholder: _customerLevel.isEmpty, + onTap: _pickLevel, + ), + ), + _field( + '状态', + control: _picker( + text: customerStatusText(_status), + placeholder: false, + onTap: _pickStatus, + ), + ), + if (_isAdmin) + _field( + '负责业务员', + control: _picker( + text: _salesmanIndex > 0 ? _salesmanLabels[_salesmanIndex] : '未指定', + placeholder: _salesmanIndex <= 0, + onTap: _pickSalesman, + ), + ), + ]; + + return XCard( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 16), + child: Column( + children: [ + for (var i = 0; i < fields.length; i++) ...[ + if (i > 0) Container(height: 1, color: AppColors.borderRule), + fields[i], + ], + ], + ), + ); + } + + Widget _field(String label, {bool required = false, required Widget control}) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text.rich( + TextSpan( + children: [ + TextSpan(text: label), + if (required) + const TextSpan( + text: ' *', + style: TextStyle(color: AppColors.statusError), + ), + ], + ), + style: AppTypography.labelBold.copyWith( + color: AppColors.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + control, + ], + ), + ); + } + + Widget _input( + TextEditingController controller, + String hint, { + bool enabled = true, + bool number = false, + }) { + return Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: Center( + child: TextField( + controller: controller, + enabled: enabled, + keyboardType: number ? TextInputType.number : TextInputType.text, + style: AppTypography.bodyMd.copyWith(color: AppColors.onSurface), + cursorColor: AppColors.primary, + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + hintText: hint, + hintStyle: AppTypography.bodyMd.copyWith( + color: AppColors.textPlaceholder, + ), + contentPadding: EdgeInsets.zero, + ), + ), + ), + ); + } + + Widget _picker({ + required String text, + required bool placeholder, + required VoidCallback onTap, + }) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + Expanded( + child: Text( + text, + style: AppTypography.bodyMd.copyWith( + color: placeholder + ? AppColors.textPlaceholder + : AppColors.onSurface, + ), + ), + ), + const XIcon('forward', size: 16, color: AppColors.outline), + ], + ), + ), + ); + } +} + +/// 省 / 市 / 区三级选择器(自建,替代 uni 的 region picker)。 +class _RegionPickerSheet extends StatefulWidget { + const _RegionPickerSheet(); + + @override + State<_RegionPickerSheet> createState() => _RegionPickerSheetState(); +} + +class _RegionPickerSheetState extends State<_RegionPickerSheet> { + int _level = 0; + String? _province; + String? _city; + + void _back() { + setState(() { + if (_level == 2) { + _city = null; + } else { + _province = null; + } + _level--; + }); + } + + @override + Widget build(BuildContext context) { + final List items; + if (_level == 0) { + items = _regionData.keys.toList(); + } else if (_level == 1) { + items = _regionData[_province]!.keys.toList(); + } else { + items = _regionData[_province!]![_city!]!; + } + final crumbs = [_province, _city].whereType().join(' '); + + return SafeArea( + top: false, + child: Container( + decoration: const BoxDecoration( + color: AppColors.surface, + borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.xl)), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Row( + children: [ + if (_level > 0) + GestureDetector( + onTap: _back, + behavior: HitTestBehavior.opaque, + child: const XIcon('back', size: 20, color: AppColors.primary), + ), + const SizedBox(width: 6), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '选择省市区', + style: AppTypography.titleSm.copyWith(fontSize: 16), + ), + if (crumbs.isNotEmpty) + Text( + crumbs, + style: AppTypography.bodyMd.copyWith( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + ], + ), + ), + GestureDetector( + onTap: () => Navigator.of(context).pop(), + behavior: HitTestBehavior.opaque, + child: const XIcon('close', size: 20, color: AppColors.textMuted), + ), + ], + ), + ), + Container(height: 1, color: AppColors.borderRule), + Flexible( + child: ListView.builder( + shrinkWrap: true, + itemCount: items.length, + itemBuilder: (_, i) { + final name = items[i]; + return InkWell( + onTap: () { + if (_level == 0) { + setState(() { + _province = name; + _level = 1; + }); + } else if (_level == 1) { + setState(() { + _city = name; + _level = 2; + }); + } else { + Navigator.of(context).pop( + ( + province: _province!, + city: _city!, + district: name, + ), + ); + } + }, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 14, + ), + decoration: const BoxDecoration( + border: Border( + bottom: BorderSide(color: AppColors.borderRule), + ), + ), + child: Text( + name, + style: AppTypography.bodyMd.copyWith( + color: AppColors.onSurface, + ), + ), + ), + ); + }, + ), + ), + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/customer/presentation/customer_tab.dart b/lib/features/customer/presentation/customer_tab.dart new file mode 100644 index 0000000..84f3851 --- /dev/null +++ b/lib/features/customer/presentation/customer_tab.dart @@ -0,0 +1,465 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/tab_index.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../data/customer_api.dart'; +import '../data/customer_models.dart'; + +/// 客户 Tab,对应 `components/tabs/CustomerTab.vue`。 +class CustomerTab extends ConsumerStatefulWidget { + const CustomerTab({super.key}); + + @override + ConsumerState createState() => _CustomerTabState(); +} + +class _CustomerTabState extends ConsumerState { + static const _statusOptions = <({String label, int? value})>[ + (label: '全部', value: null), + (label: '意向', value: 1), + (label: '签约', value: 2), + (label: '运维中', value: 3), + (label: '终止', value: 4), + ]; + + static const _levelOptions = <({String label, String? value})>[ + (label: '全部', value: null), + (label: '医院', value: '医院'), + (label: '学校', value: '学校'), + (label: '企业', value: '企业'), + ]; + + final _searchController = TextEditingController(); + + Timer? _searchTimer; + List _list = const []; + bool _loading = false; + int? _filterStatus; + String? _filterLevel; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => _load()); + } + + @override + void dispose() { + _searchTimer?.cancel(); + _searchController.dispose(); + super.dispose(); + } + + Future _load() async { + setState(() => _loading = true); + try { + // 列表由后端按 keyword / status 过滤;设施类型后端未提供查询条件,前端过滤 + final keyword = _searchController.text.trim(); + final res = await ref + .read(customerApiProvider) + .list( + page: 1, + pageSize: 100, + keyword: keyword.isEmpty ? null : keyword, + status: _filterStatus, + ); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() => _list = res.data!.list); + } + } catch (_) { + showAppToast('加载客户失败'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _onSearchChanged(String _) { + _searchTimer?.cancel(); + _searchTimer = Timer(const Duration(milliseconds: 350), _load); + } + + void _onStatusChip(int? value) { + if (_filterStatus == value) return; + setState(() => _filterStatus = value); + _load(); + } + + String? _statusAction(int status) { + if (status == 1) return '跟进展'; + if (status == 2) return '安排'; + return null; + } + + Future _goDetail(Customer c) async { + await context.push('/customer/detail/${c.id}'); + if (mounted) _load(); + } + + Future _goEdit(Customer c) async { + await context.push('/customer/edit?id=${c.id}'); + if (mounted) _load(); + } + + Future _goCreate() async { + await context.push('/customer/edit'); + if (mounted) _load(); + } + + @override + Widget build(BuildContext context) { + ref.listen(tabIndexProvider, (previous, next) { + if (next == AppTab.customer) _load(); + }); + + final visible = _filterLevel == null + ? _list + : _list.where((c) => c.customerLevel == _filterLevel).toList(); + + return Stack( + children: [ + XPageShell( + topBar: XTopBar.brand( + title: '鑫潼智电', + trailingColor: AppColors.primary, + ), + child: Column( + children: [ + _buildPageHead(), + _buildSearchBar(), + _buildFilters(), + Expanded(child: _buildList(visible)), + ], + ), + ), + Positioned( + right: 20, + bottom: 110, + child: GestureDetector( + onTap: _goCreate, + behavior: HitTestBehavior.opaque, + child: Container( + width: 52, + height: 52, + alignment: Alignment.center, + decoration: BoxDecoration( + color: AppColors.primary, + borderRadius: BorderRadius.circular(14), + boxShadow: const [ + BoxShadow( + color: Color(0x4D0054CD), + blurRadius: 16, + offset: Offset(0, 6), + ), + ], + ), + child: const XIcon('add', size: 24, color: Colors.white), + ), + ), + ), + ], + ); + } + + Widget _buildPageHead() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('客户', style: AppTypography.headlineMd), + Padding( + padding: const EdgeInsets.only(top: 2), + child: const Text( + '管理和跟踪您的运营客户组合', + style: TextStyle(fontSize: 14, color: AppColors.textMuted), + ), + ), + ], + ), + ); + } + + Widget _buildSearchBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 8), + child: XSearchField( + controller: _searchController, + hintText: '按客户名称、联系人或电话搜索...', + onChanged: _onSearchChanged, + ), + ); + } + + Widget _buildFilters() { + return Padding( + padding: const EdgeInsets.only(top: 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildFilterGroup( + '生命周期状态', + Row( + children: [ + for (final option in _statusOptions) + Padding( + padding: const EdgeInsets.only(right: 8), + child: XFilterChip( + label: option.label, + selected: _filterStatus == option.value, + onTap: () => _onStatusChip(option.value), + ), + ), + ], + ), + ), + _buildFilterGroup( + '设施类型', + Row( + children: [ + for (final option in _levelOptions) + Padding( + padding: const EdgeInsets.only(right: 8), + child: XFilterChip( + label: option.label, + selected: _filterLevel == option.value, + onTap: () => setState(() => _filterLevel = option.value), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildFilterGroup(String label, Widget chips) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(left: 16, right: 16, bottom: 6), + child: Text( + label, + style: AppTypography.captionSm.copyWith( + color: AppColors.textMuted, + letterSpacing: 1, + ), + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 16), + child: chips, + ), + ], + ), + ); + } + + Widget _buildList(List visible) { + if (_loading && _list.isEmpty) { + return const XPlaceholder(text: '加载中...'); + } + if (visible.isEmpty) { + return const XPlaceholder(text: '暂无客户'); + } + return RefreshIndicator( + color: AppColors.primary, + onRefresh: _load, + child: ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 140), + itemCount: visible.length, + itemBuilder: (context, index) => _customerCard(visible[index]), + ), + ); + } + + Widget _customerCard(Customer c) { + final action = _statusAction(c.status); + + return XCard( + padding: EdgeInsets.zero, + margin: const EdgeInsets.only(bottom: 12), + onTap: () => _goDetail(c), + child: Stack( + children: [ + // 左侧状态色条 / 右侧编号面板均贴边,圆角按卡片圆角裁出 + Positioned( + left: 0, + top: 0, + bottom: 0, + width: 4, + child: DecoratedBox( + decoration: BoxDecoration( + color: customerStatusBarColor(c.status), + borderRadius: const BorderRadius.horizontal( + left: Radius.circular(AppRadius.lg), + ), + ), + ), + ), + const Positioned( + right: 0, + top: 0, + bottom: 0, + width: 86, + child: DecoratedBox( + decoration: BoxDecoration( + color: AppColors.surfaceBright, + borderRadius: BorderRadius.horizontal( + right: Radius.circular(AppRadius.lg), + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.only(left: 4, right: 86), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Wrap( + spacing: 6, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + c.customerName, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + XChip( + customerStatusText(c.status), + tone: customerStatusTone(c.status), + ), + if (c.customerLevel.isNotEmpty) + XChip(c.customerLevel, tone: ChipTone.muted), + ], + ), + ), + const SizedBox(width: 6), + const XIcon('more', size: 20, color: AppColors.textMuted), + ], + ), + const SizedBox(height: 10), + Row( + children: [ + const XIcon( + 'location', + size: 16, + color: AppColors.textMuted, + ), + const SizedBox(width: 4), + Text( + c.locationText, + style: const TextStyle( + fontSize: 14, + color: AppColors.textMuted, + ), + ), + const SizedBox(width: 16), + const XIcon('person', size: 16, color: AppColors.textMuted), + const SizedBox(width: 4), + Text( + c.contactPerson.isEmpty ? '-' : c.contactPerson, + style: const TextStyle( + fontSize: 14, + color: AppColors.textMuted, + ), + ), + ], + ), + ], + ), + ), + ), + Positioned( + right: 0, + top: 0, + bottom: 0, + width: 86, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + '客户编号', + style: TextStyle(fontSize: 11, color: AppColors.textMuted), + ), + const SizedBox(height: 6), + Text( + c.customerNo, + style: AppTypography.dataMono.copyWith( + fontSize: 11, + color: AppColors.onSurface, + ), + ), + if (action != null) ...[ + const SizedBox(height: 6), + GestureDetector( + onTap: () => _goEdit(c), + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: const Color(0x1A712AE2), + borderRadius: BorderRadius.circular(AppRadius.regular), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const XIcon( + 'calendar', + size: 14, + color: AppColors.secondary, + ), + const SizedBox(width: 2), + Text( + action, + style: AppTypography.captionSm.copyWith( + color: AppColors.secondary, + ), + ), + ], + ), + ), + ), + ], + ], + ), + ), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/dashboard/data/dashboard_api.dart b/lib/features/dashboard/data/dashboard_api.dart new file mode 100644 index 0000000..9b96a56 --- /dev/null +++ b/lib/features/dashboard/data/dashboard_api.dart @@ -0,0 +1,22 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/network/api_client.dart'; +import '../../../core/network/api_response.dart'; +import '../../../core/providers.dart'; +import 'dashboard_models.dart'; + +final dashboardApiProvider = Provider( + (ref) => DashboardApi(ref.watch(apiClientProvider)), +); + +/// 工作台统计接口,对应 uni-app 版 `api/dashboard.ts`。 +class DashboardApi { + DashboardApi(this._client); + + final ApiClient _client; + + Future> stats() => _client.get( + '/dashboard/stats', + parse: (d) => DashboardStats.fromJson((d as Map).cast()), + ); +} \ No newline at end of file diff --git a/lib/features/dashboard/data/dashboard_models.dart b/lib/features/dashboard/data/dashboard_models.dart new file mode 100644 index 0000000..ee5aa78 --- /dev/null +++ b/lib/features/dashboard/data/dashboard_models.dart @@ -0,0 +1,159 @@ +import '../../../core/utils/id_util.dart'; + +/// 名称/数值二元组(勘察状态分布、模块统计、客户状态分布)。 +class NameValue { + const NameValue({required this.name, required this.value}); + + final String name; + final int value; + + factory NameValue.fromJson(Map json) => NameValue( + name: json['name'] as String? ?? '', + value: (json['value'] as num?)?.toInt() ?? 0, + ); +} + +/// 近期勘察派单流水。 +class DashboardSurveyItem { + const DashboardSurveyItem({ + required this.id, + required this.orderNo, + required this.customerName, + required this.locale, + required this.owner, + required this.status, + required this.time, + }); + + final int id; + final String orderNo; + final String customerName; + final String locale; + final String owner; + + /// 0 待指派 / 1 现场勘察中 / 2 待技术复核 / 3 已归档 / 5 已取消 + final int status; + final String time; + + factory DashboardSurveyItem.fromJson(Map json) => + DashboardSurveyItem( + id: toIntOr(json['id'], 0), + orderNo: json['orderNo'] as String? ?? '', + customerName: json['customerName'] as String? ?? '', + locale: json['locale'] as String? ?? '', + owner: json['owner'] as String? ?? '', + status: toIntOr(json['status'], 0), + time: json['time'] as String? ?? '', + ); +} + +/// 智电工程推进看板(contract 聚合)。 +class DashboardProjectItem { + const DashboardProjectItem({ + required this.id, + required this.customerName, + required this.amount, + required this.stage, + required this.stageLabel, + required this.progress, + required this.owner, + required this.desc, + required this.orderNo, + }); + + final int id; + final String customerName; + final num amount; + final int stage; + final String stageLabel; + final int progress; + final String owner; + final String desc; + final String orderNo; + + factory DashboardProjectItem.fromJson(Map json) => + DashboardProjectItem( + id: toIntOr(json['id'], 0), + customerName: json['customerName'] as String? ?? '', + amount: (json['amount'] as num?) ?? 0, + stage: toIntOr(json['stage'], 0), + stageLabel: json['stageLabel'] as String? ?? '', + progress: toIntOr(json['progress'], 0), + owner: json['owner'] as String? ?? '', + desc: json['desc'] as String? ?? '', + orderNo: json['orderNo'] as String? ?? '', + ); +} + +/// `/api/dashboard/stats` 真实返回体(与后端 dashboard.service.ts 对齐)。 +class DashboardStats { + const DashboardStats({ + required this.customerTotal, + required this.customerMonthlyNew, + required this.contractTotal, + required this.contractYearAmount, + required this.surveyPending, + required this.surveyTotal, + required this.visitMonthly, + required this.visitTotal, + required this.planTotal, + required this.acceptTotal, + required this.surveyByStatus, + required this.modules, + required this.trend, + required this.customerStatus, + required this.customerSignRate, + required this.surveyList, + required this.projects, + }); + + final int customerTotal; + final int customerMonthlyNew; + final int contractTotal; + final num contractYearAmount; + final int surveyPending; + final int surveyTotal; + final int visitMonthly; + final int visitTotal; + final int planTotal; + final int acceptTotal; + final List surveyByStatus; + final List modules; + final List customerStatus; + final num customerSignRate; + final List surveyList; + final List projects; + + /// 趋势项字段为 `{ date, customers, contracts }`,App 端暂未使用,保留原始结构。 + final List> trend; + + factory DashboardStats.fromJson(Map json) => DashboardStats( + customerTotal: toIntOr(json['customerTotal'], 0), + customerMonthlyNew: toIntOr(json['customerMonthlyNew'], 0), + contractTotal: toIntOr(json['contractTotal'], 0), + contractYearAmount: (json['contractYearAmount'] as num?) ?? 0, + surveyPending: toIntOr(json['surveyPending'], 0), + surveyTotal: toIntOr(json['surveyTotal'], 0), + visitMonthly: toIntOr(json['visitMonthly'], 0), + visitTotal: toIntOr(json['visitTotal'], 0), + planTotal: toIntOr(json['planTotal'], 0), + acceptTotal: toIntOr(json['acceptTotal'], 0), + surveyByStatus: _nameValues(json['surveyByStatus']), + modules: _nameValues(json['modules']), + trend: (json['trend'] as List? ?? []) + .map((e) => (e as Map).cast()) + .toList(), + customerStatus: _nameValues(json['customerStatus']), + customerSignRate: (json['customerSignRate'] as num?) ?? 0, + surveyList: (json['surveyList'] as List? ?? []) + .map((e) => DashboardSurveyItem.fromJson((e as Map).cast())) + .toList(), + projects: (json['projects'] as List? ?? []) + .map((e) => DashboardProjectItem.fromJson((e as Map).cast())) + .toList(), + ); + + static List _nameValues(dynamic raw) => (raw as List? ?? []) + .map((e) => NameValue.fromJson((e as Map).cast())) + .toList(); +} \ No newline at end of file diff --git a/lib/features/mine/presentation/mine_tab.dart b/lib/features/mine/presentation/mine_tab.dart new file mode 100644 index 0000000..a432309 --- /dev/null +++ b/lib/features/mine/presentation/mine_tab.dart @@ -0,0 +1,345 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/tab_index.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../auth/application/session_controller.dart'; +import '../../auth/data/auth_models.dart'; +import '../../customer/data/customer_api.dart'; +import '../../dashboard/data/dashboard_api.dart'; + +/// 「我的」功能入口配置。 +typedef _MenuItem = ({ + String label, + String icon, + Color background, + Color color, + VoidCallback onTap, +}); + +/// 我的 Tab,对应 `components/tabs/MineTab.vue`。 +class MineTab extends ConsumerStatefulWidget { + const MineTab({super.key}); + + @override + ConsumerState createState() => _MineTabState(); +} + +class _MineTabState extends ConsumerState { + int _customerCount = 0; + int _activeProjects = 0; + int _surveys = 0; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => _load()); + } + + Future _load() async { + var customerCount = _customerCount; + var activeProjects = _activeProjects; + var surveys = _surveys; + + // 客户总数:独立接口 + try { + final res = await ref + .read(customerApiProvider) + .list(page: 1, pageSize: 1); + if (res.isOk) customerCount = res.data?.total ?? 0; + } catch (_) { + // 静默刷新:请求失败时保留已渲染的数据 + } + + // 进行中项目 + 勘测任务:一次 dashboard 请求 + try { + final res = await ref.read(dashboardApiProvider).stats(); + final dash = res.isOk ? res.data : null; + if (dash != null) { + activeProjects = dash.contractTotal; + surveys = dash.surveyTotal; + } + } catch (_) { + // 静默刷新:请求失败时保留已渲染的数据 + } + + if (!mounted) return; + setState(() { + _customerCount = customerCount; + _activeProjects = activeProjects; + _surveys = surveys; + }); + } + + Future _goSurvey() async { + await context.push('/survey'); + if (mounted) _load(); + } + + Future _onLogout() async { + final confirmed = await showAppConfirm( + title: '退出登录', + content: '确定要退出当前账号吗?', + destructive: true, + ); + if (!confirmed) return; + await ref.read(sessionProvider.notifier).logout(); + } + + @override + Widget build(BuildContext context) { + ref.listen(tabIndexProvider, (previous, next) { + if (next == AppTab.mine) _load(); + }); + + final user = ref.watch(sessionProvider).user; + final displayName = user?.displayName ?? '陈伟'; + final avatarText = user?.avatarText ?? '陈'; + final roleText = user == null ? '高级销售工程师' : roleLabel(user.roles); + + final menus = <_MenuItem>[ + ( + label: '客户管理', + icon: 'groups', + background: const Color(0x140054CD), + color: AppColors.primary, + onTap: () => + ref.read(tabIndexProvider.notifier).select(AppTab.customer), + ), + ( + label: '项目中心', + icon: 'calendar', + background: const Color(0x14712AE2), + color: AppColors.secondary, + onTap: () => + ref.read(tabIndexProvider.notifier).select(AppTab.project), + ), + ( + label: '勘测任务', + icon: 'camera', + background: const Color(0x1400685F), + color: AppColors.tertiary, + onTap: _goSurvey, + ), + ( + label: '设置', + icon: 'more', + background: const Color(0x14E0852B), + color: AppColors.statusWarn, + onTap: () => showAppToast('设置功能即将上线'), + ), + ]; + + return XPageShell( + topBar: XTopBar.brand(title: '我的'), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 130), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildUserCard(avatarText, displayName, roleText), + _buildStats(), + XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Column( + children: [ + for (var i = 0; i < menus.length; i++) ...[ + if (i > 0) + const Divider( + height: 1, + thickness: 1, + color: AppColors.borderRule, + ), + _menuItem(menus[i]), + ], + ], + ), + ), + XPrimaryButton( + label: '退出登录', + onPressed: _onLogout, + height: 46, + margin: const EdgeInsets.only(top: 28, bottom: 40), + background: AppColors.surface, + foreground: AppColors.statusError, + borderColor: AppColors.statusError, + fontSize: 15, + pill: false, + ), + ], + ), + ), + ); + } + + Widget _buildUserCard(String avatarText, String displayName, String roleText) { + return XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 18), + margin: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + Container( + width: 60, + height: 60, + alignment: Alignment.center, + decoration: BoxDecoration( + color: AppColors.surfaceContainerHigh, + shape: BoxShape.circle, + border: Border.all(color: AppColors.primaryFixedDim, width: 2), + ), + child: Text( + avatarText, + style: const TextStyle( + fontSize: 26, + fontWeight: FontWeight.w700, + color: AppColors.primary, + ), + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + displayName, + style: const TextStyle( + fontSize: 19, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + roleText, + style: const TextStyle( + fontSize: 13, + color: AppColors.textMuted, + ), + ), + ), + const Padding( + padding: EdgeInsets.only(top: 8), + child: XChip( + '在线', + tone: ChipTone.tertiary, + leading: _OnlineDot(), + ), + ), + ], + ), + ), + const XIcon('forward', size: 20, color: AppColors.onSurfaceVariant), + ], + ), + ); + } + + Widget _buildStats() { + return XCard( + padding: const EdgeInsets.symmetric(vertical: 20), + margin: const EdgeInsets.only(bottom: 14), + child: Row( + children: [ + _statCell('$_customerCount', '我的客户'), + const _StatDivider(), + _statCell('$_activeProjects', '进行中项目'), + const _StatDivider(), + _statCell('$_surveys', '勘测任务'), + ], + ), + ); + } + + Widget _statCell(String value, String label) { + return Expanded( + child: Column( + children: [ + Text( + value, + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + const SizedBox(height: 4), + Text( + label, + style: const TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ], + ), + ); + } + + Widget _menuItem(_MenuItem menu) { + return GestureDetector( + onTap: menu.onTap, + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 15), + child: Row( + children: [ + Container( + width: 36, + height: 36, + alignment: Alignment.center, + decoration: BoxDecoration( + color: menu.background, + borderRadius: BorderRadius.circular(10), + ), + child: XIcon(menu.icon, size: 20, color: menu.color), + ), + const SizedBox(width: 14), + Expanded( + child: Text( + menu.label, + style: const TextStyle( + fontSize: 15, + color: AppColors.onSurface, + ), + ), + ), + const XIcon('forward', size: 18, color: AppColors.outline), + ], + ), + ), + ); + } +} + +/// 个人信息卡「在线」chip 左侧的状态圆点。 +class _OnlineDot extends StatelessWidget { + const _OnlineDot(); + + @override + Widget build(BuildContext context) { + return Container( + width: 7, + height: 7, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: AppColors.tertiary, + ), + ); + } +} + +/// 统计卡内的 1px 分隔线。 +class _StatDivider extends StatelessWidget { + const _StatDivider(); + + @override + Widget build(BuildContext context) { + return Container(width: 1, height: 32, color: AppColors.borderRule); + } +} \ No newline at end of file diff --git a/lib/features/project/data/project_api.dart b/lib/features/project/data/project_api.dart new file mode 100644 index 0000000..a175833 --- /dev/null +++ b/lib/features/project/data/project_api.dart @@ -0,0 +1,73 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/network/api_client.dart'; +import '../../../core/network/api_response.dart'; +import '../../../core/providers.dart'; +import 'project_models.dart'; + +final projectApiProvider = Provider( + (ref) => ProjectApi(ref.watch(apiClientProvider)), +); + +/// 智电改造方案接口,对应后端 `/api/project-plans`。 +/// +/// 说明:uni-app 版项目模块使用本地 mock(`api/mock.ts`),字段与后端契约完全不一致; +/// Flutter 版按用户确认改为直连后端真实接口。 +class ProjectApi { + ProjectApi(this._client); + + final ApiClient _client; + + Future> list({ + int page = 1, + int pageSize = 100, + String? keyword, + int? customerId, + int? status, + String? registerStartDate, + String? registerEndDate, + }) => _client.get( + '/project-plans', + query: { + 'page': page, + 'pageSize': pageSize, + 'keyword': keyword, + 'customerId': customerId, + 'status': status, + 'registerStartDate': registerStartDate, + 'registerEndDate': registerEndDate, + }, + parse: (d) { + final m = (d as Map).cast(); + return ProjectPlanPage( + list: (m['list'] as List? ?? []) + .map((e) => ProjectPlan.fromJson((e as Map).cast())) + .toList(), + total: (m['total'] as num?)?.toInt() ?? 0, + page: (m['page'] as num?)?.toInt() ?? 1, + pageSize: (m['pageSize'] as num?)?.toInt() ?? pageSize, + ); + }, + ); + + Future> detail(int id) => _client.get( + '/project-plans/$id', + parse: (d) => ProjectPlan.fromJson((d as Map).cast()), + ); + + Future> create(Map body) => + _client.post( + '/project-plans', + body: body, + parse: (d) => ProjectPlan.fromJson((d as Map).cast()), + ); + + Future> update(int id, Map body) => + _client.put( + '/project-plans/$id', + body: body, + parse: (d) => ProjectPlan.fromJson((d as Map).cast()), + ); + + Future> delete(int id) => _client.delete('/project-plans/$id'); +} \ No newline at end of file diff --git a/lib/features/project/data/project_models.dart b/lib/features/project/data/project_models.dart new file mode 100644 index 0000000..e816a22 --- /dev/null +++ b/lib/features/project/data/project_models.dart @@ -0,0 +1,150 @@ +import 'package:flutter/painting.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/utils/id_util.dart'; + +/// 方案状态:0 草稿 1 已确认。 +abstract final class ProjectPlanStatus { + static const draft = 0; + static const confirmed = 1; +} + +const projectStatusMap = { + 0: (text: '草稿', tone: ChipTone.warn), + 1: (text: '已确认', tone: ChipTone.primary), +}; + +String projectStatusText(int? s) => projectStatusMap[s]?.text ?? '未知'; + +ChipTone projectStatusTone(int? s) => projectStatusMap[s]?.tone ?? ChipTone.muted; + +/// 列表卡片左侧色条颜色。 +Color projectStatusBarColor(int? status) => switch (status) { + 0 => AppColors.statusWarn, + 1 => AppColors.primary, + _ => AppColors.borderRule, +}; + +/// 项目方案设备明细,对应后端 `project_plan_detail` 表。 +class ProjectPlanDetail { + const ProjectPlanDetail({ + required this.id, + required this.planId, + required this.customerId, + required this.equipName, + required this.quantity, + this.equipId, + this.smartDeviceId, + this.remark, + }); + + final int id; + final int planId; + final int customerId; + final String equipName; + final num quantity; + final int? equipId; + final int? smartDeviceId; + final String? remark; + + factory ProjectPlanDetail.fromJson(Map json) => ProjectPlanDetail( + id: toIntOr(json['id'], 0), + planId: toIntOr(json['planId'], 0), + customerId: toIntOr(json['customerId'], 0), + equipName: json['equipName'] as String? ?? '', + quantity: (json['quantity'] as num?) ?? 1, + equipId: toIntOrNull(json['equipId']), + smartDeviceId: toIntOrNull(json['smartDeviceId']), + remark: json['remark'] as String?, + ); + + Map toJson() => { + 'equipName': equipName, + 'quantity': quantity, + if (equipId != null) 'equipId': equipId, + if (smartDeviceId != null) 'smartDeviceId': smartDeviceId, + if (remark != null && remark!.isNotEmpty) 'remark': remark, + }; + + ProjectPlanDetail copyWith({String? equipName, num? quantity, String? remark}) => + ProjectPlanDetail( + id: id, + planId: planId, + customerId: customerId, + equipName: equipName ?? this.equipName, + quantity: quantity ?? this.quantity, + equipId: equipId, + smartDeviceId: smartDeviceId, + remark: remark ?? this.remark, + ); +} + +/// 智电改造方案,与后端 `/api/project-plans` 契约对齐。 +class ProjectPlan { + const ProjectPlan({ + required this.id, + required this.planNo, + required this.customerId, + required this.status, + this.registrar, + this.registerTime, + this.planDesc, + this.planFileUrl, + this.createdAt, + this.details = const [], + }); + + final int id; + final String planNo; + final int customerId; + + /// 方案登记人(业务员姓名文本) + final String? registrar; + + /// 方案登记时间(DATEONLY,`YYYY-MM-DD`) + final String? registerTime; + final String? planDesc; + + /// 方案最终文件 URL + final String? planFileUrl; + final String? createdAt; + + /// 设备明细,仅详情接口返回 + final List details; + final int status; + + factory ProjectPlan.fromJson(Map json) => ProjectPlan( + id: toIntOr(json['id'], 0), + planNo: json['planNo'] as String? ?? '', + customerId: toIntOr(json['customerId'], 0), + registrar: json['registrar'] as String?, + registerTime: json['registerTime'] as String?, + planDesc: json['planDesc'] as String?, + planFileUrl: json['planFileUrl'] as String?, + createdAt: json['created_at'] as String?, + details: (json['details'] as List? ?? []) + .map((e) => ProjectPlanDetail.fromJson((e as Map).cast())) + .toList(), + status: toIntOr(json['status'], 0), + ); + + /// 设备明细合计数量。 + num get detailQuantityTotal => + details.fold(0, (sum, d) => sum + d.quantity); + + String get displayTitle => planNo.isNotEmpty ? planNo : '方案 #$id'; +} + +class ProjectPlanPage { + const ProjectPlanPage({ + required this.list, + required this.total, + required this.page, + required this.pageSize, + }); + + final List list; + final int total; + final int page; + final int pageSize; +} \ No newline at end of file diff --git a/lib/features/project/presentation/project_detail_page.dart b/lib/features/project/presentation/project_detail_page.dart new file mode 100644 index 0000000..1801dd0 --- /dev/null +++ b/lib/features/project/presentation/project_detail_page.dart @@ -0,0 +1,338 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/format_util.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../customer/data/customer_api.dart'; +import '../data/project_api.dart'; +import '../data/project_models.dart'; + +/// 项目详情页。 +/// +/// 源 `pages/project/detail.vue` 基于 mock 数据(团队 / 里程碑 / 设备概览等), +/// 这里按用户确认改为直连后端 `/api/project-plans/:id`,保留信息卡 + 分组 + 明细列表的视觉语言。 +class ProjectDetailPage extends ConsumerStatefulWidget { + const ProjectDetailPage({super.key, required this.id}); + + final int id; + + @override + ConsumerState createState() => _ProjectDetailPageState(); +} + +class _ProjectDetailPageState extends ConsumerState { + ProjectPlan? _plan; + String? _customerName; + bool _loading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + setState(() => _loading = true); + try { + final res = await ref.read(projectApiProvider).detail(widget.id); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() => _plan = res.data); + await _loadCustomer(res.data!.customerId); + } else { + showAppToast(res.message.isEmpty ? '方案不存在' : res.message); + } + } catch (_) { + if (mounted) showAppToast('加载失败'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + Future _loadCustomer(int customerId) async { + try { + final res = await ref.read(customerApiProvider).detail(customerId); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() => _customerName = res.data!.customerName); + } + } catch (_) { + // 客户名称获取失败时降级为「客户 #id」 + } + } + + String _customerLabel(int customerId) { + final name = _customerName; + return (name == null || name.isEmpty) ? '客户 #$customerId' : name; + } + + String _textOrDash(String? value) => + (value == null || value.isEmpty) ? '-' : value; + + String _formatQty(num quantity) => quantity == quantity.roundToDouble() + ? quantity.toInt().toString() + : quantity.toString(); + + @override + Widget build(BuildContext context) { + final planNo = _plan?.planNo; + return XPageShell( + topBar: XTopBar.nav( + title: (planNo == null || planNo.isEmpty) ? '方案详情' : planNo, + onBack: () => context.pop(), + ), + child: _buildBody(), + ); + } + + Widget _buildBody() { + final p = _plan; + if (p == null) { + return XPlaceholder(text: _loading ? '加载中...' : '方案不存在'); + } + + return SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 60), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildHeaderCard(p), + _buildInfoCard(p), + _buildDetailSection(p), + ], + ), + ); + } + + Widget _buildHeaderCard(ProjectPlan p) { + return XCard( + padding: const EdgeInsets.all(16), + margin: const EdgeInsets.only(bottom: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 6, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + _customerLabel(p.customerId), + style: AppTypography.headlineMdMobile.copyWith( + color: AppColors.onSurface, + ), + ), + XChip( + projectStatusText(p.status), + tone: projectStatusTone(p.status), + ), + ], + ), + const SizedBox(height: 10), + Row( + children: [ + Text( + '方案单号', + style: AppTypography.bodyMd.copyWith( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + const SizedBox(width: 8), + Text( + p.displayTitle, + style: AppTypography.dataMono.copyWith( + color: AppColors.onSurface, + ), + ), + ], + ), + ], + ), + ); + } + + Widget _buildInfoCard(ProjectPlan p) { + final items = [ + _infoItem('person', '登记人', _textOrDash(p.registrar)), + _infoItem('calendar', '登记时间', formatDate(p.registerTime)), + _infoItem('clock', '创建时间', formatDateTime(p.createdAt)), + _infoItem('category', '方案说明', _textOrDash(p.planDesc)), + ]; + + return XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Column( + children: [ + for (var i = 0; i < items.length; i++) ...[ + if (i > 0) Container(height: 1, color: AppColors.borderRule), + items[i], + ], + if (p.planFileUrl != null && p.planFileUrl!.isNotEmpty) ...[ + Container(height: 1, color: AppColors.borderRule), + _buildFileRow(p.planFileUrl!), + ], + ], + ), + ); + } + + Widget _infoItem(String icon, String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 13), + child: Row( + children: [ + XIcon(icon, size: 18, color: AppColors.textMuted), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: AppTypography.bodyMd.copyWith( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + Text( + value, + style: AppTypography.bodyMd.copyWith( + color: AppColors.onSurface, + ), + ), + ], + ), + ), + ], + ), + ); + } + + /// 方案文件:源页面用 uni 下载打开,Flutter 未引入 url_launcher,这里仅展示链接文本。 + Widget _buildFileRow(String url) { + return GestureDetector( + onTap: () => showAppToast(url), + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 13), + child: Row( + children: [ + const XIcon('domain', size: 18, color: AppColors.textMuted), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '方案文件', + style: AppTypography.bodyMd.copyWith( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + Text( + url, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppTypography.bodyMd.copyWith( + color: AppColors.primary, + ), + ), + ], + ), + ), + const SizedBox(width: 6), + const XIcon('forward', size: 16, color: AppColors.textPlaceholder), + ], + ), + ), + ); + } + + Widget _buildDetailSection(ProjectPlan p) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.only(top: 22, bottom: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const XSectionTitle('设备明细', icon: 'category', fontSize: 16), + Text( + '合计 ${_formatQty(p.detailQuantityTotal)}', + style: AppTypography.dataMono.copyWith( + color: AppColors.primary, + ), + ), + ], + ), + ), + if (p.details.isEmpty) + const XPlaceholder(text: '暂无设备明细', dashed: true) + else + _buildDetailCard(p.details), + ], + ); + } + + Widget _buildDetailCard(List details) { + final items = []; + for (var i = 0; i < details.length; i++) { + if (i > 0) items.add(Container(height: 1, color: AppColors.borderRule)); + items.add(_detailItem(details[i])); + } + return XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Column(children: items), + ); + } + + Widget _detailItem(ProjectPlanDetail d) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 13), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + d.equipName.isEmpty ? '未命名设备' : d.equipName, + style: AppTypography.bodyMd.copyWith( + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + if (d.remark != null && d.remark!.isNotEmpty) ...[ + const SizedBox(height: 2), + Text( + d.remark!, + style: AppTypography.bodyMd.copyWith( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + ], + ], + ), + ), + const SizedBox(width: 12), + Text( + '×${_formatQty(d.quantity)}', + style: AppTypography.dataMono.copyWith(color: AppColors.primary), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/project/presentation/project_tab.dart b/lib/features/project/presentation/project_tab.dart new file mode 100644 index 0000000..8e582b6 --- /dev/null +++ b/lib/features/project/presentation/project_tab.dart @@ -0,0 +1,330 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/tab_index.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/format_util.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../customer/data/customer_api.dart'; +import '../data/project_api.dart'; +import '../data/project_models.dart'; + +/// 项目 Tab。 +/// +/// 源 `components/tabs/ProjectTab.vue` 使用本地 mock(字段为 projectName / progress / stage 等), +/// 这里按用户确认改为直连后端 `/api/project-plans`,视觉沿用原卡片式语言但字段换成后端真实字段。 +class ProjectTab extends ConsumerStatefulWidget { + const ProjectTab({super.key}); + + @override + ConsumerState createState() => _ProjectTabState(); +} + +class _ProjectTabState extends ConsumerState { + static const _statusOptions = <({String label, int? value})>[ + (label: '全部', value: null), + (label: '草稿', value: ProjectPlanStatus.draft), + (label: '已确认', value: ProjectPlanStatus.confirmed), + ]; + + final _searchController = TextEditingController(); + + Timer? _searchTimer; + List _list = const []; + Map _customerNames = const {}; + bool _loading = false; + int? _filterStatus; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + _loadCustomers(); + _load(); + }); + } + + @override + void dispose() { + _searchTimer?.cancel(); + _searchController.dispose(); + super.dispose(); + } + + /// `/project-plans` 只返回 customerId,需要先建立 id → 客户名称 映射用于展示。 + Future _loadCustomers() async { + try { + final res = await ref + .read(customerApiProvider) + .list(page: 1, pageSize: 200); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() { + _customerNames = { + for (final c in res.data!.list) c.id: c.customerName, + }; + }); + } + } catch (_) { + // 客户名称映射失败时降级为「客户 #id」,不影响方案列表展示 + } + } + + Future _load() async { + setState(() => _loading = true); + try { + final keyword = _searchController.text.trim(); + final res = await ref + .read(projectApiProvider) + .list( + page: 1, + pageSize: 100, + keyword: keyword.isEmpty ? null : keyword, + status: _filterStatus, + ); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() => _list = res.data!.list); + } + } catch (_) { + showAppToast('加载方案失败'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _onSearchChanged(String _) { + _searchTimer?.cancel(); + _searchTimer = Timer(const Duration(milliseconds: 350), _load); + } + + void _onStatusChip(int? value) { + if (_filterStatus == value) return; + setState(() => _filterStatus = value); + _load(); + } + + Future _goDetail(ProjectPlan p) async { + await context.push('/project/detail/${p.id}'); + if (mounted) _load(); + } + + String _customerLabel(int customerId) { + final name = _customerNames[customerId]; + return (name == null || name.isEmpty) ? '客户 #$customerId' : name; + } + + @override + Widget build(BuildContext context) { + ref.listen(tabIndexProvider, (previous, next) { + if (next == AppTab.project) _load(); + }); + + return XPageShell( + topBar: XTopBar.brand( + title: '鑫潼智电', + trailingColor: AppColors.primary, + ), + child: Column( + children: [ + _buildPageHead(), + _buildSearchBar(), + _buildFilters(), + Expanded(child: _buildList()), + ], + ), + ); + } + + Widget _buildPageHead() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('项目', style: AppTypography.headlineMd), + Padding( + padding: const EdgeInsets.only(top: 2), + child: const Text( + '管理与跟踪智电改造方案', + style: TextStyle(fontSize: 14, color: AppColors.textMuted), + ), + ), + ], + ), + ); + } + + Widget _buildSearchBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 8), + child: XSearchField( + controller: _searchController, + hintText: '按方案单号或说明搜索...', + onChanged: _onSearchChanged, + ), + ); + } + + Widget _buildFilters() { + return Padding( + padding: const EdgeInsets.only(left: 16, right: 16, top: 4, bottom: 8), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final option in _statusOptions) + Padding( + padding: const EdgeInsets.only(right: 8), + child: XFilterChip( + label: option.label, + selected: _filterStatus == option.value, + onTap: () => _onStatusChip(option.value), + ), + ), + ], + ), + ), + ); + } + + Widget _buildList() { + if (_loading && _list.isEmpty) { + return const XPlaceholder(text: '加载中...'); + } + if (_list.isEmpty) { + return const XPlaceholder(text: '暂无方案'); + } + return RefreshIndicator( + color: AppColors.primary, + onRefresh: _load, + child: ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 120), + itemCount: _list.length, + itemBuilder: (context, index) => _planCard(_list[index]), + ), + ); + } + + Widget _planCard(ProjectPlan p) { + final registrar = p.registrar; + + return XCard( + padding: EdgeInsets.zero, + margin: const EdgeInsets.only(bottom: 12), + onTap: () => _goDetail(p), + child: Stack( + children: [ + // 左侧状态色条贴边,圆角按卡片圆角裁出 + Positioned( + left: 0, + top: 0, + bottom: 0, + width: 4, + child: DecoratedBox( + decoration: BoxDecoration( + color: projectStatusBarColor(p.status), + borderRadius: const BorderRadius.horizontal( + left: Radius.circular(AppRadius.lg), + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.only(left: 4), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + _customerLabel(p.customerId), + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + ), + const SizedBox(width: 8), + XChip( + projectStatusText(p.status), + tone: projectStatusTone(p.status), + ), + ], + ), + const SizedBox(height: 6), + Text( + p.displayTitle, + style: AppTypography.dataMono.copyWith( + color: AppColors.textMuted, + ), + ), + const SizedBox(height: 10), + Row( + children: [ + const XIcon( + 'person', + size: 15, + color: AppColors.textMuted, + ), + const SizedBox(width: 4), + Expanded( + child: Text( + (registrar == null || registrar.isEmpty) + ? '未填写登记人' + : registrar, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13, + color: AppColors.textMuted, + ), + ), + ), + const SizedBox(width: 12), + const XIcon('clock', size: 15, color: AppColors.textMuted), + const SizedBox(width: 4), + Text( + formatDate(p.registerTime), + style: AppTypography.dataMono.copyWith( + color: AppColors.textMuted, + ), + ), + ], + ), + if (p.planDesc != null && p.planDesc!.isNotEmpty) ...[ + const SizedBox(height: 8), + Text( + p.planDesc!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13, + color: AppColors.onSurfaceVariant, + ), + ), + ], + ], + ), + ), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/survey/data/survey_api.dart b/lib/features/survey/data/survey_api.dart new file mode 100644 index 0000000..a65ffd8 --- /dev/null +++ b/lib/features/survey/data/survey_api.dart @@ -0,0 +1,95 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/network/api_client.dart'; +import '../../../core/network/api_response.dart'; +import '../../../core/providers.dart'; +import 'survey_models.dart'; + +final surveyApiProvider = Provider( + (ref) => SurveyApi(ref.watch(apiClientProvider)), +); + +/// SOP 回执增量保存结果。 +class SopSaveResult { + const SopSaveResult({required this.updated, required this.skipped, required this.sopResults}); + + final int updated; + final List skipped; + final List sopResults; + + factory SopSaveResult.fromJson(Map json) => SopSaveResult( + updated: (json['updated'] as num?)?.toInt() ?? 0, + skipped: (json['skipped'] as List? ?? []).map((e) => (e as num).toInt()).toList(), + sopResults: (json['sopResults'] as List? ?? []) + .map((e) => SurveySopResult.fromJson((e as Map).cast())) + .toList(), + ); +} + +/// 勘察工单接口,对应 uni-app 版 `api/survey.ts`。 +class SurveyApi { + SurveyApi(this._client); + + final ApiClient _client; + + Future> list({ + int page = 1, + int pageSize = 100, + String? keyword, + int? status, + int? customerId, + int? priority, + int? workerId, + int? salesmanId, + String? planStartDate, + String? planEndDate, + int? includeDraft, + }) => _client.get( + '/survey-orders/', + query: { + 'page': page, + 'pageSize': pageSize, + 'keyword': keyword, + 'status': status, + 'customerId': customerId, + 'priority': priority, + 'workerId': workerId, + 'salesmanId': salesmanId, + 'planStartDate': planStartDate, + 'planEndDate': planEndDate, + 'includeDraft': includeDraft, + }, + parse: (d) { + final m = (d as Map).cast(); + return SurveyPage( + list: (m['list'] as List? ?? []) + .map((e) => SurveyItem.fromJson((e as Map).cast())) + .toList(), + total: (m['total'] as num?)?.toInt() ?? 0, + page: (m['page'] as num?)?.toInt() ?? 1, + pageSize: (m['pageSize'] as num?)?.toInt() ?? pageSize, + ); + }, + ); + + Future> detail(int id) => _client.get( + '/survey-orders/$id', + parse: (d) => SurveyItem.fromJson((d as Map).cast()), + ); + + Future> update(int id, Map body) => + _client.put( + '/survey-orders/$id', + body: body, + parse: (d) => SurveyItem.fromJson((d as Map).cast()), + ); + + /// 按 SOP 检查项增量保存现场回执; + /// 仅现场勘察中(status=1)且工单对当前用户可见时后端才放行。 + Future> saveSopResults(int id, List results) => + _client.put( + '/survey-orders/$id/sop-results', + body: {'results': results.map((e) => e.toJson()).toList()}, + parse: (d) => SopSaveResult.fromJson((d as Map).cast()), + ); +} \ No newline at end of file diff --git a/lib/features/survey/data/survey_models.dart b/lib/features/survey/data/survey_models.dart new file mode 100644 index 0000000..5d8eec7 --- /dev/null +++ b/lib/features/survey/data/survey_models.dart @@ -0,0 +1,357 @@ +import 'package:flutter/painting.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/utils/id_util.dart'; + +/// 勘察工单状态:0 待指派 1 现场勘察中 2 待技术复核 3 已归档 4 预留 5 已取消。 +abstract final class SurveyStatus { + static const pendingAssign = 0; + static const surveying = 1; + static const pendingReview = 2; + static const archived = 3; + static const reserved = 4; + static const canceled = 5; +} + +/// 优先级:1 特急 P1 2 加急 P2 3 常规 P3。 +abstract final class SurveyPriority { + static const urgent = 1; + static const expedited = 2; + static const regular = 3; +} + +/// App 端展示用的状态枚举(与 uni-app 版 `SurveyStatusMap` 一一对应)。 +enum SurveyStatusKey { pending, inProgress, review, completed, canceled } + +const surveyStatusMap = { + SurveyStatusKey.pending: (text: '待处理', tone: ChipTone.warn), + SurveyStatusKey.inProgress: (text: '进行中', tone: ChipTone.primary), + SurveyStatusKey.review: (text: '待复核', tone: ChipTone.secondary), + SurveyStatusKey.completed: (text: '已完成', tone: ChipTone.tertiary), + SurveyStatusKey.canceled: (text: '已取消', tone: ChipTone.error), +}; + +/// 数字状态 → App 展示键。 +SurveyStatusKey mapSurveyStatus(int? code) => switch (code) { + SurveyStatus.surveying => SurveyStatusKey.inProgress, + SurveyStatus.pendingReview => SurveyStatusKey.review, + SurveyStatus.archived => SurveyStatusKey.completed, + SurveyStatus.canceled => SurveyStatusKey.canceled, + _ => SurveyStatusKey.pending, +}; + +String surveyStatusText(int? code) => surveyStatusMap[mapSurveyStatus(code)]!.text; + +ChipTone surveyStatusTone(int? code) => surveyStatusMap[mapSurveyStatus(code)]!.tone; + +const surveyPriorityMap = { + 1: (text: '特急 P1', tone: ChipTone.error), + 2: (text: '加急 P2', tone: ChipTone.warn), + 3: (text: '常规 P3', tone: ChipTone.muted), +}; + +String surveyPriorityText(int? p) => surveyPriorityMap[p]?.text ?? '—'; + +ChipTone surveyPriorityTone(int? p) => surveyPriorityMap[p]?.tone ?? ChipTone.muted; + +/// 列表卡片左侧色条颜色。 +Color surveyStatusBarColor(int? status) => switch (status) { + SurveyStatus.pendingAssign => AppColors.statusWarn, + SurveyStatus.surveying => AppColors.primary, + SurveyStatus.pendingReview => AppColors.secondary, + SurveyStatus.archived => AppColors.tertiaryContainer, + SurveyStatus.canceled => AppColors.statusError, + _ => AppColors.borderRule, +}; + +class SurveyCustomer { + const SurveyCustomer({required this.id, required this.customerName, this.city, this.address}); + + final int id; + final String customerName; + final String? city; + final String? address; + + factory SurveyCustomer.fromJson(Map json) => SurveyCustomer( + id: toIntOr(json['id'], 0), + customerName: json['customerName'] as String? ?? '', + city: json['city'] as String?, + address: json['address'] as String?, + ); +} + +class SurveyWorker { + const SurveyWorker({required this.id, required this.workerName, this.phone}); + + final int id; + final String workerName; + final String? phone; + + factory SurveyWorker.fromJson(Map json) => SurveyWorker( + id: toIntOr(json['id'], 0), + workerName: json['workerName'] as String? ?? '', + phone: json['phone'] as String?, + ); +} + +class SurveySopResult { + const SurveySopResult({ + required this.id, + required this.surveyOrderId, + required this.sopItemId, + required this.checked, + required this.itemName, + this.itemDesc = '', + this.receiptType = '', + this.receiptRequire = '', + this.required = false, + this.receiptValue = const [], + this.receiptUrls = const [], + this.remark = '', + }); + + final int id; + final int surveyOrderId; + final int sopItemId; + final bool checked; + final String itemName; + final String itemDesc; + final String receiptType; + final String receiptRequire; + final bool required; + + /// 回执内容:photo/meter 类为照片对象 key 数组,form 类为单元素文本值数组。 + final List receiptValue; + + /// 详情接口附带:照片类回执的预签名访问 URL(与 receiptValue 顺序一致)。 + final List receiptUrls; + final String remark; + + factory SurveySopResult.fromJson(Map json) => SurveySopResult( + id: toIntOr(json['id'], 0), + surveyOrderId: toIntOr(json['surveyOrderId'], 0), + sopItemId: toIntOr(json['sopItemId'], 0), + checked: json['checked'] == true, + itemName: json['itemName'] as String? ?? '', + itemDesc: json['itemDesc'] as String? ?? '', + receiptType: json['receiptType'] as String? ?? '', + receiptRequire: json['receiptRequire'] as String? ?? '', + required: json['required'] == true, + receiptValue: (json['receiptValue'] as List? ?? []).map((e) => e.toString()).toList(), + receiptUrls: (json['receiptUrls'] as List? ?? []).map((e) => e.toString()).toList(), + remark: json['remark'] as String? ?? '', + ); +} + +/// 逐项回执的增量提交体:只传需要变更的 SOP 项,未传项保持原值。 +class SopResultPayload { + const SopResultPayload({required this.sopItemId, this.checked, this.receiptValue, this.remark}); + + final int sopItemId; + final bool? checked; + final List? receiptValue; + final String? remark; + + Map toJson() => { + 'sopItemId': sopItemId, + if (checked != null) 'checked': checked, + if (receiptValue != null) 'receiptValue': receiptValue, + if (remark != null) 'remark': remark, + }; +} + +/// 勘察工单,与后端 `/api/survey-orders` 契约对齐。 +class SurveyItem { + const SurveyItem({ + required this.id, + required this.surveyNo, + required this.customerId, + required this.surveyor, + required this.priority, + required this.taskTitle, + required this.siteLocation, + required this.source, + required this.loopSpec, + required this.progressDone, + required this.drawingCount, + required this.techContact, + required this.slaLevel, + required this.urgeCount, + required this.isDraft, + required this.photos, + required this.reviewRemark, + required this.cancelReason, + required this.remark, + required this.status, + required this.createdAt, + required this.updatedAt, + required this.customerName, + required this.workerName, + required this.salesmanName, + required this.salesmanPhone, + this.workerId, + this.surveyTime, + this.loopCount, + this.progressTotal, + this.salesmanId, + this.planStart, + this.planEnd, + this.expectMinutes, + this.expectArrivalAt, + this.lastUrgedAt, + this.estimatedFee, + this.actualFee, + this.reviewedAt, + this.customer, + this.worker, + this.sopResults, + }); + + final int id; + final String surveyNo; + final int customerId; + final String surveyor; + final int? workerId; + final String? surveyTime; + final int priority; + final String taskTitle; + final String siteLocation; + final String source; + final String loopSpec; + final int? loopCount; + final int progressDone; + final int? progressTotal; + final int drawingCount; + final int? salesmanId; + final String techContact; + final String? planStart; + final String? planEnd; + final int? expectMinutes; + final String? expectArrivalAt; + final String slaLevel; + final int urgeCount; + final String? lastUrgedAt; + final int isDraft; + final num? estimatedFee; + final num? actualFee; + final List photos; + final String reviewRemark; + final String? reviewedAt; + final String cancelReason; + final String remark; + final int status; + final String? createdAt; + final String? updatedAt; + + // decorate 注入的冗余字段 + final SurveyCustomer? customer; + final String customerName; + final SurveyWorker? worker; + final String workerName; + final String salesmanName; + final String salesmanPhone; + + // 仅详情接口返回 + final List? sopResults; + + factory SurveyItem.fromJson(Map json) => SurveyItem( + id: toIntOr(json['id'], 0), + surveyNo: json['surveyNo'] as String? ?? '', + customerId: toIntOr(json['customerId'], 0), + surveyor: json['surveyor'] as String? ?? '', + workerId: toIntOrNull(json['workerId']), + surveyTime: json['surveyTime'] as String?, + priority: toIntOr(json['priority'], 3), + taskTitle: json['taskTitle'] as String? ?? '', + siteLocation: json['siteLocation'] as String? ?? '', + source: json['source'] as String? ?? '', + loopSpec: json['loopSpec'] as String? ?? '', + loopCount: toIntOrNull(json['loopCount']), + progressDone: toIntOr(json['progressDone'], 0), + progressTotal: toIntOrNull(json['progressTotal']), + drawingCount: toIntOr(json['drawingCount'], 0), + salesmanId: toIntOrNull(json['salesmanId']), + techContact: json['techContact'] as String? ?? '', + planStart: json['planStart'] as String?, + planEnd: json['planEnd'] as String?, + expectMinutes: toIntOrNull(json['expectMinutes']), + expectArrivalAt: json['expectArrivalAt'] as String?, + slaLevel: json['slaLevel'] as String? ?? '', + urgeCount: toIntOr(json['urgeCount'], 0), + lastUrgedAt: json['lastUrgedAt'] as String?, + isDraft: toIntOr(json['isDraft'], 0), + estimatedFee: json['estimatedFee'] as num?, + actualFee: json['actualFee'] as num?, + photos: (json['photos'] as List? ?? []).map((e) => e.toString()).toList(), + reviewRemark: json['reviewRemark'] as String? ?? '', + reviewedAt: json['reviewedAt'] as String?, + cancelReason: json['cancelReason'] as String? ?? '', + remark: json['remark'] as String? ?? '', + status: toIntOr(json['status'], 0), + createdAt: json['createdAt'] as String?, + updatedAt: json['updatedAt'] as String?, + customer: json['customer'] == null + ? null + : SurveyCustomer.fromJson((json['customer'] as Map).cast()), + customerName: json['customerName'] as String? ?? '', + worker: json['worker'] == null + ? null + : SurveyWorker.fromJson((json['worker'] as Map).cast()), + workerName: json['workerName'] as String? ?? '', + salesmanName: json['salesmanName'] as String? ?? '', + salesmanPhone: json['salesmanPhone'] as String? ?? '', + sopResults: json['sopResults'] == null + ? null + : (json['sopResults'] as List) + .map((e) => SurveySopResult.fromJson((e as Map).cast())) + .toList(), + ); + + /// 计划时间展示,等价于 `formatSurveyPlanTime`。 + String get planTimeText => formatSurveyPlanTime(planStart, planEnd); + + String get displayTitle => taskTitle.isNotEmpty ? taskTitle : '勘察 #$surveyNo'; + + String get displayCustomer => customerName.isNotEmpty ? customerName : (customer?.customerName ?? '客户 #$customerId'); +} + +class SurveyPage { + const SurveyPage({ + required this.list, + required this.total, + required this.page, + required this.pageSize, + }); + + final List list; + final int total; + final int page; + final int pageSize; +} + +/// 勘察单计划时间展示:`05-12 09:00 - 11:00` / `05-12 09:00 - 05-13 10:00` / `未安排`。 +String formatSurveyPlanTime(String? planStart, String? planEnd) { + if ((planStart == null || planStart.isEmpty) && (planEnd == null || planEnd.isEmpty)) { + return '未安排'; + } + String hm(DateTime dt) => + '${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')} ' + '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}'; + String md(DateTime dt) => + '${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')}'; + + final start = parseSurveyDate(planStart); + final end = parseSurveyDate(planEnd); + if (start != null && end != null) { + final sameDay = + start.year == end.year && start.month == end.month && start.day == end.day; + return sameDay ? '${hm(start)} - ${md(end)}' : '${hm(start)} - ${hm(end)}'; + } + final only = start ?? end; + return only == null ? (planStart ?? planEnd ?? '未安排') : hm(only); +} + +DateTime? parseSurveyDate(String? raw) { + if (raw == null || raw.isEmpty) return null; + return DateTime.tryParse(raw); +} \ No newline at end of file diff --git a/lib/features/survey/presentation/survey_form_page.dart b/lib/features/survey/presentation/survey_form_page.dart new file mode 100644 index 0000000..665388d --- /dev/null +++ b/lib/features/survey/presentation/survey_form_page.dart @@ -0,0 +1,1285 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:image_picker/image_picker.dart'; + +import '../../../core/network/api_response.dart'; +import '../../../core/providers.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../data/survey_api.dart'; +import '../data/survey_models.dart'; + +const _monoFallback = ['JetBrains Mono', 'SF Mono', 'Menlo', 'Consolas']; + +/// 现场勘测(勘察单编辑 + SOP 逐项回执),对应 `pages/survey/form.vue`。 +class SurveyFormPage extends ConsumerStatefulWidget { + const SurveyFormPage({super.key, this.id, this.customerId}); + + final int? id; + final int? customerId; + + @override + ConsumerState createState() => _SurveyFormPageState(); +} + +class _SurveyFormPageState extends ConsumerState { + final _mainPanelLocation = TextEditingController(); + final _loadCapacity = TextEditingController(); + final _observation = TextEditingController(); + + final List<_PhotoSlot> _photoSlots = [ + _PhotoSlot('主面板'), + _PhotoSlot('电表读数'), + _PhotoSlot('环境'), + _PhotoSlot('缺陷(如有)'), + ]; + + SurveyItem? _survey; + int _surveyId = 0; + bool _submitting = false; + String _busyText = ''; + + List<_SopRow> _sopRows = const []; + final List> _strokes = []; + List? _drawing; + + bool get _busy => _busyText.isNotEmpty; + + /// 回执仅「现场勘察中」可录入,其余状态只读展示(与 Web 端 isReadonly 判定一致)。 + bool get _canEditReceipt => _survey?.status == SurveyStatus.surveying; + + int get _sopDoneCount => _sopRows.where((r) => r.checked).length; + + List get _sopMissingRequired => _sopRows + .where((r) => r.required && !r.checked) + .map((r) => r.itemName) + .toList(); + + bool get _hasSignature => _strokes.isNotEmpty || _drawing != null; + + @override + void initState() { + super.initState(); + _surveyId = widget.id ?? 0; + if (_surveyId == 0) { + WidgetsBinding.instance.addPostFrameCallback( + (_) => showAppToast('缺少勘察单 ID'), + ); + return; + } + _loadDetail(); + } + + @override + void dispose() { + _mainPanelLocation.dispose(); + _loadCapacity.dispose(); + _observation.dispose(); + for (final row in _sopRows) { + row.dispose(); + } + super.dispose(); + } + + // ===== 数据 ===== + + Future _loadDetail() async { + try { + final res = await ref.read(surveyApiProvider).detail(_surveyId); + if (!mounted) return; + if (res.isOk && res.data != null) { + final data = res.data!; + setState(() { + _survey = data; + _sopRows = (data.sopResults ?? const []) + .map(_buildSopRow) + .toList(); + }); + } else { + showAppToast(res.message.isEmpty ? '加载勘察单失败' : res.message); + } + } catch (e) { + if (mounted) showAppToast(e is ApiException ? e.message : '加载勘察单失败'); + } + } + + _SopRow _buildSopRow(SurveySopResult result) { + final keys = List.from(result.receiptValue); + final row = _SopRow( + sopItemId: result.sopItemId, + itemName: result.itemName.isEmpty ? '检查项 #${result.sopItemId}' : result.itemName, + itemDesc: result.itemDesc, + receiptType: result.receiptType.isEmpty ? 'photo' : result.receiptType, + receiptRequire: result.receiptRequire, + required: result.required, + checked: result.checked, + keys: keys, + urls: List.from(result.receiptUrls), + text: result.receiptType == 'form' ? (keys.isEmpty ? '' : keys.first) : '', + remark: result.remark, + ); + row.snap = _rowSnapshot(row); + return row; + } + + List _rowReceiptValue(_SopRow row) { + if (row.receiptType != 'form') return row.keys; + final text = row.textController.text; + return text.isEmpty ? const [] : [text]; + } + + String _rowSnapshot(_SopRow row) => + jsonEncode({'v': _rowReceiptValue(row), 'r': row.remarkController.text}); + + /// 增量保存单项回执:只提交当前项,未传项后端保持原值。 + Future _saveSopItem(_SopRow row) async { + if (!_canEditReceipt || row.saving) return; + final snap = _rowSnapshot(row); + if (snap == row.snap) return; + final receiptValue = _rowReceiptValue(row); + final checked = receiptValue.isNotEmpty; + setState(() => row.saving = true); + try { + final res = await ref.read(surveyApiProvider).saveSopResults(_surveyId, [ + SopResultPayload( + sopItemId: row.sopItemId, + checked: checked, + receiptValue: receiptValue, + remark: row.remarkController.text, + ), + ]); + if (!mounted) return; + if (res.isOk) { + setState(() { + row.snap = snap; + row.checked = checked; + }); + } else { + showAppToast(res.message.isEmpty ? '回执保存失败' : res.message); + } + } catch (e) { + if (mounted) showAppToast(e is ApiException ? e.message : '回执保存失败'); + } finally { + if (mounted) setState(() => row.saving = false); + } + } + + /// 选中即上传即保存,电工中途退出不丢已传内容。 + Future _addSopPhotos(_SopRow row) async { + if (!_canEditReceipt) return; + final picked = await ImagePicker().pickMultiImage(); + if (picked.isEmpty || !mounted) return; + setState(() => _busyText = '上传中...'); + var failed = 0; + final client = ref.read(apiClientProvider); + for (final image in picked) { + try { + final result = await client.uploadImage(image.path); + row.keys.add(result.key); + row.urls.add(result.url.isEmpty ? image.path : result.url); + } catch (_) { + failed++; + } + } + if (!mounted) return; + setState(() => _busyText = ''); + if (row.keys.isNotEmpty) await _saveSopItem(row); + if (failed > 0) showAppToast('$failed 张上传失败'); + } + + void _removeSopPhoto(_SopRow row, int index) { + if (!_canEditReceipt) return; + setState(() { + if (index < row.keys.length) row.keys.removeAt(index); + if (index < row.urls.length) row.urls.removeAt(index); + }); + _saveSopItem(row); + } + + void _previewSopPhotos(_SopRow row, int index) { + if (row.urls.isEmpty || index >= row.urls.length) return; + final url = row.urls[index]; + showDialog( + context: context, + barrierColor: const Color(0xEB000000), + builder: (ctx) => GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => Navigator.of(ctx).pop(), + child: SizedBox.expand(child: _buildImage(url, fit: BoxFit.contain)), + ), + ); + } + + // ===== 照片证据(工单级) ===== + + Future _pickPhoto(int index) async { + final picked = await ImagePicker().pickImage(source: ImageSource.gallery); + if (picked == null || !mounted) return; + setState(() => _photoSlots[index].src = picked.path); + } + + Widget _buildImage(String src, {BoxFit fit = BoxFit.cover}) { + if (src.startsWith('http')) { + return Image.network( + src, + fit: fit, + errorBuilder: (context, error, stackTrace) => const SizedBox.shrink(), + ); + } + return Image.file( + File(src), + fit: fit, + errorBuilder: (context, error, stackTrace) => const SizedBox.shrink(), + ); + } + + // ===== 签名 ===== + + void _clearSignature() { + setState(() { + _strokes.clear(); + _drawing = null; + }); + } + + // ===== 提交 ===== + + /// 把表单字段拼装成 remark 文本。 + String _buildRemark() { + final parts = []; + if (_mainPanelLocation.text.isNotEmpty) { + parts.add('主配电箱位置: ${_mainPanelLocation.text}'); + } + if (_loadCapacity.text.isNotEmpty) { + parts.add('当前负载容量: ${_loadCapacity.text} kVA'); + } + if (_observation.text.isNotEmpty) { + parts.add('初步观察: ${_observation.text}'); + } + return parts.join('; '); + } + + /// 上传所有已选照片,返回 key 数组(失败的阻断提交)。 + Future> _uploadPhotos() async { + final keys = []; + final client = ref.read(apiClientProvider); + for (final slot in _photoSlots) { + final src = slot.src; + if (src == null || src.isEmpty) continue; + try { + final result = await client.uploadImage(src); + if (result.key.isNotEmpty) keys.add(result.key); + } catch (e) { + final reason = e is ApiException ? e.message : '网络异常'; + throw ApiException('照片「${slot.label}」上传失败: $reason'); + } + } + return keys; + } + + Future _onSubmit() async { + if (_submitting) return; + if (_surveyId == 0 || _survey == null) { + showAppToast('勘察单未加载'); + return; + } + // 至少填一项技术发现或一张照片 + final hasForm = _mainPanelLocation.text.isNotEmpty || + _loadCapacity.text.isNotEmpty || + _observation.text.isNotEmpty; + final hasPhotos = _photoSlots.any((s) => (s.src ?? '').isNotEmpty); + if (!hasForm && !hasPhotos) { + showAppToast('请填写技术发现或上传照片'); + return; + } + final confirmed = await showAppConfirm( + title: '提交勘测报告', + content: '确认提交本次现场勘测报告?', + ); + if (!confirmed || !mounted) return; + + _submitting = true; + setState(() => _busyText = '提交中...'); + try { + final remark = _buildRemark(); + final photos = await _uploadPhotos(); + final payload = {}; + if (remark.isNotEmpty) payload['remark'] = remark; + if (photos.isNotEmpty) payload['photos'] = photos; + // 没有任何可提交内容时给个提示(理论上前面已挡,这里兜底) + if (payload.isEmpty) { + setState(() { + _busyText = ''; + _submitting = false; + }); + showAppToast('无内容可提交'); + return; + } + final res = await ref.read(surveyApiProvider).update(_surveyId, payload); + if (!mounted) return; + setState(() { + _busyText = ''; + _submitting = false; + }); + if (res.isOk) { + showAppToast('提交成功', success: true); + await Future.delayed(const Duration(milliseconds: 600)); + if (mounted) context.pop(); + } else { + showAppToast(res.message.isEmpty ? '提交失败' : res.message); + } + } catch (e) { + if (!mounted) return; + setState(() { + _busyText = ''; + _submitting = false; + }); + showAppToast(e is ApiException ? e.message : '提交失败'); + } + } + + // ===== 视图 ===== + + @override + Widget build(BuildContext context) { + final survey = _survey; + return XPageShell( + topBar: XTopBar.nav(title: '现场勘测', onBack: () => context.pop()), + child: Stack( + children: [ + AbsorbPointer( + absorbing: _busy, + child: ListView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 60), + children: [ + if (survey != null) _buildTaskCard(survey), + _buildTechSection(), + _buildPhotoSection(), + if (_sopRows.isNotEmpty) _buildSopSection(), + _buildSignSection(), + _buildSubmitButton(), + ], + ), + ), + if (_busy) _buildBusyOverlay(), + ], + ), + ); + } + + Widget _buildTaskCard(SurveyItem survey) { + return XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + margin: const EdgeInsets.only(bottom: 20), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.only(right: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${survey.customerName.isEmpty ? '未知客户' : survey.customerName}的勘测', + style: AppTypography.titleSm.copyWith( + color: AppColors.onSurface, + ), + ), + const SizedBox(height: 4), + Text( + '任务ID:${survey.surveyNo}', + style: AppTypography.dataMono.copyWith( + color: AppColors.textMuted, + ), + ), + ], + ), + ), + ), + XChip( + surveyStatusText(survey.status), + tone: surveyStatusTone(survey.status), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.only(bottom: 14), + child: Column( + children: [ + _buildTaskLine( + 'location', + AppColors.primary, + survey.siteLocation.isEmpty ? '地点未填' : survey.siteLocation, + ), + const SizedBox(height: 10), + _buildTaskLine( + 'schedule', + AppColors.statusWarn, + '计划时间:${survey.planTimeText}', + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildTaskLine(String icon, Color color, String text) { + return Row( + children: [ + XIcon(icon, size: 18, color: color), + const SizedBox(width: 10), + Expanded( + child: Text( + text, + style: const TextStyle( + fontSize: 14, + color: AppColors.onSurfaceVariant, + ), + ), + ), + ], + ); + } + + Widget _buildTechSection() { + return Padding( + padding: const EdgeInsets.only(bottom: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle('edit', AppColors.secondary, '技术发现'), + XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + margin: const EdgeInsets.only(top: 12), + child: Column( + children: [ + _buildField( + label: '主配电箱位置', + input: _buildInput( + controller: _mainPanelLocation, + hint: '例如:地下室西北角', + ), + ), + _buildField( + label: '当前负载容量 (kVA)', + divider: true, + input: _buildInput( + controller: _loadCapacity, + hint: '输入数值', + mono: true, + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + ), + ), + ), + _buildField( + label: '初步观察', + divider: true, + input: _buildTextarea( + controller: _observation, + hint: '记录任何可见的损坏、非标准接线或通行障碍...', + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildField({ + required String label, + required Widget input, + bool divider = false, + }) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 13), + decoration: divider + ? const BoxDecoration( + border: Border(top: BorderSide(color: AppColors.borderRule)), + ) + : null, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: AppTypography.labelBold.copyWith( + color: AppColors.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + input, + ], + ), + ); + } + + Widget _buildInput({ + required TextEditingController controller, + required String hint, + bool enabled = true, + bool mono = false, + double height = 44, + TextInputType? keyboardType, + VoidCallback? onEditDone, + }) { + return Container( + height: height, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + Expanded( + child: TextField( + controller: controller, + enabled: enabled, + keyboardType: keyboardType, + style: TextStyle( + fontSize: 15, + color: AppColors.onSurface, + fontFamilyFallback: mono ? _monoFallback : null, + ), + cursorColor: AppColors.primary, + onEditingComplete: () { + onEditDone?.call(); + FocusScope.of(context).unfocus(); + }, + onTapOutside: (_) { + onEditDone?.call(); + FocusScope.of(context).unfocus(); + }, + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + hintText: hint, + hintStyle: const TextStyle( + fontSize: 15, + color: AppColors.textPlaceholder, + ), + ), + ), + ), + ], + ), + ); + } + + Widget _buildTextarea({ + required TextEditingController controller, + required String hint, + bool enabled = true, + VoidCallback? onEditDone, + }) { + return Container( + height: 96, + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: TextField( + controller: controller, + enabled: enabled, + maxLines: null, + expands: true, + textAlignVertical: TextAlignVertical.top, + style: const TextStyle(fontSize: 15, color: AppColors.onSurface), + cursorColor: AppColors.primary, + onEditingComplete: () { + onEditDone?.call(); + FocusScope.of(context).unfocus(); + }, + onTapOutside: (_) { + onEditDone?.call(); + FocusScope.of(context).unfocus(); + }, + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + hintText: hint, + hintStyle: const TextStyle( + fontSize: 15, + color: AppColors.textPlaceholder, + ), + ), + ), + ); + } + + Widget _buildSectionTitle(String icon, Color iconColor, String text) { + return Row( + children: [ + XIcon(icon, size: 18, color: iconColor), + const SizedBox(width: 4), + Text(text, style: AppTypography.titleSm.copyWith(color: AppColors.onSurface)), + ], + ); + } + + Widget _buildPhotoSection() { + return Padding( + padding: const EdgeInsets.only(bottom: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _buildSectionTitle('camera', AppColors.primary, '照片证据'), + const Text( + '需要:4', + style: TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ], + ), + Padding( + padding: const EdgeInsets.only(top: 12), + child: LayoutBuilder( + builder: (context, constraints) => Wrap( + spacing: 12, + runSpacing: 12, + children: [ + for (var i = 0; i < _photoSlots.length; i++) + _buildPhotoSlot(i, _photoSlots[i], (constraints.maxWidth - 12) / 2), + ], + ), + ), + ), + const Padding( + padding: EdgeInsets.only(top: 8), + child: Row( + children: [ + XIcon('schedule', size: 14, color: AppColors.outline), + SizedBox(width: 6), + Text( + '照片将自动添加GPS坐标和时间戳水印', + style: TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildPhotoSlot(int index, _PhotoSlot slot, double width) { + final src = slot.src; + final filled = src != null && src.isNotEmpty; + return GestureDetector( + onTap: () => _pickPhoto(index), + child: Container( + width: width, + height: 128, + padding: const EdgeInsets.all(2), + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + color: AppColors.surface, + border: Border.all( + color: filled ? AppColors.primary : AppColors.outlineVariant, + width: 2, + ), + borderRadius: BorderRadius.circular(12), + ), + child: Stack( + children: [ + if (filled) + Positioned.fill(child: _buildImage(src)) + else + Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const XIcon('camera', size: 30, color: AppColors.outline), + const SizedBox(height: 6), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Text( + slot.label, + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + ), + ], + ), + ), + if (filled) + Positioned( + left: 0, + right: 0, + bottom: 0, + child: Container( + color: const Color(0x80000000), + padding: const EdgeInsets.symmetric(vertical: 3), + child: Text( + slot.label, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 11, color: Colors.white), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _buildSopSection() { + return Padding( + padding: const EdgeInsets.only(bottom: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _buildSectionTitle('edit', AppColors.secondary, '勘察回执标准'), + Text( + '$_sopDoneCount/${_sopRows.length} 项已回执', + style: const TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ], + ), + if (_canEditReceipt && _sopMissingRequired.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Row( + children: [ + const XIcon('schedule', size: 14, color: AppColors.statusWarn), + const SizedBox(width: 6), + Expanded( + child: Text( + '还有 ${_sopMissingRequired.length} 项必填回执未完成:' + '${_sopMissingRequired.join('、')}', + style: const TextStyle( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + ), + ], + ), + ), + for (final row in _sopRows) _buildSopCard(row), + ], + ), + ); + } + + Widget _buildSopCard(_SopRow row) { + final isForm = row.receiptType == 'form'; + return XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + margin: const EdgeInsets.only(top: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + row.itemName, + style: AppTypography.bodyMd.copyWith( + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + ), + const SizedBox(width: 8), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (row.required) + _buildSopTag('必填', const Color(0xFFC0392B), const Color(0x1AC0392B)), + if (row.required && row.checked) const SizedBox(width: 6), + if (row.checked) + _buildSopTag( + '已回执', + AppColors.tertiaryContainer, + const Color(0x1A008378), + ), + ], + ), + ], + ), + if (row.itemDesc.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text( + row.itemDesc, + style: const TextStyle( + fontSize: 13, + color: AppColors.onSurfaceVariant, + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + _receiptTypeLabel(row.receiptType), + style: const TextStyle(fontSize: 12, color: AppColors.primary), + ), + Text( + row.receiptRequire.isEmpty ? '—' : row.receiptRequire, + style: const TextStyle(fontSize: 12, color: AppColors.primary), + ), + ], + ), + ), + ), + if (isForm) + Padding( + padding: const EdgeInsets.only(top: 10), + child: _buildTextarea( + controller: row.textController, + hint: '按清单格式填写回执内容', + enabled: _canEditReceipt, + onEditDone: () => _saveSopItem(row), + ), + ) + else + Padding( + padding: const EdgeInsets.only(top: 10), + child: Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (var i = 0; i < row.urls.length; i++) + _buildSopPhoto(row, i), + if (_canEditReceipt) _buildSopPhotoAdd(row), + ], + ), + ), + if (_canEditReceipt) + Padding( + padding: const EdgeInsets.only(top: 10), + child: _buildInput( + controller: row.remarkController, + hint: '备注(选填)', + height: 40, + onEditDone: () => _saveSopItem(row), + ), + ) + else if (row.remarkController.text.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + '备注:${row.remarkController.text}', + style: const TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ), + if (row.saving) + const Padding( + padding: EdgeInsets.only(top: 6), + child: Text( + '保存中...', + style: TextStyle(fontSize: 11, color: AppColors.textMuted), + ), + ), + ], + ), + ); + } + + Widget _buildSopTag(String text, Color foreground, Color background) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(4), + ), + child: Text(text, style: TextStyle(fontSize: 11, color: foreground)), + ); + } + + Widget _buildSopPhoto(_SopRow row, int index) { + return SizedBox( + width: 84, + height: 84, + child: Stack( + children: [ + Positioned.fill( + child: GestureDetector( + onTap: () => _previewSopPhotos(row, index), + child: ClipRRect( + borderRadius: BorderRadius.circular(10), + child: _buildImage(row.urls[index]), + ), + ), + ), + if (_canEditReceipt) + Positioned( + right: 2, + top: 2, + child: GestureDetector( + onTap: () => _removeSopPhoto(row, index), + child: Container( + width: 18, + height: 18, + alignment: Alignment.center, + decoration: const BoxDecoration( + color: Color(0x8C000000), + shape: BoxShape.circle, + ), + child: const XIcon('delete', size: 12, color: Colors.white), + ), + ), + ), + ], + ), + ); + } + + Widget _buildSopPhotoAdd(_SopRow row) { + return GestureDetector( + onTap: () => _addSopPhotos(row), + child: Container( + width: 84, + height: 84, + decoration: BoxDecoration( + color: AppColors.surface, + border: Border.all(color: AppColors.outlineVariant, width: 2), + borderRadius: BorderRadius.circular(10), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const XIcon('camera', size: 24, color: AppColors.outline), + const SizedBox(height: 2), + const Text( + '添加', + style: TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ], + ), + ), + ); + } + + Widget _buildSignSection() { + return Padding( + padding: const EdgeInsets.only(bottom: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle('edit', AppColors.tertiaryContainer, '现场确认'), + XCard( + padding: const EdgeInsets.all(16), + margin: const EdgeInsets.only(top: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + '我确认已进行上述勘测,且据我所知提供的信息准确无误。', + style: TextStyle( + fontSize: 12, + color: AppColors.onSurfaceVariant, + ), + ), + const SizedBox(height: 14), + _buildSignPad(), + const SizedBox(height: 10), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: _clearSignature, + child: const Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + XIcon('delete', size: 14, color: AppColors.onSurfaceVariant), + SizedBox(width: 4), + Text( + '清除签名', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: AppColors.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildSignPad() { + final width = math.min(700.0, MediaQuery.sizeOf(context).width - 80); + return Container( + height: 150, + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.outlineVariant, width: 2), + borderRadius: BorderRadius.circular(10), + ), + child: Stack( + children: [ + Positioned( + left: 0, + top: 0, + child: SizedBox( + width: width, + height: 150, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onPanStart: (details) => + setState(() => _drawing = [details.localPosition]), + onPanUpdate: (details) => + setState(() => _drawing?.add(details.localPosition)), + onPanEnd: (_) { + final stroke = _drawing; + setState(() { + if (stroke != null && stroke.isNotEmpty) { + _strokes.add(List.of(stroke)); + } + _drawing = null; + }); + }, + child: CustomPaint( + size: Size(width, 150), + painter: _SignaturePainter(strokes: _strokes, current: _drawing), + ), + ), + ), + ), + if (!_hasSignature) + const Center( + child: Text( + '在此签名', + style: TextStyle(fontSize: 14, color: AppColors.outline), + ), + ), + ], + ), + ); + } + + Widget _buildSubmitButton() { + return Padding( + padding: const EdgeInsets.only(top: 8, bottom: 40), + child: Container( + height: 48, + decoration: BoxDecoration( + color: AppColors.primary, + borderRadius: BorderRadius.circular(999), + boxShadow: const [ + BoxShadow( + color: Color(0x4D0054CD), + blurRadius: 16, + offset: Offset(0, 6), + ), + ], + ), + child: Material( + color: Colors.transparent, + borderRadius: BorderRadius.circular(999), + child: InkWell( + onTap: _submitting ? null : _onSubmit, + borderRadius: BorderRadius.circular(999), + child: const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + XIcon('send', size: 18, color: Colors.white), + SizedBox(width: 6), + Text( + '提交勘测报告', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _buildBusyOverlay() { + return Positioned.fill( + child: AbsorbPointer( + child: ColoredBox( + color: const Color(0x33000000), + child: Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + decoration: BoxDecoration( + color: AppColors.surface, + borderRadius: BorderRadius.circular(AppRadius.lg), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2, + color: AppColors.primary, + ), + ), + const SizedBox(height: 10), + Text( + _busyText, + style: const TextStyle( + fontSize: 13, + color: AppColors.onSurfaceVariant, + ), + ), + ], + ), + ), + ), + ), + ), + ); + } + + String _receiptTypeLabel(String type) { + if (type.isEmpty) return '—'; + return const { + 'photo': '现场照片', + 'form': '清单格式', + 'meter': '手持测仪', + }[type] ?? + type; + } +} + +/// 工单级照片槽位(标签 + 本地临时路径)。 +class _PhotoSlot { + _PhotoSlot(this.label); + + final String label; + String? src; +} + +/// SOP 逐项回执行。 +class _SopRow { + _SopRow({ + required this.sopItemId, + required this.itemName, + required this.itemDesc, + required this.receiptType, + required this.receiptRequire, + required this.required, + required this.checked, + required this.keys, + required this.urls, + String text = '', + String remark = '', + }) : textController = TextEditingController(text: text), + remarkController = TextEditingController(text: remark); + + final int sopItemId; + final String itemName; + final String itemDesc; + final String receiptType; + final String receiptRequire; + final bool required; + bool checked; + + /// 已上传照片的对象 key(form 类不用) + final List keys; + + /// 与 keys 顺序一致的预览地址(后端预签名 URL 或刚上传的临时地址) + final List urls; + + /// form 类的表单文本值,photo/meter 类为备注 + final TextEditingController textController; + final TextEditingController remarkController; + + bool saving = false; + + /// 最近一次保存成功的快照,用于避免 blur 触发的无变化请求 + String snap = ''; + + void dispose() { + textController.dispose(); + remarkController.dispose(); + } +} + +/// 手写签名笔迹绘制,对应源页面 canvas 的 `#0054cd` / 3px / round 笔触。 +class _SignaturePainter extends CustomPainter { + const _SignaturePainter({required this.strokes, this.current}); + + final List> strokes; + final List? current; + + @override + void paint(Canvas canvas, Size size) { + final stroke = Paint() + ..color = AppColors.primary + ..strokeWidth = 3 + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + final dot = Paint() + ..color = AppColors.primary + ..style = PaintingStyle.fill; + + for (final points in [...strokes, ?current]) { + if (points.isEmpty) continue; + if (points.length == 1) { + canvas.drawCircle(points.first, 1.5, dot); + continue; + } + final path = Path()..moveTo(points.first.dx, points.first.dy); + for (var i = 1; i < points.length; i++) { + path.lineTo(points[i].dx, points[i].dy); + } + canvas.drawPath(path, stroke); + } + } + + @override + bool shouldRepaint(covariant _SignaturePainter oldDelegate) => true; +} \ No newline at end of file diff --git a/lib/features/survey/presentation/survey_list_page.dart b/lib/features/survey/presentation/survey_list_page.dart new file mode 100644 index 0000000..c318bc8 --- /dev/null +++ b/lib/features/survey/presentation/survey_list_page.dart @@ -0,0 +1,165 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../data/survey_api.dart'; +import '../data/survey_models.dart'; + +/// 勘测任务列表,对应 `pages/survey/list.vue`。 +class SurveyListPage extends ConsumerStatefulWidget { + const SurveyListPage({super.key}); + + @override + ConsumerState createState() => _SurveyListPageState(); +} + +class _SurveyListPageState extends ConsumerState { + List _list = const []; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + final res = await ref.read(surveyApiProvider).list(pageSize: 100); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() => _list = res.data!.list); + } + } catch (_) { + if (mounted) showAppToast('加载失败'); + } + } + + Future _goForm(SurveyItem item) async { + await context.push('/survey/form?id=${item.id}'); + if (mounted) _load(); + } + + @override + Widget build(BuildContext context) { + return XPageShell( + topBar: XTopBar.brand(title: '勘测任务'), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 8, 16, 4), + child: Text( + '管理您的现场勘测与检查任务', + style: TextStyle(fontSize: 14, color: AppColors.textMuted), + ), + ), + Expanded(child: _buildContent()), + ], + ), + ); + } + + Widget _buildContent() { + if (_list.isEmpty) { + return ListView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), + children: const [XPlaceholder(text: '暂无勘测任务')], + ); + } + return ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), + itemCount: _list.length, + itemBuilder: (context, index) => _buildCard(_list[index]), + ); + } + + Widget _buildCard(SurveyItem item) { + return XCard( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + onTap: () => _goForm(item), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.only(right: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${item.customerName.isEmpty ? '未知客户' : item.customerName}的勘测', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + const SizedBox(height: 4), + Text( + '任务ID:${item.surveyNo}', + style: AppTypography.dataMono.copyWith( + color: AppColors.textMuted, + ), + ), + ], + ), + ), + ), + XChip( + surveyStatusText(item.status), + tone: surveyStatusTone(item.status), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(0, 8, 0, 14), + child: Column( + children: [ + _buildLine( + 'location', + AppColors.primary, + item.siteLocation.isEmpty ? '地点未填' : item.siteLocation, + ), + const SizedBox(height: 10), + _buildLine( + 'schedule', + AppColors.statusWarn, + '计划时间:${item.planTimeText}', + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildLine(String icon, Color color, String text) { + return Row( + children: [ + XIcon(icon, size: 18, color: color), + const SizedBox(width: 10), + Expanded( + child: Text( + text, + style: const TextStyle(fontSize: 14, color: AppColors.onSurfaceVariant), + ), + ), + ], + ); + } +} \ No newline at end of file diff --git a/lib/features/visit/data/visit_api.dart b/lib/features/visit/data/visit_api.dart new file mode 100644 index 0000000..ce80399 --- /dev/null +++ b/lib/features/visit/data/visit_api.dart @@ -0,0 +1,105 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/network/api_client.dart'; +import '../../../core/network/api_response.dart'; +import '../../../core/providers.dart'; +import 'visit_models.dart'; + +final visitApiProvider = Provider( + (ref) => VisitApi(ref.watch(apiClientProvider)), +); + +/// 拜访台账接口,对应 uni-app 版 `api/customerVisit.ts`。 +class VisitApi { + VisitApi(this._client); + + final ApiClient _client; + + Future> list({ + int page = 1, + int pageSize = 100, + String? keyword, + int? customerId, + int? salesmanId, + int? visitType, + int? status, + int? priority, + String? planStartDate, + String? planEndDate, + }) => _client.get( + '/customer-visits', + query: { + 'page': page, + 'pageSize': pageSize, + 'keyword': keyword, + 'customerId': customerId, + 'salesmanId': salesmanId, + 'visitType': visitType, + 'status': status, + 'priority': priority, + 'planStartDate': planStartDate, + 'planEndDate': planEndDate, + }, + parse: (d) { + final m = (d as Map).cast(); + return VisitPage( + list: (m['list'] as List? ?? []) + .map((e) => VisitInfo.fromJson((e as Map).cast())) + .toList(), + total: (m['total'] as num?)?.toInt() ?? 0, + page: (m['page'] as num?)?.toInt() ?? 1, + pageSize: (m['pageSize'] as num?)?.toInt() ?? pageSize, + ); + }, + ); + + Future> stats() => _client.get( + '/customer-visits/stats', + parse: (d) => VisitStats.fromJson((d as Map).cast()), + ); + + Future> detail(int id) => _client.get( + '/customer-visits/$id', + parse: (d) => VisitInfo.fromJson((d as Map).cast()), + ); + + Future> create(Map body) => + _client.post( + '/customer-visits', + body: body, + parse: (d) => VisitInfo.fromJson((d as Map).cast()), + ); + + /// 批量安排拜访:多选客户生成统一的待执行计划。 + Future> batchCreate(Map body) => + _client.post( + '/customer-visits/batch', + body: body, + parse: (d) => VisitBatchResult.fromJson((d as Map).cast()), + ); + + Future> update(int id, Map body) => + _client.put( + '/customer-visits/$id', + body: body, + parse: (d) => VisitInfo.fromJson((d as Map).cast()), + ); + + /// 状态流转:待执行 → 已完成 / 取消 等。 + Future> updateStatus(int id, Map body) => + _client.put( + '/customer-visits/$id/status', + body: body, + parse: (d) => VisitInfo.fromJson((d as Map).cast()), + ); + + /// 改派:更换跟进业务员(仅 ADMIN)。 + Future> reassign(int id, Map body) => + _client.put( + '/customer-visits/$id/reassign', + body: body, + parse: (d) => VisitInfo.fromJson((d as Map).cast()), + ); + + Future> delete(int id) => _client.delete('/customer-visits/$id'); +} \ No newline at end of file diff --git a/lib/features/visit/data/visit_models.dart b/lib/features/visit/data/visit_models.dart new file mode 100644 index 0000000..efec3c5 --- /dev/null +++ b/lib/features/visit/data/visit_models.dart @@ -0,0 +1,342 @@ +import 'package:flutter/painting.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/utils/id_util.dart'; + +/// 数值下拉选项。 +typedef ValueOption = ({int value, String label}); + +/// 拜访类型:1 首访摸排 2 方案沟通 3 商务二访 4 维保回访 5 应急巡检 +const visitTypeOptions = [ + (value: 1, label: '首访摸排'), + (value: 2, label: '方案沟通'), + (value: 3, label: '商务二访'), + (value: 4, label: '维保回访'), + (value: 5, label: '应急巡检'), +]; + +/// 拜访方式:1 现场拜访 2 商务拜访 3 电话沟通 4 线上会议 +const visitModeOptions = [ + (value: 1, label: '现场拜访'), + (value: 2, label: '商务拜访'), + (value: 3, label: '电话沟通'), + (value: 4, label: '线上会议'), +]; + +/// 优先级:1 特急 P1 2 加急 P2 3 常规 P3 +const visitPriorityOptions = [ + (value: 1, label: '特急 · P1'), + (value: 2, label: '加急 · P2'), + (value: 3, label: '常规 · P3'), +]; + +/// 意向评级:1=A 高意向 2=B 中意向 3=C 低意向 +const visitIntentOptions = [ + (value: 1, label: 'A级 · 高意向'), + (value: 2, label: 'B级 · 中意向'), + (value: 3, label: 'C级 · 低意向'), +]; + +/// 状态:0 待执行 1 已完成待复核 2 取证待技术复核 3 已立项转勘察 4 已归档 5 已取消 +const visitStatusOptions = [ + (value: 0, label: '待执行'), + (value: 1, label: '已完成待复核'), + (value: 2, label: '取证待技术复核'), + (value: 3, label: '已立项转勘察'), + (value: 4, label: '已归档'), + (value: 5, label: '已取消'), +]; + +abstract final class VisitStatus { + static const pending = 0; + static const done = 1; + static const evidence = 2; + static const survey = 3; + static const archived = 4; + static const canceled = 5; +} + +const visitStatusMap = { + 0: (text: '待执行', tone: ChipTone.warn), + 1: (text: '已完成待复核', tone: ChipTone.primary), + 2: (text: '取证待技术复核', tone: ChipTone.secondary), + 3: (text: '已立项转勘察', tone: ChipTone.secondary), + 4: (text: '已归档', tone: ChipTone.tertiary), + 5: (text: '已取消', tone: ChipTone.error), +}; + +const visitPriorityMap = { + 1: (text: '特急 P1', tone: ChipTone.error), + 2: (text: '加急 P2', tone: ChipTone.warn), + 3: (text: '常规 P3', tone: ChipTone.muted), +}; + +String visitStatusText(int? s) => visitStatusMap[s]?.text ?? '未知'; + +ChipTone visitStatusTone(int? s) => visitStatusMap[s]?.tone ?? ChipTone.muted; + +String visitPriorityText(int? p) => visitPriorityMap[p]?.text ?? '—'; + +ChipTone visitPriorityTone(int? p) => visitPriorityMap[p]?.tone ?? ChipTone.muted; + +String optionLabel(List options, int? value) => + options.where((o) => o.value == value).map((o) => o.label).firstOrNull ?? '—'; + +/// 列表卡片左侧色条颜色。 +Color visitStatusBarColor(int status) => switch (status) { + 0 => AppColors.statusWarn, + 1 => AppColors.primary, + 2 || 3 => AppColors.secondary, + 4 => AppColors.tertiaryContainer, + 5 => AppColors.statusError, + _ => AppColors.borderRule, +}; + +/// 关联客户(列表/详情 include 的精简字段)。 +class VisitCustomer { + const VisitCustomer({ + required this.id, + this.customerNo, + this.customerName, + this.customerLevel, + this.contactPerson, + this.contactPhone, + this.address, + this.salesmanId, + }); + + final int id; + final String? customerNo; + final String? customerName; + final String? customerLevel; + final String? contactPerson; + final String? contactPhone; + final String? address; + final int? salesmanId; + + factory VisitCustomer.fromJson(Map json) => VisitCustomer( + id: toIntOr(json['id'], 0), + customerNo: json['customerNo'] as String?, + customerName: json['customerName'] as String?, + customerLevel: json['customerLevel'] as String?, + contactPerson: json['contactPerson'] as String?, + contactPhone: json['contactPhone'] as String?, + address: json['address'] as String?, + salesmanId: toIntOrNull(json['salesmanId']), + ); +} + +/// 拜访台账,与后端 `/api/customer-visits` 契约对齐。 +class VisitInfo { + const VisitInfo({ + required this.id, + required this.visitNo, + required this.customerId, + required this.visitPerson, + required this.status, + this.visitPhone, + this.visitContent, + this.visitTime, + this.salesmanId, + this.willPlan, + this.visitType, + this.visitMode, + this.priority, + this.subject, + this.planTime, + this.planEndTime, + this.checkinTime, + this.checkinStatus, + this.checkinLng, + this.checkinLat, + this.spaceDesc, + this.intentLevel, + this.intentDesc, + this.demands, + this.companion, + this.receptionPerson, + this.receptionTitle, + this.receptionPhone, + this.resultRating, + this.nextVisitTime, + this.nextAction, + this.photos = const [], + this.photoUrls = const [], + this.surveyOrderId, + this.projectNo, + this.createdAt, + this.updatedAt, + this.customer, + this.salesmanName, + this.salesmanPhone, + }); + + final int id; + final String visitNo; + final int customerId; + final String visitPerson; + final int status; + final String? visitPhone; + final String? visitContent; + final String? visitTime; + final int? salesmanId; + final int? willPlan; + final int? visitType; + final int? visitMode; + final int? priority; + final String? subject; + final String? planTime; + final String? planEndTime; + final String? checkinTime; + final int? checkinStatus; + final double? checkinLng; + final double? checkinLat; + final String? spaceDesc; + final int? intentLevel; + final String? intentDesc; + final String? demands; + final String? companion; + final String? receptionPerson; + final String? receptionTitle; + final String? receptionPhone; + final String? resultRating; + final String? nextVisitTime; + final String? nextAction; + + /// 现场照片对象 key 列表(持久化字段) + final List photos; + + /// 现场照片预签名访问 URL 列表(后端动态生成) + final List photoUrls; + final int? surveyOrderId; + final String? projectNo; + final String? createdAt; + final String? updatedAt; + final VisitCustomer? customer; + final String? salesmanName; + final String? salesmanPhone; + + factory VisitInfo.fromJson(Map json) => VisitInfo( + id: toIntOr(json['id'], 0), + visitNo: json['visitNo'] as String? ?? '', + customerId: toIntOr(json['customerId'], 0), + visitPerson: json['visitPerson'] as String? ?? '', + status: toIntOr(json['status'], 0), + visitPhone: json['visitPhone'] as String?, + visitContent: json['visitContent'] as String?, + visitTime: json['visitTime'] as String?, + salesmanId: toIntOrNull(json['salesmanId']), + willPlan: toIntOrNull(json['willPlan']), + visitType: toIntOrNull(json['visitType']), + visitMode: toIntOrNull(json['visitMode']), + priority: toIntOrNull(json['priority']), + subject: json['subject'] as String?, + planTime: json['planTime'] as String?, + planEndTime: json['planEndTime'] as String?, + checkinTime: json['checkinTime'] as String?, + checkinStatus: toIntOrNull(json['checkinStatus']), + checkinLng: (json['checkinLng'] as num?)?.toDouble(), + checkinLat: (json['checkinLat'] as num?)?.toDouble(), + spaceDesc: json['spaceDesc'] as String?, + intentLevel: toIntOrNull(json['intentLevel']), + intentDesc: json['intentDesc'] as String?, + demands: json['demands'] as String?, + companion: json['companion'] as String?, + receptionPerson: json['receptionPerson'] as String?, + receptionTitle: json['receptionTitle'] as String?, + receptionPhone: json['receptionPhone'] as String?, + resultRating: json['resultRating'] as String?, + nextVisitTime: json['nextVisitTime'] as String?, + nextAction: json['nextAction'] as String?, + photos: (json['photos'] as List? ?? []).map((e) => e.toString()).toList(), + photoUrls: (json['photoUrls'] as List? ?? []).map((e) => e.toString()).toList(), + surveyOrderId: toIntOrNull(json['surveyOrderId']), + projectNo: json['projectNo'] as String?, + createdAt: json['created_at'] as String?, + updatedAt: json['updated_at'] as String?, + customer: json['customer'] == null + ? null + : VisitCustomer.fromJson((json['customer'] as Map).cast()), + salesmanName: json['salesmanName'] as String?, + salesmanPhone: json['salesmanPhone'] as String?, + ); + + String get customerName => + customer?.customerName ?? '客户 #$customerId'; +} + +class VisitPage { + const VisitPage({ + required this.list, + required this.total, + required this.page, + required this.pageSize, + }); + + final List list; + final int total; + final int page; + final int pageSize; +} + +/// KPI 统计卡数据。 +class VisitStats { + const VisitStats({ + required this.total, + required this.pending, + required this.todayPlan, + required this.urgentPending, + required this.conversionRate, + required this.pendingReview, + required this.completed, + required this.converted, + required this.intentTotal, + }); + + final int total; + final int pending; + final int todayPlan; + final int urgentPending; + final num conversionRate; + final int pendingReview; + final int completed; + final int converted; + final int intentTotal; + + factory VisitStats.fromJson(Map json) => VisitStats( + total: toIntOr(json['total'], 0), + pending: toIntOr(json['pending'], 0), + todayPlan: toIntOr(json['todayPlan'], 0), + urgentPending: toIntOr(json['urgentPending'], 0), + conversionRate: (json['conversionRate'] as num?) ?? 0, + pendingReview: toIntOr(json['pendingReview'], 0), + completed: toIntOr(json['completed'], 0), + converted: toIntOr(json['converted'], 0), + intentTotal: toIntOr(json['intentTotal'], 0), + ); + + static const empty = VisitStats( + total: 0, + pending: 0, + todayPlan: 0, + urgentPending: 0, + conversionRate: 0, + pendingReview: 0, + completed: 0, + converted: 0, + intentTotal: 0, + ); +} + +/// 批量安排拜访结果。 +class VisitBatchResult { + const VisitBatchResult({required this.total, required this.ids}); + + final int total; + final List ids; + + factory VisitBatchResult.fromJson(Map json) => VisitBatchResult( + total: toIntOr(json['total'], 0), + ids: (json['ids'] as List? ?? []).map((e) => toIntOr(e, 0)).toList(), + ); +} \ No newline at end of file diff --git a/lib/features/visit/presentation/visit_batch_page.dart b/lib/features/visit/presentation/visit_batch_page.dart new file mode 100644 index 0000000..6f9609f --- /dev/null +++ b/lib/features/visit/presentation/visit_batch_page.dart @@ -0,0 +1,695 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/format_util.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../auth/application/session_controller.dart'; +import '../../customer/data/customer_api.dart'; +import '../../customer/data/customer_models.dart'; +import '../../customer/data/user_api.dart'; +import '../data/visit_api.dart'; +import '../data/visit_models.dart'; + +/// 批量安排拜访页,对应 `pages/visit/batch.vue`。 +class VisitBatchPage extends ConsumerStatefulWidget { + const VisitBatchPage({super.key}); + + @override + ConsumerState createState() => _VisitBatchPageState(); +} + +class _VisitBatchPageState extends ConsumerState { + final _keyword = TextEditingController(); + final _subject = TextEditingController(); + + final List _customers = []; + final List _selectedIds = []; + List _salesmen = const []; + + bool _customerLoading = false; + bool _saving = false; + bool _initialized = false; + + String _planTime = todayStr(); + String _planEndTime = ''; + int _typeIndex = 0; + int _modeIndex = 0; + int _priorityIndex = 2; + int _salesmanIndex = -1; + + late final List _typeLabels = visitTypeOptions + .map((o) => o.label) + .toList(); + late final List _modeLabels = visitModeOptions + .map((o) => o.label) + .toList(); + late final List _priorityLabels = visitPriorityOptions + .map((o) => o.label) + .toList(); + + @override + void dispose() { + _keyword.dispose(); + _subject.dispose(); + super.dispose(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_initialized) return; + _initialized = true; + + final preset = int.tryParse( + GoRouterState.of(context).uri.queryParameters['customerId'] ?? '', + ); + if (preset != null && preset > 0) _selectedIds.add(preset); + + _loadCustomers(); + if (_isAdmin) _loadSalesmen(); + } + + bool get _isAdmin => ref.read(sessionProvider).user?.isAdmin ?? false; + + int get _visitType => visitTypeOptions[_typeIndex].value; + + int get _visitMode => visitModeOptions[_modeIndex].value; + + int get _priority => visitPriorityOptions[_priorityIndex].value; + + int? get _salesmanId => + _salesmanIndex > 0 ? _salesmen[_salesmanIndex - 1].id : null; + + List get _salesmanLabels => [ + '默认本人', + ..._salesmen.map((s) => s.optionLabel), + ]; + + List get _filteredCustomers { + final kw = _keyword.text.trim().toLowerCase(); + if (kw.isEmpty) return _customers; + return _customers + .where( + (c) => + c.customerName.toLowerCase().contains(kw) || + c.customerNo.toLowerCase().contains(kw), + ) + .toList(); + } + + Future _loadCustomers() async { + _customerLoading = true; + try { + final res = await ref.read(customerApiProvider).options(); + if (!mounted) return; + if (res.isOk && res.data != null) { + _customers + ..clear() + ..addAll(res.data!); + } + } catch (_) { + showAppToast('客户列表加载失败'); + } finally { + if (mounted) setState(() => _customerLoading = false); + } + } + + Future _loadSalesmen() async { + try { + final list = await ref.read(userApiProvider).salesmanOptions(); + if (mounted) setState(() => _salesmen = list); + } catch (_) { + if (mounted) setState(() => _salesmen = const []); + } + } + + void _toggle(int id) { + setState(() { + if (_selectedIds.contains(id)) { + _selectedIds.remove(id); + } else { + _selectedIds.add(id); + } + }); + } + + void _selectAll() { + setState(() { + for (final c in _filteredCustomers) { + if (!_selectedIds.contains(c.id)) _selectedIds.add(c.id); + } + }); + } + + void _clearAll() => setState(_selectedIds.clear); + + Future _pickPlanStart() async { + final picked = await _pickDate(_planTime); + if (picked == null) return; + if (!mounted) return; + setState(() => _planTime = formatDate(picked)); + } + + Future _pickPlanEnd() async { + final picked = await _pickDate(_planEndTime); + if (picked == null) return; + if (!mounted) return; + setState(() => _planEndTime = formatDate(picked)); + } + + Future _pickDate(String current) { + return showDatePicker( + context: context, + initialDate: parseDate(current) ?? DateTime.now(), + firstDate: DateTime(2000), + lastDate: DateTime(2100), + ); + } + + Future _pickOption({ + required List labels, + required int selectedIndex, + required ValueChanged onSelected, + }) async { + final index = await showModalBottomSheet( + context: context, + backgroundColor: AppColors.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.lg)), + ), + builder: (ctx) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + for (var i = 0; i < labels.length; i++) + ListTile( + title: Text( + labels[i], + style: AppTypography.bodyMd.copyWith( + color: AppColors.onSurface, + ), + ), + trailing: i == selectedIndex + ? const XIcon('check', size: 18, color: AppColors.primary) + : null, + onTap: () => Navigator.of(ctx).pop(i), + ), + ], + ), + ), + ); + if (index == null) return; + if (!mounted) return; + setState(() => onSelected(index)); + } + + Future _onSave() async { + if (_selectedIds.isEmpty) { + showAppToast('请至少选择一个客户'); + return; + } + if (_planTime.isEmpty) { + showAppToast('请选择计划日期'); + return; + } + + setState(() => _saving = true); + try { + final payload = { + 'customerIds': List.from(_selectedIds), + 'planTime': _planTime, + 'subject': _subject.text, + 'visitType': _visitType, + 'visitMode': _visitMode, + 'priority': _priority, + }; + if (_planEndTime.isNotEmpty) payload['planEndTime'] = _planEndTime; + final salesmanId = _salesmanId; + if (_isAdmin && salesmanId != null) payload['salesmanId'] = salesmanId; + + final res = await ref.read(visitApiProvider).batchCreate(payload); + if (!mounted) return; + final data = res.data; + if (res.isOk && data != null) { + showAppToast('成功创建 ${data.total} 条拜访计划'); + Future.delayed(const Duration(milliseconds: 800), () { + if (mounted) context.pop(); + }); + } else { + showAppToast(res.message.isEmpty ? '创建失败' : res.message); + } + } catch (_) { + if (mounted) showAppToast('创建失败,请重试'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + @override + Widget build(BuildContext context) { + return XPageShell( + topBar: XTopBar.nav(title: '批量安排拜访', onBack: () => context.pop()), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 60), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildPlanCard(), + _buildCustomerCard(), + Container( + margin: const EdgeInsets.fromLTRB(0, 24, 0, 40), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(9999), + boxShadow: const [ + BoxShadow( + color: Color(0x4D0054CD), + blurRadius: 16, + offset: Offset(0, 6), + ), + ], + ), + child: XPrimaryButton( + label: '创建 ${_selectedIds.length} 条拜访计划', + loading: _saving, + onPressed: _onSave, + ), + ), + ], + ), + ), + ); + } + + Widget _buildPlanCard() { + return XCard( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 16), + margin: const EdgeInsets.only(bottom: 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(0, 14, 0, 6), + child: Text( + '计划信息', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + ), + _formItem( + label: '计划日期', + isRequired: true, + child: _pickerValue( + text: _planTime.isEmpty ? '请选择计划日期' : _planTime, + placeholder: _planTime.isEmpty, + trailingIcon: 'calendar', + onTap: _pickPlanStart, + ), + ), + _formDivider(), + _formItem( + label: '计划结束', + child: _pickerValue( + text: _planEndTime.isEmpty ? '选填' : _planEndTime, + placeholder: _planEndTime.isEmpty, + trailingIcon: 'calendar', + onTap: _pickPlanEnd, + ), + ), + _formDivider(), + _formItem( + label: '拜访主题', + child: _textInput(_subject, '默认:批量安排的拜访计划'), + ), + _formDivider(), + _formItem( + label: '拜访类型', + child: _pickerValue( + text: _typeLabels[_typeIndex], + placeholder: false, + trailingIcon: 'forward', + onTap: () => _pickOption( + labels: _typeLabels, + selectedIndex: _typeIndex, + onSelected: (i) => _typeIndex = i, + ), + ), + ), + _formDivider(), + _formItem( + label: '拜访方式', + child: _pickerValue( + text: _modeLabels[_modeIndex], + placeholder: false, + trailingIcon: 'forward', + onTap: () => _pickOption( + labels: _modeLabels, + selectedIndex: _modeIndex, + onSelected: (i) => _modeIndex = i, + ), + ), + ), + _formDivider(), + _formItem( + label: '优先级', + child: _pickerValue( + text: _priorityLabels[_priorityIndex], + placeholder: false, + trailingIcon: 'forward', + onTap: () => _pickOption( + labels: _priorityLabels, + selectedIndex: _priorityIndex, + onSelected: (i) => _priorityIndex = i, + ), + ), + ), + if (_isAdmin) ...[ + _formDivider(), + _formItem( + label: '负责业务员', + child: _pickerValue( + text: _salesmanIndex >= 0 + ? _salesmanLabels[_salesmanIndex] + : '默认本人', + placeholder: _salesmanIndex < 0, + trailingIcon: 'forward', + onTap: () => _pickOption( + labels: _salesmanLabels, + selectedIndex: _salesmanIndex, + onSelected: (i) => _salesmanIndex = i, + ), + ), + ), + ], + ], + ), + ); + } + + Widget _buildCustomerCard() { + return XCard( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(0, 14, 0, 6), + child: Row( + children: [ + const Text( + '选择客户', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + const Spacer(), + GestureDetector( + onTap: _selectAll, + child: const Text( + '全选', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: AppColors.primary, + ), + ), + ), + const SizedBox(width: 16), + GestureDetector( + onTap: _clearAll, + child: const Text( + '清空', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: AppColors.primary, + ), + ), + ), + ], + ), + ), + _searchBar(), + Padding( + padding: const EdgeInsets.fromLTRB(0, 4, 0, 8), + child: Row( + children: [ + const Text( + '已选 ', + style: TextStyle(fontSize: 13, color: AppColors.textMuted), + ), + Text( + '${_selectedIds.length}', + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: AppColors.primary, + ), + ), + const Text( + ' 个客户', + style: TextStyle(fontSize: 13, color: AppColors.textMuted), + ), + ], + ), + ), + if (_customerLoading) + _centerText('加载中...') + else if (_filteredCustomers.isEmpty) + _centerText('暂无可选客户') + else + for (final c in _filteredCustomers) _customerItem(c), + ], + ), + ); + } + + Widget _formItem({ + required String label, + required Widget child, + bool isRequired = false, + }) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + label, + style: AppTypography.labelBold.copyWith( + color: AppColors.onSurfaceVariant, + ), + ), + if (isRequired) + const Text( + ' *', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: AppColors.statusError, + ), + ), + ], + ), + const SizedBox(height: 8), + child, + ], + ), + ); + } + + Widget _formDivider() => + const Divider(height: 1, thickness: 1, color: AppColors.borderRule); + + Widget _pickerValue({ + required String text, + required bool placeholder, + required String trailingIcon, + required VoidCallback onTap, + }) { + return GestureDetector( + onTap: onTap, + child: Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + Expanded( + child: Text( + text, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 15, + color: placeholder + ? AppColors.textPlaceholder + : AppColors.onSurface, + ), + ), + ), + XIcon(trailingIcon, size: 16, color: AppColors.outline), + ], + ), + ), + ); + } + + Widget _textInput(TextEditingController controller, String hint) { + return Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: TextField( + controller: controller, + style: const TextStyle(fontSize: 15, color: AppColors.onSurface), + cursorColor: AppColors.primary, + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + hintText: hint, + hintStyle: const TextStyle( + fontSize: 15, + color: AppColors.textPlaceholder, + ), + ), + ), + ); + } + + Widget _searchBar() { + return Container( + height: 42, + margin: const EdgeInsets.fromLTRB(0, 6, 0, 8), + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + const XIcon('search', size: 18, color: AppColors.textMuted), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: _keyword, + onChanged: (_) => setState(() {}), + style: const TextStyle(fontSize: 15, color: AppColors.onSurface), + cursorColor: AppColors.primary, + decoration: const InputDecoration( + isDense: true, + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + hintText: '按客户名称、编号筛选...', + hintStyle: TextStyle( + fontSize: 15, + color: AppColors.textPlaceholder, + ), + ), + ), + ), + ], + ), + ); + } + + Widget _centerText(String text) => Padding( + padding: const EdgeInsets.symmetric(vertical: 32), + child: Text( + text, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 14, color: AppColors.textMuted), + ), + ); + + Widget _customerItem(CustomerOption c) { + final selected = _selectedIds.contains(c.id); + return GestureDetector( + onTap: () => _toggle(c.id), + child: Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12), + decoration: BoxDecoration( + color: selected ? AppColors.surfaceContainerLow : AppColors.surfaceBright, + border: Border.all( + color: selected ? AppColors.primaryContainer : AppColors.borderRule, + ), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + Container( + width: 22, + height: 22, + alignment: Alignment.center, + decoration: BoxDecoration( + color: selected ? AppColors.primaryContainer : Colors.white, + border: Border.all( + color: selected + ? AppColors.primaryContainer + : AppColors.borderRule, + width: 1.5, + ), + borderRadius: BorderRadius.circular(6), + ), + child: selected + ? const XIcon('check', size: 14, color: Colors.white) + : null, + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + c.customerName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 15, + color: AppColors.onSurface, + ), + ), + const SizedBox(height: 2), + Text( + c.customerNo, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppTypography.dataMono.copyWith( + fontSize: 11, + color: AppColors.textMuted, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/visit/presentation/visit_detail_page.dart b/lib/features/visit/presentation/visit_detail_page.dart new file mode 100644 index 0000000..7c2693d --- /dev/null +++ b/lib/features/visit/presentation/visit_detail_page.dart @@ -0,0 +1,604 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/format_util.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../auth/application/session_controller.dart'; +import '../../customer/data/user_api.dart'; +import '../data/visit_api.dart'; +import '../data/visit_models.dart'; + +/// 拜访详情页,对应 `pages/visit/detail.vue`。 +class VisitDetailPage extends ConsumerStatefulWidget { + const VisitDetailPage({super.key, required this.id}); + + final int id; + + @override + ConsumerState createState() => _VisitDetailPageState(); +} + +class _VisitDetailPageState extends ConsumerState { + VisitInfo? _visit; + bool _loading = false; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + setState(() => _loading = true); + try { + final res = await ref.read(visitApiProvider).detail(widget.id); + if (!mounted) return; + if (res.isOk && res.data != null) { + setState(() => _visit = res.data); + } else { + showAppToast(res.message.isNotEmpty ? res.message : '拜访记录不存在'); + } + } catch (_) { + showAppToast('加载失败'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + String _findLabel(List options, int? value) { + if (value == null) return ''; + return options.where((o) => o.value == value).map((o) => o.label).firstOrNull ?? + ''; + } + + String _planRange(VisitInfo visit) { + if (visit.planTime == null || visit.planTime!.isEmpty) return '未排期'; + final start = formatDate(visit.planTime); + if (visit.planEndTime == null || visit.planEndTime!.isEmpty) return start; + return '$start ~ ${formatDate(visit.planEndTime)}'; + } + + String _receptionText(VisitInfo visit) { + if (visit.receptionPerson == null || visit.receptionPerson!.isEmpty) return '-'; + final title = visit.receptionTitle != null && visit.receptionTitle!.isNotEmpty + ? '(${visit.receptionTitle})' + : ''; + final phone = visit.receptionPhone != null && visit.receptionPhone!.isNotEmpty + ? ' · ${visit.receptionPhone}' + : ''; + return '${visit.receptionPerson}$title$phone'; + } + + void _goEdit(bool canEdit) { + if (!canEdit) { + showAppToast('仅待执行的拜访可编辑'); + return; + } + context.push('/visit/form?id=${widget.id}').then((_) { + if (mounted) _load(); + }); + } + + void _goExecute() { + context.push('/visit/execute/${widget.id}').then((_) { + if (mounted) _load(); + }); + } + + Future _onCancelVisit() async { + final confirmed = await showAppConfirm( + title: '取消拜访', + content: '确定取消该拜访计划吗?取消后不可再执行。', + ); + if (!confirmed) return; + try { + final res = await ref + .read(visitApiProvider) + .updateStatus(widget.id, {'status': VisitStatus.canceled}); + if (res.isOk) { + showAppToast('已取消', success: true); + _load(); + } else { + showAppToast(res.message.isNotEmpty ? res.message : '操作失败'); + } + } catch (_) { + showAppToast('操作失败'); + } + } + + Future _onReassign() async { + try { + final salesmen = await ref.read(userApiProvider).salesmanOptions(); + if (!mounted) return; + if (salesmen.isEmpty) { + showAppToast('暂无可选业务员'); + return; + } + final index = await _showSalesmanSheet( + salesmen.map((s) => s.optionLabel).toList(), + ); + if (index == null || !mounted) return; + final res = await ref + .read(visitApiProvider) + .reassign(widget.id, {'salesmanId': salesmen[index].id}); + if (res.isOk) { + showAppToast('改派成功', success: true); + _load(); + } else { + showAppToast(res.message.isNotEmpty ? res.message : '改派失败'); + } + } catch (_) { + showAppToast('获取业务员失败'); + } + } + + Future _showSalesmanSheet(List labels) { + return showModalBottomSheet( + context: context, + backgroundColor: AppColors.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.lg)), + ), + builder: (ctx) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + for (var i = 0; i < labels.length; i++) + ListTile( + title: Text( + labels[i], + style: AppTypography.bodyMd.copyWith(color: AppColors.onSurface), + ), + onTap: () => Navigator.of(ctx).pop(i), + ), + ], + ), + ), + ); + } + + void _previewPhoto(List urls, int index) { + showDialog( + context: context, + barrierColor: Colors.black, + builder: (_) => Dialog( + backgroundColor: Colors.transparent, + insetPadding: EdgeInsets.zero, + child: GestureDetector( + onTap: () => Navigator.of(context).pop(), + child: Center( + child: Image.network(urls[index], fit: BoxFit.contain), + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final visit = _visit; + final isAdmin = ref.watch(sessionProvider).user?.isAdmin ?? false; + final canEdit = visit?.status == VisitStatus.pending; + + return XPageShell( + topBar: XTopBar.nav( + title: '拜访详情', + onBack: () => context.pop(), + trailing: GestureDetector( + onTap: () => _goEdit(canEdit), + behavior: HitTestBehavior.opaque, + child: XIcon( + 'edit', + size: 20, + color: canEdit ? AppColors.primary : AppColors.outlineVariant, + ), + ), + ), + child: visit == null + ? (Center( + child: _loading + ? const Text( + '加载中...', + style: TextStyle(fontSize: 15, color: AppColors.textMuted), + ) + : const SizedBox.shrink(), + )) + : ListView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 60), + children: _buildContent(visit, canEdit, isAdmin), + ), + ); + } + + List _buildContent(VisitInfo visit, bool canEdit, bool isAdmin) { + final customer = visit.customer; + final photoList = visit.photoUrls.where((u) => u.isNotEmpty).toList(); + final hasGps = + (visit.checkinLng ?? 0) != 0 && (visit.checkinLat ?? 0) != 0; + final hasExecution = + (visit.checkinTime != null && visit.checkinTime!.isNotEmpty) || + (visit.checkinStatus ?? 0) > 0 || + hasGps || + (visit.spaceDesc != null && visit.spaceDesc!.isNotEmpty); + final hasResult = + (visit.visitTime != null && visit.visitTime!.isNotEmpty) || + (visit.intentLevel ?? 0) > 0 || + (visit.intentDesc != null && visit.intentDesc!.isNotEmpty) || + (visit.demands != null && visit.demands!.isNotEmpty) || + (visit.visitContent != null && visit.visitContent!.isNotEmpty) || + (visit.companion != null && visit.companion!.isNotEmpty) || + (visit.receptionPerson != null && visit.receptionPerson!.isNotEmpty) || + (visit.resultRating != null && visit.resultRating!.isNotEmpty); + final hasNext = + (visit.nextVisitTime != null && visit.nextVisitTime!.isNotEmpty) || + (visit.nextAction != null && visit.nextAction!.isNotEmpty); + final priority = visit.priority ?? 0; + final typeText = _findLabel(visitTypeOptions, visit.visitType); + final modeText = _findLabel(visitModeOptions, visit.visitMode); + + return [ + // 头部 + XCard( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + visit.subject?.isNotEmpty == true ? visit.subject! : '客户拜访', + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + ), + const SizedBox(width: 8), + XChip( + visitStatusText(visit.status), + tone: visitStatusTone(visit.status), + ), + ], + ), + if (priority > 0 || typeText.isNotEmpty || modeText.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 10), + child: Wrap( + spacing: 6, + runSpacing: 6, + children: [ + if (priority > 0) + XChip( + visitPriorityText(visit.priority), + tone: visitPriorityTone(visit.priority), + ), + if (typeText.isNotEmpty) XChip(typeText, tone: ChipTone.muted), + if (modeText.isNotEmpty) XChip(modeText, tone: ChipTone.muted), + ], + ), + ), + Padding( + padding: const EdgeInsets.only(top: 12), + child: Row( + children: [ + const Text( + '拜访单号', + style: TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + const SizedBox(width: 8), + Text( + visit.visitNo, + style: AppTypography.dataMono.copyWith( + fontSize: 12, + color: AppColors.onSurface, + ), + ), + ], + ), + ), + ], + ), + ), + + // 客户信息 + _sectionTitle('groups', AppColors.primary, '客户信息'), + XCard( + onTap: visit.customerId > 0 + ? () => context.push('/customer/detail/${visit.customerId}') + : null, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: _infoColumn([ + _infoItem( + 'business', + '客户名称', + customer?.customerName?.isNotEmpty == true + ? customer!.customerName! + : '-', + link: true, + ), + if (customer?.customerNo?.isNotEmpty == true) + _infoItem('category', '客户编号', customer!.customerNo!, mono: true), + if (customer?.contactPerson?.isNotEmpty == true) + _infoItem('person', '联系人', customer!.contactPerson!), + if (customer?.contactPhone?.isNotEmpty == true) + _infoItem('call', '联系电话', customer!.contactPhone!, mono: true), + if (customer?.address?.isNotEmpty == true) + _infoItem('location', '客户地址', customer!.address!), + ]), + ), + + // 计划安排 + _sectionTitle('schedule', AppColors.secondary, '计划安排'), + _plainInfoCard([ + _infoItem('calendar', '计划时间', _planRange(visit)), + _infoItem( + 'person', + '拜访人', + '${visit.visitPerson.isNotEmpty ? visit.visitPerson : '-'}' + '${visit.visitPhone != null && visit.visitPhone!.isNotEmpty ? ' · ${visit.visitPhone}' : ''}', + ), + if (visit.salesmanName != null && visit.salesmanName!.isNotEmpty) + _infoItem( + 'verified', + '负责业务员', + '${visit.salesmanName}' + '${visit.salesmanPhone != null && visit.salesmanPhone!.isNotEmpty ? ' · ${visit.salesmanPhone}' : ''}', + ), + ]), + + // 现场执行 + if (hasExecution) ...[ + _sectionTitle('location', AppColors.tertiary, '现场执行'), + _plainInfoCard([ + if (visit.checkinTime != null && visit.checkinTime!.isNotEmpty) + _infoItem('clock', '到场签到', formatDateTime(visit.checkinTime)), + if (hasGps) + _infoItem( + 'location', + 'GPS 坐标', + '${visit.checkinLat}, ${visit.checkinLng}', + mono: true, + ), + if (visit.spaceDesc != null && visit.spaceDesc!.isNotEmpty) + _infoItem('business', '现场情况', visit.spaceDesc!), + ]), + ], + + // 拜访结果 + if (hasResult) ...[ + _sectionTitle('check-circle', AppColors.primary, '拜访结果'), + _plainInfoCard([ + if (visit.visitTime != null && visit.visitTime!.isNotEmpty) + _infoItem('clock', '实际拜访时间', formatDate(visit.visitTime)), + if ((visit.intentLevel ?? 0) > 0) + _infoItem( + 'trend-up', + '意向评级', + _findLabel(visitIntentOptions, visit.intentLevel), + ), + if (visit.intentDesc != null && visit.intentDesc!.isNotEmpty) + _infoItem('chart', '意向说明', visit.intentDesc!), + if (visit.demands != null && visit.demands!.isNotEmpty) + _infoItem('bolt', '客户需求', visit.demands!), + if (visit.visitContent != null && visit.visitContent!.isNotEmpty) + _infoItem('edit', '拜访内容', visit.visitContent!), + if (visit.companion != null && visit.companion!.isNotEmpty) + _infoItem('person', '随行人员', visit.companion!), + if (visit.receptionPerson != null && visit.receptionPerson!.isNotEmpty) + _infoItem('person', '接待人', _receptionText(visit)), + if (visit.resultRating != null && visit.resultRating!.isNotEmpty) + _infoItem('verified', '结果评价', visit.resultRating!), + ]), + ], + + // 后续计划 + if (hasNext) ...[ + _sectionTitle('forward', AppColors.secondary, '后续计划'), + _plainInfoCard([ + if (visit.nextVisitTime != null && visit.nextVisitTime!.isNotEmpty) + _infoItem('calendar', '下次拜访', formatDate(visit.nextVisitTime)), + if (visit.nextAction != null && visit.nextAction!.isNotEmpty) + _infoItem('forward', '下一步动作', visit.nextAction!), + ]), + ], + + // 现场照片 + if (photoList.isNotEmpty) ...[ + _sectionTitle('camera', AppColors.primary, '现场照片'), + LayoutBuilder( + builder: (context, constraints) { + final width = (constraints.maxWidth - 10) / 2; + return Wrap( + spacing: 10, + runSpacing: 10, + children: [ + for (var i = 0; i < photoList.length; i++) + GestureDetector( + onTap: () => _previewPhoto(photoList, i), + child: ClipRRect( + borderRadius: BorderRadius.circular(AppRadius.lg), + child: Container( + width: width, + height: 140, + color: AppColors.surfaceVariant, + child: Image.network(photoList[i], fit: BoxFit.cover), + ), + ), + ), + ], + ); + }, + ), + ], + + // 流程信息 + _sectionTitle('verified', AppColors.tertiary, '流程信息'), + _plainInfoCard([ + if ((visit.surveyOrderId ?? 0) > 0 || + (visit.projectNo != null && visit.projectNo!.isNotEmpty)) + _infoItem( + 'construction', + '关联立项', + visit.projectNo != null && visit.projectNo!.isNotEmpty + ? visit.projectNo! + : '勘察单 #${visit.surveyOrderId}', + mono: true, + ), + _infoItem('clock', '创建时间', formatDateTime(visit.createdAt)), + ]), + + // 业务员操作 + _buildActions(canEdit, isAdmin), + ]; + } + + Widget _buildActions(bool canEdit, bool isAdmin) { + if (!canEdit && !isAdmin) { + return Padding( + padding: const EdgeInsets.only(top: 24), + child: Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(AppRadius.lg), + ), + child: const Text( + '当前状态下无需业务员操作,取证复核 / 立项 / 归档请在 Web 后台办理', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 13, color: AppColors.textMuted), + ), + ), + ); + } + return Padding( + padding: const EdgeInsets.only(top: 24), + child: Column( + children: [ + if (canEdit) + XPrimaryButton( + label: '开始执行并完成', + onPressed: _goExecute, + pill: false, + height: 48, + fontSize: 15, + margin: const EdgeInsets.only(bottom: 12), + ), + if (canEdit) + XPrimaryButton( + label: '取消拜访', + onPressed: _onCancelVisit, + pill: false, + height: 48, + fontSize: 15, + background: AppColors.surface, + foreground: AppColors.statusError, + borderColor: AppColors.borderRule, + margin: const EdgeInsets.only(bottom: 12), + ), + if (isAdmin) + XPrimaryButton( + label: '改派业务员', + onPressed: _onReassign, + pill: false, + height: 48, + fontSize: 15, + background: AppColors.surface, + foreground: AppColors.statusError, + borderColor: AppColors.borderRule, + ), + ], + ), + ); + } + + Widget _sectionTitle(String icon, Color iconColor, String text) { + return Padding( + padding: const EdgeInsets.only(top: 22, bottom: 10), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + XIcon(icon, size: 17, color: iconColor), + const SizedBox(width: 6), + Text( + text, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + ], + ), + ); + } + + Widget _plainInfoCard(List items) { + return XCard( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: _infoColumn(items), + ); + } + + Widget _infoColumn(List items) { + final children = []; + for (var i = 0; i < items.length; i++) { + if (i > 0) { + children.add( + const Divider(height: 1, thickness: 1, color: AppColors.borderRule), + ); + } + children.add(items[i]); + } + return Column(children: children); + } + + Widget _infoItem( + String icon, + String label, + String value, { + bool mono = false, + bool link = false, + }) { + final color = link ? AppColors.primary : AppColors.onSurface; + final style = mono + ? AppTypography.dataMono.copyWith(fontSize: 15, color: color) + : TextStyle(fontSize: 15, color: color); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 13), + child: Row( + children: [ + XIcon(icon, size: 18, color: AppColors.textMuted), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + Text(value, style: style), + ], + ), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/visit/presentation/visit_execute_page.dart b/lib/features/visit/presentation/visit_execute_page.dart new file mode 100644 index 0000000..25e1797 --- /dev/null +++ b/lib/features/visit/presentation/visit_execute_page.dart @@ -0,0 +1,947 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:go_router/go_router.dart'; +import 'package:image_picker/image_picker.dart'; + +import '../../../core/network/api_response.dart'; +import '../../../core/providers.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/format_util.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../data/visit_api.dart'; +import '../data/visit_models.dart'; + +/// 拜访执行页,对应 `pages/visit/execute.vue`。 +class VisitExecutePage extends ConsumerStatefulWidget { + const VisitExecutePage({super.key, required this.id}); + + final int id; + + @override + ConsumerState createState() => _VisitExecutePageState(); +} + +/// 现场照片槽位:key 为对象存储 key(落库),url 为预签名访问地址(预览)。 +class _PhotoSlot { + String key = ''; + String url = ''; +} + +class _VisitExecutePageState extends ConsumerState { + VisitInfo? _visit; + bool _loading = false; + bool _checking = false; + bool _submitting = false; + + final _spaceDesc = TextEditingController(); + final _visitContent = TextEditingController(); + final _demands = TextEditingController(); + final _intentDesc = TextEditingController(); + int? _intentLevel; + + final List<_PhotoSlot> _photoSlots = [_PhotoSlot(), _PhotoSlot()]; + + NavigatorState? _uploadingNavigator; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _spaceDesc.dispose(); + _visitContent.dispose(); + _demands.dispose(); + _intentDesc.dispose(); + super.dispose(); + } + + VisitApi get _api => ref.read(visitApiProvider); + + bool get _checkedIn => _visit?.checkinStatus == 1; + + bool get _hasGps => + (_visit?.checkinLng ?? 0) != 0 && (_visit?.checkinLat ?? 0) != 0; + + String get _gpsText => '${_visit?.checkinLat}, ${_visit?.checkinLng}'; + + String get _planRange { + final v = _visit; + final planTime = v?.planTime; + if (planTime == null || planTime.isEmpty) return '未排期'; + final start = formatDate(planTime); + final endTime = v?.planEndTime; + if (endTime == null || endTime.isEmpty) return start; + return '$start ~ ${formatDate(endTime)}'; + } + + Future _load() async { + setState(() => _loading = true); + try { + final res = await _api.detail(widget.id); + if (!mounted) return; + final d = res.data; + if (!res.isOk || d == null) { + showAppToast(res.message.isEmpty ? '拜访记录不存在' : res.message); + return; + } + if (d.status != VisitStatus.pending) { + showAppToast('该拜访已处理,无需执行'); + Future.delayed(const Duration(milliseconds: 600), () { + if (mounted) context.pop(); + }); + return; + } + _spaceDesc.text = d.spaceDesc ?? ''; + _visitContent.text = d.visitContent ?? ''; + _demands.text = d.demands ?? ''; + _intentDesc.text = d.intentDesc ?? ''; + setState(() { + _visit = d; + _intentLevel = d.intentLevel; + }); + } catch (_) { + if (mounted) showAppToast('加载失败'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + /// 到场签到:获取 GPS 后落库(后端 update 透传 checkinLng/checkinLat/checkinStatus)。 + Future _onCheckin() async { + setState(() => _checking = true); + try { + Position? loc; + try { + final permission = await Geolocator.requestPermission(); + if (permission == LocationPermission.denied || + permission == LocationPermission.deniedForever) { + loc = null; + } else { + loc = await Geolocator.getCurrentPosition(); + } + } catch (_) { + loc = null; + } + if (loc == null) { + showAppToast('定位失败,请检查定位权限'); + return; + } + + final res = await _api.update(widget.id, { + 'checkinLng': double.parse(loc.longitude.toStringAsFixed(6)), + 'checkinLat': double.parse(loc.latitude.toStringAsFixed(6)), + 'checkinStatus': 1, + 'checkinTime': nowDateTimeStr(), + }); + if (!mounted) return; + if (res.isOk) { + showAppToast('签到成功', success: true); + await _load(); + } else { + showAppToast(res.message.isEmpty ? '签到失败' : res.message); + } + } catch (_) { + if (mounted) showAppToast('签到失败,请重试'); + } finally { + if (mounted) setState(() => _checking = false); + } + } + + void _onPhotoTap(int index) { + final slot = _photoSlots[index]; + if (slot.url.isNotEmpty) { + _previewPhotos(index); + } else { + _pickPhoto(index); + } + } + + Future _pickPhoto(int index) async { + final source = await showModalBottomSheet( + context: context, + backgroundColor: AppColors.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.lg)), + ), + builder: (ctx) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + title: Text( + '拍照', + style: AppTypography.bodyMd.copyWith(color: AppColors.onSurface), + ), + onTap: () => Navigator.of(ctx).pop(ImageSource.camera), + ), + ListTile( + title: Text( + '从相册选择', + style: AppTypography.bodyMd.copyWith(color: AppColors.onSurface), + ), + onTap: () => Navigator.of(ctx).pop(ImageSource.gallery), + ), + ], + ), + ), + ); + if (source == null) return; + if (!mounted) return; + + final file = await ImagePicker().pickImage( + source: source, + imageQuality: 80, + ); + if (file == null) return; + if (!mounted) return; + + _showUploading(); + try { + // 严格依赖对象存储:上传失败直接抛出,不写入本地槽位。 + final up = await ref.read(apiClientProvider).uploadImage(file.path); + if (mounted) { + setState(() { + _photoSlots[index] + ..key = up.key + ..url = up.url; + }); + showAppToast('上传成功', success: true); + } + } catch (e) { + final message = e is ApiException && e.message.isNotEmpty + ? e.message + : '照片上传失败'; + showAppToast(message); + } finally { + _hideUploading(); + } + } + + void _removePhoto(int index) { + setState(() { + _photoSlots[index] + ..key = '' + ..url = ''; + }); + } + + void _previewPhotos(int index) { + final urls = _photoSlots + .where((s) => s.url.isNotEmpty) + .map((s) => s.url) + .toList(); + if (urls.isEmpty) return; + final current = urls.indexOf(_photoSlots[index].url); + showDialog( + context: context, + barrierColor: Colors.black, + builder: (ctx) => Dialog.fullscreen( + backgroundColor: Colors.black, + child: Stack( + children: [ + GestureDetector( + onTap: () => Navigator.of(ctx).pop(), + child: PageView.builder( + controller: PageController( + initialPage: current < 0 ? 0 : current, + ), + itemCount: urls.length, + itemBuilder: (_, i) => Center( + child: Image.network(urls[i], fit: BoxFit.contain), + ), + ), + ), + Positioned( + right: 12, + top: MediaQuery.paddingOf(ctx).top + 12, + child: GestureDetector( + onTap: () => Navigator.of(ctx).pop(), + child: const XIcon('close', size: 24, color: Colors.white), + ), + ), + ], + ), + ), + ); + } + + void _showUploading() { + // 提前抓取根导航器,页面被销毁时也能正常关闭上传遮罩。 + _uploadingNavigator = Navigator.of(context, rootNavigator: true); + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const _UploadingDialog(), + ); + } + + void _hideUploading() { + _uploadingNavigator?.pop(); + _uploadingNavigator = null; + } + + Future _onSubmit() async { + if (!_checkedIn) { + final go = await showAppConfirm( + title: '尚未签到', + content: '还未完成到场签到,确定直接提交吗?', + ); + if (!go) return; + } + + final photos = _photoSlots + .where((s) => s.key.isNotEmpty) + .map((s) => s.key) + .toList(); + + setState(() => _submitting = true); + try { + final payload = { + 'spaceDesc': _spaceDesc.text, + 'visitContent': _visitContent.text, + 'demands': _demands.text, + 'intentDesc': _intentDesc.text, + }; + final intentLevel = _intentLevel; + if (intentLevel != null && intentLevel != 0) { + payload['intentLevel'] = intentLevel; + } + if (photos.isNotEmpty) payload['photos'] = photos; + + final upd = await _api.update(widget.id, payload); + if (!mounted) return; + if (!upd.isOk) { + showAppToast(upd.message.isEmpty ? '保存失败' : upd.message); + return; + } + + final res = await _api.updateStatus(widget.id, { + 'status': VisitStatus.done, + }); + if (!mounted) return; + if (res.isOk) { + showAppToast('拜访已完成', success: true); + Future.delayed(const Duration(milliseconds: 600), () { + if (mounted) context.pop(); + }); + } else { + showAppToast(res.message.isEmpty ? '状态更新失败' : res.message); + } + } catch (_) { + if (mounted) showAppToast('提交失败,请重试'); + } finally { + if (mounted) setState(() => _submitting = false); + } + } + + @override + Widget build(BuildContext context) { + final visit = _visit; + return XPageShell( + topBar: XTopBar.nav(title: '拜访执行', onBack: () => context.pop()), + child: visit == null + ? (_loading + ? const Center(child: XPlaceholder(text: '加载中...')) + : const SizedBox.shrink()) + : SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 60), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildTaskCard(visit), + _sectionTitle( + '到场签到', + icon: 'location', + iconColor: AppColors.tertiary, + ), + _buildCheckinCard(), + _sectionTitle( + '现场记录', + icon: 'edit', + iconColor: AppColors.secondary, + ), + _buildRecordCard(), + _sectionTitle( + '意向评级', + icon: 'trend-up', + iconColor: AppColors.primary, + ), + _buildIntentCard(), + _sectionTitle( + '现场照片', + icon: 'camera', + iconColor: AppColors.primary, + hint: '最多 2 张', + ), + _buildPhotoGrid(), + _pillButton( + label: '提交并标记完成', + icon: 'check', + background: AppColors.primary, + fontSize: 16, + shadow: true, + loading: _submitting, + margin: const EdgeInsets.fromLTRB(16, 24, 16, 40), + onPressed: _onSubmit, + ), + ], + ), + ), + ); + } + + Widget _sectionTitle( + String text, { + required String icon, + required Color iconColor, + String? hint, + }) { + return Padding( + padding: const EdgeInsets.fromLTRB(0, 22, 0, 10), + child: Row( + children: [ + XIcon(icon, size: 17, color: iconColor), + const SizedBox(width: 6), + Text( + text, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + if (hint != null) ...[ + const SizedBox(width: 6), + Text( + hint, + style: const TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ], + ], + ), + ); + } + + Widget _buildTaskCard(VisitInfo visit) { + final customer = visit.customer; + final address = customer?.address; + final subject = visit.subject; + return XCard( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + subject == null || subject.isEmpty ? '客户拜访' : subject, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + const SizedBox(height: 4), + Text( + visit.visitNo, + style: AppTypography.dataMono.copyWith( + color: AppColors.textMuted, + ), + ), + ], + ), + ), + const SizedBox(width: 10), + XChip( + visitStatusText(visit.status), + tone: visitStatusTone(visit.status), + ), + ], + ), + const SizedBox(height: 12), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _taskLine( + 'business', + AppColors.primary, + customer?.customerName ?? '未知客户', + ), + if (address != null && address.isNotEmpty) ...[ + const SizedBox(height: 8), + _taskLine('location', AppColors.textMuted, address), + ], + const SizedBox(height: 8), + _taskLine( + 'schedule', + AppColors.statusWarn, + '计划时间:$_planRange', + ), + ], + ), + ], + ), + ); + } + + Widget _taskLine(String icon, Color color, String text) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + XIcon(icon, size: 18, color: color), + const SizedBox(width: 8), + Expanded( + child: Text( + text, + style: const TextStyle( + fontSize: 14, + color: AppColors.onSurfaceVariant, + ), + ), + ), + ], + ); + } + + Widget _buildCheckinCard() { + return XCard( + padding: const EdgeInsets.all(16), + child: _checkedIn ? _buildCheckinDone() : _buildCheckinAction(), + ); + } + + Widget _buildCheckinDone() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Row( + children: [ + XIcon('check-circle', size: 20, color: AppColors.tertiary), + SizedBox(width: 6), + Text( + '已签到', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: AppColors.tertiary, + ), + ), + ], + ), + const SizedBox(height: 6), + Text( + '签到时间:${formatDateTime(_visit?.checkinTime)}', + style: const TextStyle( + fontSize: 13, + color: AppColors.onSurfaceVariant, + ), + ), + if (_hasGps) ...[ + const SizedBox(height: 6), + Text( + '坐标:$_gpsText', + style: AppTypography.dataMono.copyWith( + fontSize: 13, + color: AppColors.onSurfaceVariant, + ), + ), + ], + ], + ); + } + + Widget _buildCheckinAction() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _pillButton( + label: '获取定位并签到', + icon: 'location', + background: AppColors.tertiary, + height: 46, + radius: 10, + loading: _checking, + onPressed: _onCheckin, + ), + const SizedBox(height: 10), + const Text( + '签到将记录当前时间与 GPS 坐标,请到达客户现场后操作', + style: TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ], + ); + } + + Widget _buildRecordCard() { + return XCard( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: Column( + children: [ + _textAreaField('现场情况', _spaceDesc, '记录配电房、设备与现场的实际情况...'), + _fieldDivider(), + _textAreaField('沟通纪要', _visitContent, '本次与客户沟通的主要内容...'), + _fieldDivider(), + _textAreaField('客户需求', _demands, '客户提出的需求与关注点...'), + ], + ), + ); + } + + Widget _fieldDivider() => + const Divider(height: 1, thickness: 1, color: AppColors.borderRule); + + Widget _textAreaField( + String label, + TextEditingController controller, + String hint, + ) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _fieldLabel(label), + const SizedBox(height: 8), + Container( + height: 84, + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: TextField( + controller: controller, + maxLines: null, + expands: true, + textAlignVertical: TextAlignVertical.top, + style: const TextStyle(fontSize: 15, color: AppColors.onSurface), + cursorColor: AppColors.primary, + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + hintText: hint, + hintStyle: const TextStyle( + fontSize: 15, + color: AppColors.textPlaceholder, + ), + ), + ), + ), + ], + ), + ); + } + + Widget _fieldLabel(String label) => Text( + label, + style: AppTypography.labelBold.copyWith(color: AppColors.onSurfaceVariant), + ); + + Widget _buildIntentCard() { + return XCard( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 14), + child: Row( + children: [ + for (var i = 0; i < visitIntentOptions.length; i++) ...[ + if (i > 0) const SizedBox(width: 10), + Expanded(child: _intentChip(visitIntentOptions[i])), + ], + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _fieldLabel('意向说明'), + const SizedBox(height: 8), + Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ), + child: TextField( + controller: _intentDesc, + style: const TextStyle( + fontSize: 15, + color: AppColors.onSurface, + ), + cursorColor: AppColors.primary, + decoration: const InputDecoration( + isDense: true, + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + hintText: '选填,补充判断依据', + hintStyle: TextStyle( + fontSize: 15, + color: AppColors.textPlaceholder, + ), + ), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _intentChip(ValueOption option) { + final active = _intentLevel == option.value; + return GestureDetector( + onTap: () => setState(() => _intentLevel = option.value), + child: Container( + height: 44, + alignment: Alignment.center, + decoration: BoxDecoration( + color: active ? AppColors.surfaceVariant : AppColors.surfaceBright, + border: Border.all( + color: active ? AppColors.primary : AppColors.borderRule, + ), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + option.label, + style: TextStyle( + fontSize: 13, + fontWeight: active ? FontWeight.w700 : FontWeight.w400, + color: active ? AppColors.primary : AppColors.onSurfaceVariant, + ), + ), + ), + ); + } + + Widget _buildPhotoGrid() { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + for (var i = 0; i < _photoSlots.length; i++) ...[ + if (i > 0) const SizedBox(width: 10), + Expanded(child: _photoSlot(i)), + ], + ], + ), + const SizedBox(height: 10), + const Row( + children: [ + XIcon('warning', size: 14, color: AppColors.outline), + SizedBox(width: 6), + Expanded( + child: Text( + '照片上传依赖对象存储服务,上传失败将无法提交', + style: TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ), + ], + ), + ], + ); + } + + Widget _photoSlot(int index) { + final slot = _photoSlots[index]; + final filled = slot.url.isNotEmpty; + return GestureDetector( + onTap: () => _onPhotoTap(index), + child: Container( + height: 120, + decoration: BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(12), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Stack( + fit: StackFit.expand, + children: [ + if (filled) + Image.network(slot.url, fit: BoxFit.cover) + else + Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const XIcon('camera', size: 28, color: AppColors.outline), + const SizedBox(height: 6), + Text( + '现场照片 ${index + 1}', + style: const TextStyle( + fontSize: 12, + color: AppColors.textMuted, + ), + ), + ], + ), + if (filled) + Positioned( + left: 0, + right: 0, + bottom: 0, + child: Container( + height: 28, + padding: const EdgeInsets.symmetric(horizontal: 10), + color: const Color(0x8C0D1C2C), + child: Row( + children: [ + Text( + '现场照片 ${index + 1}', + style: const TextStyle( + fontSize: 11, + color: Colors.white, + ), + ), + const Spacer(), + GestureDetector( + onTap: () => _removePhoto(index), + child: const XIcon( + 'delete', + size: 15, + color: Colors.white, + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _pillButton({ + required String label, + required String icon, + required Color background, + required VoidCallback onPressed, + bool loading = false, + double height = 48, + double radius = 9999, + double fontSize = 15, + bool shadow = false, + EdgeInsetsGeometry? margin, + }) { + return Padding( + padding: margin ?? EdgeInsets.zero, + child: Container( + height: height, + width: double.infinity, + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(radius), + boxShadow: shadow + ? const [ + BoxShadow( + color: Color(0x4D0054CD), + blurRadius: 16, + offset: Offset(0, 6), + ), + ] + : null, + ), + child: Material( + color: Colors.transparent, + borderRadius: BorderRadius.circular(radius), + child: InkWell( + onTap: loading ? null : onPressed, + borderRadius: BorderRadius.circular(radius), + child: Center( + child: loading + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + valueColor: AlwaysStoppedAnimation(Colors.white), + ), + ) + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + XIcon(icon, size: 18, color: Colors.white), + const SizedBox(width: 6), + Text( + label, + style: TextStyle( + fontSize: fontSize, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} + +/// `uni.showLoading({ title: '上传中...' })` 的等价实现。 +class _UploadingDialog extends StatelessWidget { + const _UploadingDialog(); + + @override + Widget build(BuildContext context) { + return const Dialog( + backgroundColor: Color(0xE60D1C2C), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10)), + ), + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 20, vertical: 16), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + valueColor: AlwaysStoppedAnimation(Colors.white), + ), + ), + SizedBox(width: 10), + Text( + '上传中...', + style: TextStyle(fontSize: 14, color: Colors.white), + ), + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/visit/presentation/visit_form_page.dart b/lib/features/visit/presentation/visit_form_page.dart new file mode 100644 index 0000000..7a3f5e6 --- /dev/null +++ b/lib/features/visit/presentation/visit_form_page.dart @@ -0,0 +1,550 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/format_util.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../auth/application/session_controller.dart'; +import '../../customer/data/customer_api.dart'; +import '../../customer/data/customer_models.dart'; +import '../../customer/data/user_api.dart'; +import '../data/visit_api.dart'; +import '../data/visit_models.dart'; + +/// 拜访新建 / 编辑页,对应 `pages/visit/form.vue`。 +class VisitFormPage extends ConsumerStatefulWidget { + const VisitFormPage({super.key, this.id}); + + /// 为空表示新增,否则为编辑。 + final int? id; + + @override + ConsumerState createState() => _VisitFormPageState(); +} + +class _VisitFormPageState extends ConsumerState { + final TextEditingController _subject = TextEditingController(); + final TextEditingController _visitPerson = TextEditingController(); + final TextEditingController _visitPhone = TextEditingController(); + final TextEditingController _visitContent = TextEditingController(); + + final List _typeLabels = visitTypeOptions.map((o) => o.label).toList(); + final List _modeLabels = visitModeOptions.map((o) => o.label).toList(); + final List _priorityLabels = + visitPriorityOptions.map((o) => o.label).toList(); + + List _customers = const []; + List _salesmen = const []; + + late final bool _isEdit; + late final bool _isAdmin; + + int? _customerId; + int _typeIndex = 0; + int _modeIndex = 0; + int _priorityIndex = 2; + int _salesmanIndex = -1; + String _planTime = ''; + String _planEndTime = ''; + bool _saving = false; + + @override + void initState() { + super.initState(); + _isEdit = widget.id != null; + final user = ref.read(sessionProvider).user; + _isAdmin = user?.isAdmin ?? false; + _planTime = todayStr(); + _visitPerson.text = user?.realName ?? ''; + _init(); + } + + @override + void dispose() { + _subject.dispose(); + _visitPerson.dispose(); + _visitPhone.dispose(); + _visitContent.dispose(); + super.dispose(); + } + + Future _init() async { + await _loadCustomers(); + if (_isAdmin) await _loadSalesmen(); + if (widget.id != null) await _loadDetail(); + } + + Future _loadCustomers() async { + try { + final res = await ref.read(customerApiProvider).options(); + if (res.isOk && res.data != null && mounted) { + setState(() => _customers = res.data!); + } + } catch (_) { + // 客户列表加载失败由保存前的校验兜底 + } + } + + Future _loadSalesmen() async { + try { + final list = await ref.read(userApiProvider).salesmanOptions(); + if (mounted) setState(() => _salesmen = list); + } catch (_) { + if (mounted) setState(() => _salesmen = const []); + } + } + + Future _loadDetail() async { + final res = await ref.read(visitApiProvider).detail(widget.id!); + if (!res.isOk || res.data == null) { + showAppToast(res.message.isNotEmpty ? res.message : '拜访记录不存在'); + return; + } + if (!mounted) return; + final detail = res.data!; + setState(() { + _customerId = detail.customerId; + _subject.text = detail.subject ?? ''; + _typeIndex = _indexOf( + visitTypeOptions, + detail.visitType ?? visitTypeOptions[0].value, + ); + _modeIndex = _indexOf( + visitModeOptions, + detail.visitMode ?? visitModeOptions[0].value, + ); + _priorityIndex = _indexOf( + visitPriorityOptions, + detail.priority ?? visitPriorityOptions[2].value, + ); + _planTime = detail.planTime != null && detail.planTime!.isNotEmpty + ? _dateOnly(detail.planTime!) + : todayStr(); + _planEndTime = _dateOnly(detail.planEndTime ?? ''); + _visitPerson.text = detail.visitPerson; + _visitPhone.text = detail.visitPhone ?? ''; + _visitContent.text = detail.visitContent ?? ''; + final index = _salesmen.indexWhere((s) => s.id == detail.salesmanId); + _salesmanIndex = index >= 0 ? index + 1 : -1; + + // 编辑时若客户不在可选范围内(如已终止),补充一条占位以正确回显 + if (detail.customerId != 0 && + !_customers.any((c) => c.id == detail.customerId)) { + _customers = [ + CustomerOption( + id: detail.customerId, + customerNo: detail.customer?.customerNo ?? '', + customerName: detail.customer?.customerName ?? '当前客户', + status: 0, + ), + ..._customers, + ]; + } + }); + } + + int _indexOf(List options, int value) { + final index = options.indexWhere((o) => o.value == value); + return index < 0 ? 0 : index; + } + + String _dateOnly(String value) => + value.length >= 10 ? value.substring(0, 10) : value; + + CustomerOption? get _selectedCustomer => + _customers.where((c) => c.id == _customerId).firstOrNull; + + String get _customerLabel { + final customer = _selectedCustomer; + if (customer == null) return ''; + return '${customer.customerName}' + '${customer.customerNo.isNotEmpty ? ' · ${customer.customerNo}' : ''}'; + } + + List get _customerLabels => _customers + .map( + (c) => + '${c.customerName}${c.customerNo.isNotEmpty ? ' · ${c.customerNo}' : ''}', + ) + .toList(); + + void _pickCustomer() { + final labels = _customerLabels; + if (labels.isEmpty) return; + final index = _customers.indexWhere((c) => c.id == _customerId); + _pickIndex(labels, index < 0 ? 0 : index, (i) { + setState(() => _customerId = _customers[i].id); + }); + } + + Future _pickIndex( + List labels, + int current, + ValueChanged onSelected, + ) async { + final index = await showModalBottomSheet( + context: context, + backgroundColor: AppColors.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.lg)), + ), + builder: (ctx) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + for (var i = 0; i < labels.length; i++) + ListTile( + title: Text( + labels[i], + style: AppTypography.bodyMd.copyWith(color: AppColors.onSurface), + ), + trailing: i == current + ? const XIcon('check', size: 18, color: AppColors.primary) + : null, + onTap: () => Navigator.of(ctx).pop(i), + ), + ], + ), + ), + ); + if (index != null) onSelected(index); + } + + Future _pickDate({required bool isStart}) async { + final initial = parseDate(isStart ? _planTime : _planEndTime) ?? DateTime.now(); + final picked = await showDatePicker( + context: context, + initialDate: initial, + firstDate: DateTime(2000), + lastDate: DateTime(2100), + ); + if (picked == null) return; + setState(() { + if (isStart) { + _planTime = formatDate(picked); + } else { + _planEndTime = formatDate(picked); + } + }); + } + + Future _onSave() async { + if (_customerId == null) { + showAppToast('请选择关联客户'); + return; + } + if (_planTime.isEmpty) { + showAppToast('请选择计划开始日期'); + return; + } + setState(() => _saving = true); + try { + final payload = { + 'customerId': _customerId, + 'subject': _subject.text, + 'visitType': visitTypeOptions[_typeIndex].value, + 'visitMode': visitModeOptions[_modeIndex].value, + 'priority': visitPriorityOptions[_priorityIndex].value, + 'planTime': _planTime, + 'planEndTime': _planEndTime, + 'visitPerson': _visitPerson.text, + 'visitPhone': _visitPhone.text, + 'visitContent': _visitContent.text, + }; + final salesmanId = + _salesmanIndex > 0 ? _salesmen[_salesmanIndex - 1].id : null; + if (_isAdmin && salesmanId != null) payload['salesmanId'] = salesmanId; + + final api = ref.read(visitApiProvider); + final res = _isEdit + ? await api.update(widget.id!, payload) + : await api.create(payload); + if (!mounted) return; + if (res.isOk) { + showAppToast('保存成功', success: true); + await Future.delayed(const Duration(milliseconds: 500)); + if (mounted) context.pop(); + } else { + showAppToast(res.message.isNotEmpty ? res.message : '保存失败'); + } + } catch (_) { + showAppToast('保存失败,请重试'); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + @override + Widget build(BuildContext context) { + final items = [ + _formItem(label: '关联客户', isRequired: true, child: _customerPicker()), + _formItem( + label: '拜访主题', + child: _input(_subject, '例如:配电房增容方案沟通'), + ), + _formItem( + label: '拜访类型', + child: _optionPicker( + _typeLabels, + _typeIndex, + (i) => setState(() => _typeIndex = i), + ), + ), + _formItem( + label: '拜访方式', + child: _optionPicker( + _modeLabels, + _modeIndex, + (i) => setState(() => _modeIndex = i), + ), + ), + _formItem( + label: '优先级', + child: _optionPicker( + _priorityLabels, + _priorityIndex, + (i) => setState(() => _priorityIndex = i), + ), + ), + _formItem( + label: '计划开始', + isRequired: true, + child: _datePicker( + _planTime, + '请选择计划开始日期', + () => _pickDate(isStart: true), + ), + ), + _formItem( + label: '计划结束', + child: _datePicker(_planEndTime, '选填', () => _pickDate(isStart: false)), + ), + _formItem(label: '拜访人', child: _input(_visitPerson, '默认当前登录用户')), + _formItem( + label: '联系电话', + child: _input(_visitPhone, '选填', number: true), + ), + if (_isAdmin) _formItem(label: '负责业务员', child: _salesmanPicker()), + _formItem( + label: '计划说明', + child: _textarea(_visitContent, '本次拜访的目标与重点事项...'), + ), + ]; + + final children = []; + for (var i = 0; i < items.length; i++) { + if (i > 0) { + children.add( + const Divider(height: 1, thickness: 1, color: AppColors.borderRule), + ); + } + children.add(items[i]); + } + + return XPageShell( + topBar: XTopBar.nav( + title: _isEdit ? '编辑拜访计划' : '新建拜访计划', + onBack: () => context.pop(), + ), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 60), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + XCard( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 16), + child: Column(children: children), + ), + XPrimaryButton( + label: '保存计划', + loading: _saving, + onPressed: _onSave, + margin: const EdgeInsets.fromLTRB(16, 24, 16, 40), + ), + ], + ), + ), + ); + } + + Widget _formItem({ + required String label, + bool isRequired = false, + required Widget child, + }) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + label, + style: AppTypography.labelBold.copyWith( + color: AppColors.onSurfaceVariant, + ), + ), + if (isRequired) + Text( + ' *', + style: AppTypography.labelBold.copyWith( + color: AppColors.statusError, + ), + ), + ], + ), + const SizedBox(height: 8), + child, + ], + ), + ); + } + + Widget _customerPicker() { + final label = _customerLabel; + final disabled = _isEdit || _customers.isEmpty; + return GestureDetector( + onTap: disabled ? null : _pickCustomer, + child: _pickerBox( + label.isNotEmpty + ? label + : (_customers.isNotEmpty ? '请选择客户' : '暂无客户可选'), + label.isEmpty, + _isEdit + ? null + : const XIcon('forward', size: 16, color: AppColors.outline), + ), + ); + } + + Widget _optionPicker( + List labels, + int index, + ValueChanged onSelected, + ) { + return GestureDetector( + onTap: () => _pickIndex(labels, index, onSelected), + child: _pickerBox( + labels[index], + false, + const XIcon('forward', size: 16, color: AppColors.outline), + ), + ); + } + + Widget _datePicker(String value, String placeholder, VoidCallback onPick) { + return GestureDetector( + onTap: onPick, + child: _pickerBox( + value.isNotEmpty ? value : placeholder, + value.isEmpty, + const XIcon('calendar', size: 16, color: AppColors.outline), + ), + ); + } + + Widget _salesmanPicker() { + final labels = ['默认本人', ..._salesmen.map((s) => s.optionLabel)]; + final index = _salesmanIndex; + final text = index >= 0 && index < labels.length ? labels[index] : '默认本人'; + return GestureDetector( + onTap: () => _pickIndex(labels, index < 0 ? 0 : index, (i) { + setState(() => _salesmanIndex = i); + }), + child: _pickerBox( + text, + index < 0, + const XIcon('forward', size: 16, color: AppColors.outline), + ), + ); + } + + Widget _pickerBox(String text, bool placeholder, Widget? trailing) { + return Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: _fieldDecoration, + child: Row( + children: [ + Expanded( + child: Text( + text, + style: TextStyle( + fontSize: 15, + color: placeholder + ? AppColors.textPlaceholder + : AppColors.onSurface, + ), + ), + ), + ?trailing, + ], + ), + ); + } + + Widget _input( + TextEditingController controller, + String hint, { + bool number = false, + }) { + return Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: _fieldDecoration, + child: Row( + children: [ + Expanded( + child: TextField( + controller: controller, + keyboardType: number ? TextInputType.number : TextInputType.text, + style: const TextStyle(fontSize: 15, color: AppColors.onSurface), + cursorColor: AppColors.primary, + decoration: _inputDecoration(hint), + ), + ), + ], + ), + ); + } + + Widget _textarea(TextEditingController controller, String hint) { + return Container( + height: 92, + padding: const EdgeInsets.fromLTRB(14, 12, 14, 12), + decoration: _fieldDecoration, + child: TextField( + controller: controller, + maxLines: null, + expands: true, + textAlignVertical: TextAlignVertical.top, + style: const TextStyle(fontSize: 15, color: AppColors.onSurface), + cursorColor: AppColors.primary, + decoration: _inputDecoration(hint), + ), + ); + } + + BoxDecoration get _fieldDecoration => BoxDecoration( + color: AppColors.surfaceBright, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(10), + ); + + InputDecoration _inputDecoration(String hint) => InputDecoration( + isDense: true, + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + hintText: hint, + hintStyle: const TextStyle(fontSize: 15, color: AppColors.textPlaceholder), + ); +} \ No newline at end of file diff --git a/lib/features/visit/presentation/visit_list_page.dart b/lib/features/visit/presentation/visit_list_page.dart new file mode 100644 index 0000000..5c08f19 --- /dev/null +++ b/lib/features/visit/presentation/visit_list_page.dart @@ -0,0 +1,553 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../core/utils/format_util.dart'; +import '../../../shared/widgets/app_feedback.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../data/visit_api.dart'; +import '../data/visit_models.dart'; + +/// 拜访列表页,对应 `pages/visit/list.vue`。 +class VisitListPage extends ConsumerStatefulWidget { + const VisitListPage({super.key}); + + @override + ConsumerState createState() => _VisitListPageState(); +} + +class _VisitListPageState extends ConsumerState { + static const int _pageSize = 10; + + final ScrollController _scrollController = ScrollController(); + final TextEditingController _keywordController = TextEditingController(); + + List _list = const []; + VisitStats _stats = VisitStats.empty; + int _total = 0; + int _page = 1; + bool _hasMore = true; + bool _loading = false; + + String _keyword = ''; + int? _filterStatus; + int? _filterPriority; + String _filterPlanDate = ''; + + Timer? _searchDebounce; + + @override + void initState() { + super.initState(); + _scrollController.addListener(_onScroll); + _reload(); + } + + @override + void dispose() { + _searchDebounce?.cancel(); + _scrollController.dispose(); + _keywordController.dispose(); + super.dispose(); + } + + void _onScroll() { + final position = _scrollController.position; + if (position.pixels >= position.maxScrollExtent - 200) _loadMore(); + } + + Future _loadStats() async { + try { + final res = await ref.read(visitApiProvider).stats(); + if (res.isOk && res.data != null && mounted) { + setState(() => _stats = res.data!); + } + } catch (_) { + // 统计失败不阻塞列表 + } + } + + Future _load({bool reset = false}) async { + if (_loading) return; + setState(() => _loading = true); + if (reset) { + _page = 1; + _hasMore = true; + } + try { + final res = await ref + .read(visitApiProvider) + .list( + page: _page, + pageSize: _pageSize, + keyword: _keyword.isEmpty ? null : _keyword, + status: _filterStatus, + priority: _filterPriority, + planStartDate: _filterPlanDate.isEmpty ? null : _filterPlanDate, + planEndDate: _filterPlanDate.isEmpty ? null : _filterPlanDate, + ); + if (res.isOk && res.data != null && mounted) { + final data = res.data!; + setState(() { + _list = reset ? data.list : [..._list, ...data.list]; + _total = data.total; + _hasMore = _list.length < data.total; + if (_hasMore) _page += 1; + }); + } + } catch (_) { + showAppToast('加载拜访记录失败'); + } finally { + if (mounted) setState(() => _loading = false); + } + } + + void _reload() { + _loadStats(); + _load(reset: true); + } + + void _loadMore() { + if (_hasMore && !_loading) _load(); + } + + Future _refresh() async { + await _loadStats(); + await _load(reset: true); + } + + void _onSearchChanged(String value) { + _keyword = value; + _searchDebounce?.cancel(); + _searchDebounce = Timer( + const Duration(milliseconds: 350), + () => _load(reset: true), + ); + } + + void _setStatus(int? value) { + if (_filterStatus == value) return; + setState(() { + _filterStatus = value; + _filterPlanDate = ''; + }); + _load(reset: true); + } + + void _setPriority(int? value) { + if (_filterPriority == value) return; + setState(() => _filterPriority = value); + _load(reset: true); + } + + void _quickStatus(int status) { + setState(() { + _filterPlanDate = ''; + _filterPriority = null; + _filterStatus = status; + }); + _load(reset: true); + } + + void _quickToday() { + setState(() { + _filterStatus = null; + _filterPriority = null; + _filterPlanDate = todayStr(); + }); + _load(reset: true); + } + + void _quickPriority() { + setState(() { + _filterPlanDate = ''; + _filterStatus = VisitStatus.pending; + _filterPriority = 1; + }); + _load(reset: true); + } + + String _findLabel(List options, int? value) { + if (value == null) return ''; + return options.where((o) => o.value == value).map((o) => o.label).firstOrNull ?? + ''; + } + + @override + Widget build(BuildContext context) { + return XPageShell( + topBar: XTopBar.nav( + title: '客户拜访', + onBack: () => context.pop(), + trailing: GestureDetector( + onTap: () => context.push('/visit/batch'), + behavior: HitTestBehavior.opaque, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const XIcon('calendar', size: 20, color: AppColors.primary), + const SizedBox(width: 4), + Text( + '批量安排', + style: AppTypography.labelBold.copyWith( + color: AppColors.primary, + ), + ), + ], + ), + ), + ), + child: Stack( + children: [ + RefreshIndicator( + onRefresh: _refresh, + color: AppColors.primary, + child: ListView( + controller: _scrollController, + padding: const EdgeInsets.fromLTRB(16, 12, 16, 140), + children: [ + _buildKpiGrid(), + const SizedBox(height: 14), + XSearchField( + controller: _keywordController, + hintText: '按单号、主题、拜访人搜索...', + onChanged: _onSearchChanged, + ), + const SizedBox(height: 8), + _buildFilters(), + ..._buildList(), + ], + ), + ), + Positioned(right: 20, bottom: 40, child: _buildFab()), + ], + ), + ); + } + + Widget _buildKpiGrid() { + return LayoutBuilder( + builder: (context, constraints) { + final width = (constraints.maxWidth - 10) / 2; + return Wrap( + spacing: 10, + runSpacing: 10, + children: [ + _kpiTile( + width, + '${_stats.pending}', + '待执行', + AppColors.primary, + () => _quickStatus(VisitStatus.pending), + ), + _kpiTile( + width, + '${_stats.todayPlan}', + '今日计划', + AppColors.tertiary, + _quickToday, + ), + _kpiTile( + width, + '${_stats.urgentPending}', + '加急待办', + AppColors.statusError, + _quickPriority, + ), + _kpiTile( + width, + '${_stats.conversionRate}%', + '转化率', + AppColors.secondary, + null, + ), + ], + ); + }, + ); + } + + Widget _kpiTile( + double width, + String value, + String label, + Color valueColor, + VoidCallback? onTap, + ) { + return GestureDetector( + onTap: onTap, + child: Container( + width: width, + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: AppColors.surface, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(AppRadius.lg), + boxShadow: const [ + BoxShadow(color: Color(0x0A000000), blurRadius: 8, offset: Offset(0, 2)), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + value, + style: AppTypography.dataMono.copyWith( + fontSize: 22, + fontWeight: FontWeight.w700, + color: valueColor, + ), + ), + const SizedBox(height: 2), + Text( + label, + style: const TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ], + ), + ), + ); + } + + Widget _buildFilters() { + return Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + _filterChip('全部', _filterStatus == null, () => _setStatus(null)), + for (final option in visitStatusOptions) + _filterChip( + option.label, + _filterStatus == option.value, + () => _setStatus(option.value), + ), + ], + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 6, bottom: 2), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + _filterChip( + '全部优先级', + _filterPriority == null, + () => _setPriority(null), + ), + for (final option in visitPriorityOptions) + _filterChip( + option.label, + _filterPriority == option.value, + () => _setPriority(option.value), + ), + ], + ), + ), + ), + ], + ), + ); + } + + Widget _filterChip(String label, bool selected, VoidCallback onTap) { + return Padding( + padding: const EdgeInsets.only(right: 8), + child: XFilterChip(label: label, selected: selected, onTap: onTap), + ); + } + + List _buildList() { + if (_loading && _list.isEmpty) { + return const [XPlaceholder(text: '加载中...')]; + } + if (_list.isEmpty) { + return const [XPlaceholder(text: '暂无拜访记录')]; + } + return [ + for (final visit in _list) _buildCard(visit), + _buildFooter(), + ]; + } + + Widget _buildCard(VisitInfo visit) { + final subject = visit.subject?.isNotEmpty == true + ? visit.subject! + : (visit.customer?.customerName?.isNotEmpty == true + ? visit.customer!.customerName! + : '未命名拜访'); + final customerName = visit.customer?.customerName?.isNotEmpty == true + ? visit.customer!.customerName! + : '未知客户'; + final typeText = _findLabel(visitTypeOptions, visit.visitType); + + return XCard( + clip: true, + margin: const EdgeInsets.only(top: 12), + onTap: () => context.push('/visit/detail/${visit.id}'), + child: Stack( + children: [ + Positioned( + left: 0, + top: 0, + bottom: 0, + child: Container(width: 4, color: visitStatusBarColor(visit.status)), + ), + Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + subject, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + ), + const SizedBox(width: 8), + XChip( + visitStatusText(visit.status), + tone: visitStatusTone(visit.status), + ), + ], + ), + const SizedBox(height: 8), + Row( + children: [ + const XIcon('groups', size: 15, color: AppColors.textMuted), + const SizedBox(width: 6), + Text( + customerName, + style: const TextStyle( + fontSize: 14, + color: AppColors.onSurfaceVariant, + ), + ), + if (typeText.isNotEmpty) ...[ + const SizedBox(width: 6), + XChip(typeText, tone: ChipTone.muted), + ], + ], + ), + const SizedBox(height: 8), + Row( + children: [ + _metaItem( + 'schedule', + visit.planTime != null && visit.planTime!.isNotEmpty + ? formatDateLabel(visit.planTime) + : '未排期', + ), + const SizedBox(width: 14), + _metaItem( + 'person', + visit.visitPerson.isNotEmpty ? visit.visitPerson : '-', + ), + ], + ), + ], + ), + ), + ), + Container( + width: 92, + color: AppColors.surfaceBright, + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + XChip( + visit.priority == null ? '' : visitPriorityText(visit.priority), + tone: visitPriorityTone(visit.priority), + ), + const SizedBox(height: 8), + Text( + visit.visitNo, + style: AppTypography.dataMono.copyWith( + fontSize: 10, + color: AppColors.textMuted, + ), + ), + ], + ), + ), + ], + ), + ], + ), + ); + } + + Widget _metaItem(String icon, String text) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + XIcon(icon, size: 15, color: AppColors.textMuted), + const SizedBox(width: 4), + Text( + text, + style: const TextStyle(fontSize: 13, color: AppColors.textMuted), + ), + ], + ); + } + + Widget _buildFooter() { + return Padding( + padding: const EdgeInsets.only(top: 16, bottom: 4), + child: Center( + child: Text( + _hasMore ? '加载中...' : '共 $_total 条', + style: const TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ), + ); + } + + Widget _buildFab() { + return GestureDetector( + onTap: () => context.push('/visit/form'), + child: Container( + width: 52, + height: 52, + decoration: BoxDecoration( + color: AppColors.primary, + borderRadius: BorderRadius.circular(14), + boxShadow: const [ + BoxShadow(color: Color(0x4D0054CD), blurRadius: 16, offset: Offset(0, 6)), + ], + ), + child: const Center(child: XIcon('add', size: 24, color: Colors.white)), + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/workbench/presentation/workbench_tab.dart b/lib/features/workbench/presentation/workbench_tab.dart new file mode 100644 index 0000000..0903e84 --- /dev/null +++ b/lib/features/workbench/presentation/workbench_tab.dart @@ -0,0 +1,651 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/tab_index.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../core/theme/app_dimens.dart'; +import '../../../core/theme/app_typography.dart'; +import '../../../shared/widgets/x_card.dart'; +import '../../../shared/widgets/x_chip.dart'; +import '../../../shared/widgets/x_common.dart'; +import '../../../shared/widgets/x_icon.dart'; +import '../../../shared/widgets/x_top_bar.dart'; +import '../../auth/application/session_controller.dart'; +import '../../auth/data/auth_models.dart'; +import '../../dashboard/data/dashboard_api.dart'; +import '../../dashboard/data/dashboard_models.dart'; + +enum _TaskType { survey, issue } + +/// 最近任务的展示模型,字段与源页面 `TaskItem` 一一对应。 +class _TaskItem { + const _TaskItem({ + required this.id, + required this.title, + required this.desc, + required this.time, + required this.type, + required this.high, + required this.completed, + required this.isLate, + }); + + final int id; + final String title; + final String desc; + final String time; + final _TaskType type; + final bool high; + final bool completed; + final bool isLate; +} + +/// 工作台 Tab,对应 `components/tabs/WorkbenchTab.vue`。 +class WorkbenchTab extends ConsumerStatefulWidget { + const WorkbenchTab({super.key}); + + @override + ConsumerState createState() => _WorkbenchTabState(); +} + +class _WorkbenchTabState extends ConsumerState { + int _activeProjects = 0; + int _newProjectsWeek = 0; + int _pendingTasks = 0; + int _urgentTasks = 0; + int _newAlarms = 0; + List<_TaskItem> _tasks = const []; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => _load()); + } + + Future _load() async { + try { + final res = await ref.read(dashboardApiProvider).stats(); + if (!mounted) return; + final dash = res.isOk ? res.data : null; + if (dash == null) return; + setState(() { + _activeProjects = dash.contractTotal; + _newProjectsWeek = dash.customerMonthlyNew; + _pendingTasks = dash.surveyPending; + _urgentTasks = dash.surveyPending; + _newAlarms = dash.surveyPending; + _tasks = dash.surveyList.map(_toTaskItem).toList(); + }); + } catch (_) { + // 静默刷新:请求失败时保留已渲染的数据 + } + } + + /// dashboard.surveyList 元素 → 最近任务(判定规则照抄源 `toTaskItem`)。 + _TaskItem _toTaskItem(DashboardSurveyItem s) { + // 状态 0待指派 1现场勘察中 2待技术复核 3已归档 5已取消 + final canceled = s.status == 5; + final archived = s.status == 3; + final pendingReview = s.status == 2; + final pendingAssign = s.status == 0; + // type 映射:勘察中/待指派 → survey;待复核 → issue;已归档/已取消 → issue + final type = (pendingReview || archived || canceled) + ? _TaskType.issue + : _TaskType.survey; + return _TaskItem( + id: s.id, + title: '${s.customerName}的勘察', + desc: s.locale.isNotEmpty ? s.locale : s.owner, + time: s.time, + type: type, + high: pendingAssign, + completed: archived || canceled, + isLate: canceled, + ); + } + + String _typeLabel(_TaskType type) => + type == _TaskType.survey ? '勘测' : '问题'; + + ChipTone _typeTone(_TaskType type) => + type == _TaskType.survey ? ChipTone.primary : ChipTone.error; + + Future _goSurvey() async { + await context.push('/survey'); + if (mounted) _load(); + } + + Future _goVisit() async { + await context.push('/visit'); + if (mounted) _load(); + } + + @override + Widget build(BuildContext context) { + ref.listen(tabIndexProvider, (previous, next) { + if (next == AppTab.workbench) _load(); + }); + + final user = ref.watch(sessionProvider).user; + final avatarText = user?.avatarText ?? '陈'; + final displayName = user?.displayName ?? '陈伟'; + final roleText = user == null ? '高级销售工程师' : roleLabel(user.roles); + final userNo = user == null + ? '工号: XT-8842' + : '工号: ${user.username.toUpperCase()}'; + + return XPageShell( + topBar: XTopBar.brand(title: '鑫潼智电', trailingIcon: 'notification'), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 120), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildUserCard(avatarText, displayName, roleText, userNo), + _buildStats(), + _buildQuickActions(), + _buildTasks(), + ], + ), + ), + ); + } + + Widget _buildUserCard( + String avatarText, + String displayName, + String roleText, + String userNo, + ) { + return XCard( + padding: const EdgeInsets.all(16), + margin: const EdgeInsets.only(bottom: 16), + child: Row( + children: [ + Container( + width: 56, + height: 56, + alignment: Alignment.center, + decoration: BoxDecoration( + color: AppColors.surfaceContainerHigh, + shape: BoxShape.circle, + border: Border.all(color: AppColors.primaryFixedDim, width: 2), + ), + child: Text( + avatarText, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.w700, + color: AppColors.primary, + ), + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(displayName, style: AppTypography.titleSm), + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + roleText, + style: const TextStyle( + fontSize: 12, + letterSpacing: 1, + color: AppColors.textMuted, + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 6), + child: Row( + children: [ + const XChip( + '在线', + tone: ChipTone.tertiary, + leading: _OnlineDot(), + ), + const SizedBox(width: 8), + Text( + userNo, + style: AppTypography.dataMono.copyWith( + color: AppColors.textMuted, + ), + ), + ], + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildStats() { + return Padding( + padding: const EdgeInsets.only(bottom: 24), + child: Column( + children: [ + IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: _statCard( + head: _statHead( + '进行中项目', + const XIcon('domain', size: 20, color: AppColors.primary), + ), + value: _statValue('$_activeProjects'), + foot: _statFoot( + children: [ + const XIcon( + 'trend-up', + size: 14, + color: AppColors.tertiaryContainer, + ), + const SizedBox(width: 4), + Text( + '本月新增客户 +$_newProjectsWeek', + style: const TextStyle( + fontSize: 12, + color: AppColors.tertiary, + ), + ), + ], + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: _statCard( + head: _statHead( + '待办任务', + const XIcon( + 'clock', + size: 20, + color: AppColors.statusWarn, + ), + ), + value: _statValue('$_pendingTasks'), + foot: _statFoot( + children: [ + Text( + '$_urgentTasks 项需立即处理', + style: const TextStyle( + fontSize: 12, + color: AppColors.statusWarn, + ), + ), + ], + ), + ), + ), + ], + ), + ), + const SizedBox(height: 12), + XCard( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _statHead( + '新告警', + const XIcon( + 'warning', + size: 20, + color: AppColors.statusError, + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + _statValue('$_newAlarms', color: AppColors.statusError), + GestureDetector( + onTap: _goSurvey, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 4, + ), + decoration: BoxDecoration( + color: const Color(0x14DC2626), + borderRadius: BorderRadius.circular(AppRadius.full), + ), + child: Text( + '查看', + style: AppTypography.labelBold.copyWith( + color: AppColors.statusError, + ), + ), + ), + ), + ], + ), + Padding( + padding: const EdgeInsets.only(top: 6), + child: const Text( + '待指派勘察单', + style: TextStyle(fontSize: 12, color: AppColors.textMuted), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _statCard({ + required Widget head, + required Widget value, + required Widget foot, + }) { + return XCard( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [head, value, foot], + ), + ); + } + + Widget _statHead(String label, Widget icon) { + return Container( + padding: const EdgeInsets.only(bottom: 12), + margin: const EdgeInsets.only(bottom: 8), + decoration: const BoxDecoration( + border: Border(bottom: BorderSide(color: AppColors.borderRule)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + label, + style: AppTypography.captionSm.copyWith( + color: AppColors.textMuted, + letterSpacing: 1, + ), + ), + icon, + ], + ), + ); + } + + Widget _statValue(String value, {Color? color}) { + return Text( + value, + style: AppTypography.displayLg.copyWith(height: 1, color: color), + ); + } + + Widget _statFoot({required List children}) { + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Row(children: children), + ); + } + + Widget _buildQuickActions() { + return Padding( + padding: const EdgeInsets.only(bottom: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('快捷操作', style: AppTypography.titleSm), + Padding( + padding: const EdgeInsets.only(top: 12), + child: Row( + children: [ + Expanded( + child: _quickItem( + '客户录入', + 'person-add', + const Color(0xFFE5EFFF), + const Color(0xFF0054CD), + () => ref + .read(tabIndexProvider.notifier) + .select(AppTab.customer), + ), + ), + Expanded( + child: _quickItem( + '勘查预约', + 'calendar', + const Color(0xFFEADDFF), + const Color(0xFF712AE2), + _goSurvey, + ), + ), + Expanded( + child: _quickItem( + '拜访记录', + 'check', + const Color(0x1A00685F), + const Color(0xFF008378), + _goVisit, + ), + ), + Expanded( + child: _quickItem( + '报表查看', + 'chart', + const Color(0x1A1D6FFF), + const Color(0xFF0C4DD1), + () => + ref.read(tabIndexProvider.notifier).select(AppTab.mine), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _quickItem( + String label, + String icon, + Color background, + Color color, + VoidCallback onTap, + ) { + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Column( + children: [ + Container( + width: 40, + height: 40, + alignment: Alignment.center, + decoration: BoxDecoration(color: background, shape: BoxShape.circle), + child: XIcon(icon, size: 22, color: color), + ), + const SizedBox(height: 8), + Text(label, style: AppTypography.captionSm), + ], + ), + ); + } + + Widget _buildTasks() { + // 外层保留卡片阴影,内层裁剪对应源样式的 `overflow: hidden`。 + return XCard( + padding: EdgeInsets.zero, + child: ClipRRect( + borderRadius: BorderRadius.circular(AppRadius.lg), + child: Column( + children: [ + Container( + padding: const EdgeInsets.all(18), + decoration: const BoxDecoration( + border: Border(bottom: BorderSide(color: AppColors.borderRule)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('最近任务', style: AppTypography.titleSm), + GestureDetector( + onTap: _goSurvey, + behavior: HitTestBehavior.opaque, + child: Row( + children: [ + Text( + '查看全部', + style: AppTypography.labelBold.copyWith( + color: AppColors.primary, + ), + ), + const SizedBox(width: 4), + const XIcon( + 'forward', + size: 14, + color: AppColors.primary, + ), + ], + ), + ), + ], + ), + ), + for (var i = 0; i < _tasks.length; i++) ...[ + if (i > 0) + const Divider( + height: 1, + thickness: 1, + color: AppColors.borderRule, + ), + _taskItem(_tasks[i]), + ], + ], + ), + ), + ); + } + + Widget _taskItem(_TaskItem task) { + final isIssue = task.type == _TaskType.issue; + final iconColor = isIssue + ? AppColors.statusError + : (task.completed ? AppColors.primary : AppColors.outline); + + return GestureDetector( + onTap: _goSurvey, + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 4), + child: XIcon( + isIssue ? 'warning' : 'check-circle', + size: 22, + color: iconColor, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + task.title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: AppColors.onSurface, + ), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: task.isLate + ? const Color(0x14DC2626) + : AppColors.surfaceContainer, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + task.time, + style: TextStyle( + fontSize: 12, + color: task.isLate + ? AppColors.statusError + : AppColors.textMuted, + ), + ), + ), + ], + ), + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + task.desc, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + color: AppColors.textMuted, + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 8), + child: Row( + children: [ + XChip(_typeLabel(task.type), tone: _typeTone(task.type)), + if (task.high) ...[ + const SizedBox(width: 8), + const XChip('高优先级', tone: ChipTone.warn), + ], + ], + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +/// 「在线」chip 左侧的状态圆点。 +class _OnlineDot extends StatelessWidget { + const _OnlineDot(); + + @override + Widget build(BuildContext context) { + return Container( + width: 7, + height: 7, + decoration: const BoxDecoration( + shape: BoxShape.circle, + color: AppColors.tertiary, + ), + ); + } +} \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..a7a0acd --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'app/app.dart'; +import 'core/providers.dart'; +import 'core/storage/token_storage.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // 与源项目一致:浅色背景 + 深色状态栏图标。 + SystemChrome.setSystemUIOverlayStyle( + const SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: Brightness.dark, + statusBarBrightness: Brightness.light, + ), + ); + + final storage = await TokenStorage.open(); + + runApp( + ProviderScope( + overrides: [tokenStorageProvider.overrideWithValue(storage)], + child: const SmartGridApp(), + ), + ); +} \ No newline at end of file diff --git a/lib/shared/widgets/app_feedback.dart b/lib/shared/widgets/app_feedback.dart new file mode 100644 index 0000000..61089ad --- /dev/null +++ b/lib/shared/widgets/app_feedback.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; + +import '../../core/app_keys.dart'; +import '../../core/theme/app_colors.dart'; +import '../../core/theme/app_dimens.dart'; +import '../../core/theme/app_typography.dart'; + +/// `uni.showToast({ title, icon })` 的等价实现。 +/// 不依赖调用方的 BuildContext,可在任意异步回调里安全使用。 +void showAppToast(String title, {bool success = false}) { + final messenger = AppKeys.scaffoldMessenger.currentState; + if (messenger == null) return; + messenger + ..clearSnackBars() + ..showSnackBar( + SnackBar( + content: Row( + children: [ + if (success) ...[ + const Icon( + Icons.check_circle, + size: 18, + color: AppColors.tertiaryFixed, + ), + const SizedBox(width: 8), + ], + Expanded( + child: Text( + title, + style: AppTypography.bodyMd.copyWith( + color: AppColors.surface, + ), + ), + ), + ], + ), + backgroundColor: AppColors.inverseSurface, + behavior: SnackBarBehavior.floating, + margin: const EdgeInsets.all(AppSpacing.md), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppRadius.lg), + ), + duration: Duration(milliseconds: success ? 1500 : 2200), + ), + ); +} + +/// `uni.showModal({ title, content })` 的等价实现,返回用户是否点了确认。 +Future showAppConfirm({ + required String title, + required String content, + String confirmText = '确定', + String cancelText = '取消', + bool destructive = false, +}) async { + final navigator = AppKeys.rootNavigator.currentState; + if (navigator == null) return false; + final result = await showDialog( + context: navigator.context, + builder: (ctx) => AlertDialog( + backgroundColor: AppColors.surface, + surfaceTintColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppRadius.lg), + ), + title: Text(title, style: AppTypography.titleSm), + content: Text( + content, + style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(false), + child: Text( + cancelText, + style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted), + ), + ), + TextButton( + onPressed: () => Navigator.of(ctx).pop(true), + child: Text( + confirmText, + style: AppTypography.bodyMd.copyWith( + fontWeight: FontWeight.w700, + color: destructive + ? AppColors.statusError + : AppColors.primary, + ), + ), + ), + ], + ), + ); + return result ?? false; +} \ No newline at end of file diff --git a/lib/shared/widgets/x_bottom_nav.dart b/lib/shared/widgets/x_bottom_nav.dart new file mode 100644 index 0000000..0148fdb --- /dev/null +++ b/lib/shared/widgets/x_bottom_nav.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; + +import '../../core/theme/app_colors.dart'; +import '../../core/theme/app_dimens.dart'; +import '../../core/theme/app_typography.dart'; +import 'x_icon.dart'; + +/// 底部悬浮胶囊导航,对应 `components/XBottomNav.vue`。 +/// +/// 距屏幕底部 12px(再叠加安全区),高 56,四周内边距 5, +/// 四个 tab 等宽均分;激活项铺满所在分格。 +class XBottomNav extends StatelessWidget { + const XBottomNav({ + super.key, + required this.current, + required this.onChanged, + }); + + final String current; + final ValueChanged onChanged; + + static const items = <({String key, String label, String icon})>[ + (key: 'workbench', label: '工作台', icon: 'dashboard'), + (key: 'customer', label: '客户', icon: 'groups'), + (key: 'project', label: '项目', icon: 'calendar'), + (key: 'mine', label: '我的', icon: 'person'), + ]; + + @override + Widget build(BuildContext context) { + final bottomInset = MediaQuery.paddingOf(context).bottom; + + return Padding( + padding: EdgeInsets.only( + left: 16, + right: 16, + bottom: 12 + bottomInset, + ), + child: Container( + height: 56, + padding: const EdgeInsets.all(5), + decoration: BoxDecoration( + color: AppColors.surface, + border: Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(AppRadius.full), + boxShadow: AppShadows.bottomNav, + ), + child: Row( + children: [ + for (final item in items) + Expanded( + child: GestureDetector( + onTap: () { + if (item.key == current) return; + onChanged(item.key); + }, + behavior: HitTestBehavior.opaque, + child: Container( + height: 44, + decoration: BoxDecoration( + color: item.key == current + ? AppColors.accentSubtle + : Colors.transparent, + borderRadius: BorderRadius.circular(AppRadius.full), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + XIcon( + item.icon, + size: 22, + color: item.key == current + ? AppColors.primary + : AppColors.textMuted, + ), + const SizedBox(height: 2), + Text( + item.label, + style: AppTypography.captionSm.copyWith( + color: item.key == current + ? AppColors.primary + : AppColors.textMuted, + ), + ), + ], + ), + ), + ), + ), + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/shared/widgets/x_card.dart b/lib/shared/widgets/x_card.dart new file mode 100644 index 0000000..0b74d35 --- /dev/null +++ b/lib/shared/widgets/x_card.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; + +import '../../core/theme/app_colors.dart'; +import '../../core/theme/app_dimens.dart'; + +/// 全局 `.card` 样式:白底 + 1px 描边 + 圆角 + 阴影。 +class XCard extends StatelessWidget { + const XCard({ + super.key, + required this.child, + this.padding, + this.margin, + this.radius, + this.clip = false, + this.onTap, + }); + + final Widget child; + final EdgeInsetsGeometry? padding; + final EdgeInsetsGeometry? margin; + final double? radius; + final bool clip; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + final r = BorderRadius.circular(radius ?? AppRadius.lg); + final content = Container( + padding: padding, + decoration: BoxDecoration( + color: AppColors.surface, + border: Border.all(color: AppColors.borderRule), + borderRadius: r, + boxShadow: AppShadows.card, + ), + child: child, + ); + + return Padding( + padding: margin ?? EdgeInsets.zero, + child: onTap == null + ? (clip ? ClipRRect(borderRadius: r, child: content) : content) + : Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + borderRadius: r, + child: clip + ? ClipRRect(borderRadius: r, child: content) + : content, + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/shared/widgets/x_chip.dart b/lib/shared/widgets/x_chip.dart new file mode 100644 index 0000000..e7ec561 --- /dev/null +++ b/lib/shared/widgets/x_chip.dart @@ -0,0 +1,88 @@ +import 'package:flutter/material.dart'; + +import '../../core/theme/app_colors.dart'; +import '../../core/theme/app_typography.dart'; + +/// 全局 `.chip` 样式:胶囊标签,2px 8px 内边距,12/14 粗体。 +class XChip extends StatelessWidget { + const XChip( + this.text, { + super.key, + this.tone = ChipTone.muted, + this.leading, + this.foreground, + this.background, + }); + + final String text; + final ChipTone tone; + + /// 前置装饰(如状态圆点) + final Widget? leading; + final Color? foreground; + final Color? background; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: background ?? tone.background, + borderRadius: BorderRadius.circular(9999), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (leading != null) ...[leading!, const SizedBox(width: 4)], + Text( + text, + style: AppTypography.captionSm.copyWith( + color: foreground ?? tone.foreground, + ), + ), + ], + ), + ); + } +} + +/// 可点选的筛选 chip(客户/项目列表顶部的过滤器)。 +class XFilterChip extends StatelessWidget { + const XFilterChip({ + super.key, + required this.label, + required this.selected, + required this.onTap, + this.background = AppColors.surface, + this.selectedBackground = AppColors.primaryContainer, + }); + + final String label; + final bool selected; + final VoidCallback onTap; + final Color background; + final Color selectedBackground; + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onTap, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: selected ? selectedBackground : background, + border: Border.all( + color: selected ? selectedBackground : AppColors.borderRule, + ), + borderRadius: BorderRadius.circular(9999), + ), + child: Text( + label, + style: AppTypography.captionSm.copyWith( + color: selected ? const Color(0xFFFEFCFF) : AppColors.onSurfaceVariant, + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/shared/widgets/x_common.dart b/lib/shared/widgets/x_common.dart new file mode 100644 index 0000000..54cfd52 --- /dev/null +++ b/lib/shared/widgets/x_common.dart @@ -0,0 +1,254 @@ +import 'package:flutter/material.dart'; + +import '../../core/theme/app_colors.dart'; +import '../../core/theme/app_dimens.dart'; +import '../../core/theme/app_typography.dart'; +import 'x_icon.dart'; + +/// 页面骨架:固定顶栏 + 可滚动内容区。 +/// +/// 对应 uni-app 版「根容器铺满且不滚动,滚动只发生在内容区 scroll-view」的固定高度布局, +/// 保证顶栏永远不动 —— 接近原生 App 的体验。 +class XPageShell extends StatelessWidget { + const XPageShell({ + super.key, + required this.topBar, + required this.child, + this.backgroundColor = AppColors.bgPage, + }); + + final Widget topBar; + final Widget child; + final Color backgroundColor; + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: backgroundColor, + body: Column( + children: [topBar, Expanded(child: child)], + ), + ); + } +} + +/// 搜索框,对应各页面 `.search-bar`。 +class XSearchField extends StatelessWidget { + const XSearchField({ + super.key, + required this.controller, + required this.hintText, + this.onChanged, + this.iconSize = 20, + this.height = 44, + this.radius = 12, + this.background = AppColors.surface, + this.iconColor = AppColors.textMuted, + this.filled = false, + }); + + final TextEditingController controller; + final String hintText; + final ValueChanged? onChanged; + final double iconSize; + final double height; + final double radius; + final Color background; + final Color iconColor; + final bool filled; + + @override + Widget build(BuildContext context) { + return Container( + height: height, + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: filled ? background : background, + border: filled ? null : Border.all(color: AppColors.borderRule), + borderRadius: BorderRadius.circular(radius), + ), + child: Row( + children: [ + XIcon('search', size: iconSize, color: iconColor), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: controller, + onChanged: onChanged, + style: const TextStyle( + fontSize: 15, + color: AppColors.onSurface, + ), + cursorColor: AppColors.primary, + decoration: InputDecoration( + isDense: true, + border: InputBorder.none, + hintText: hintText, + hintStyle: const TextStyle( + fontSize: 15, + color: AppColors.textPlaceholder, + ), + ), + ), + ), + ], + ), + ); + } +} + +/// 空态 / 加载中占位,对应 `.center` / `.empty-block`。 +class XPlaceholder extends StatelessWidget { + const XPlaceholder({ + super.key, + required this.text, + this.dashed = false, + this.padding = const EdgeInsets.symmetric(vertical: 60), + }); + + final String text; + final bool dashed; + final EdgeInsetsGeometry padding; + + @override + Widget build(BuildContext context) { + final label = Text( + text, + textAlign: TextAlign.center, + style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted), + ); + + if (!dashed) { + return Padding(padding: padding, child: Center(child: label)); + } + return Padding( + padding: padding, + child: Container( + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16), + decoration: BoxDecoration( + color: AppColors.surfaceBright, + borderRadius: BorderRadius.circular(AppRadius.lg), + border: Border.all(color: AppColors.borderRule), + ), + child: label, + ), + ); + } +} + +/// 实心主色按钮,对应 `.save-btn` / `.login-btn` 等胶囊按钮。 +class XPrimaryButton extends StatelessWidget { + const XPrimaryButton({ + super.key, + required this.label, + required this.onPressed, + this.loading = false, + this.height = 48, + this.margin, + this.background = AppColors.primary, + this.foreground = AppColors.onPrimary, + this.fontSize = 16, + this.pill = true, + this.borderColor, + }); + + final String label; + final VoidCallback? onPressed; + final bool loading; + final double height; + final EdgeInsetsGeometry? margin; + final Color background; + final Color foreground; + final double fontSize; + final bool pill; + final Color? borderColor; + + @override + Widget build(BuildContext context) { + final disabled = onPressed == null || loading; + + return Padding( + padding: margin ?? EdgeInsets.zero, + child: Opacity( + opacity: disabled && loading ? 0.85 : 1, + child: SizedBox( + height: height, + width: double.infinity, + child: Material( + color: background, + borderRadius: BorderRadius.circular(pill ? 9999 : AppRadius.lg), + child: InkWell( + onTap: disabled ? null : onPressed, + borderRadius: BorderRadius.circular(pill ? 9999 : AppRadius.lg), + child: Container( + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular( + pill ? 9999 : AppRadius.lg, + ), + border: borderColor == null + ? null + : Border.all(color: borderColor!), + ), + child: loading + ? SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + valueColor: AlwaysStoppedAnimation(foreground), + ), + ) + : Text( + label, + style: TextStyle( + fontSize: fontSize, + fontWeight: FontWeight.w700, + color: foreground, + ), + ), + ), + ), + ), + ), + ), + ); + } +} + +/// 分组小标题,对应 `.section-title`。 +class XSectionTitle extends StatelessWidget { + const XSectionTitle( + this.text, { + super.key, + this.icon, + this.iconColor = AppColors.primary, + this.fontSize = 17, + }); + + final String text; + final String? icon; + final Color iconColor; + final double fontSize; + + @override + Widget build(BuildContext context) { + if (icon == null) { + return Text( + text, + style: AppTypography.titleSm.copyWith(fontSize: fontSize), + ); + } + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + XIcon(icon!, size: fontSize, color: iconColor), + const SizedBox(width: 6), + Text( + text, + style: AppTypography.titleSm.copyWith(fontSize: fontSize), + ), + ], + ); + } +} \ No newline at end of file diff --git a/lib/shared/widgets/x_icon.dart b/lib/shared/widgets/x_icon.dart new file mode 100644 index 0000000..eea4a0d --- /dev/null +++ b/lib/shared/widgets/x_icon.dart @@ -0,0 +1,113 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_svg/flutter_svg.dart'; + +import '../../core/theme/app_colors.dart'; + +/// 图标组件,逐像素对应 uni-app 版 `components/XIcon.vue` 的 SVG 路径表。 +/// +/// 源实现把 SVG 拼成 data URI 交给背景图渲染(为绕过 uni-app 端 svg 命名空间问题), +/// Flutter 端直接用 [SvgPicture.string] 渲染同一份路径数据,视觉完全一致。 +class XIcon extends StatelessWidget { + const XIcon( + this.name, { + super.key, + this.size = 20, + this.color = AppColors.textMuted, + }); + + final String name; + final double size; + final Color color; + + /// 形状与 XIcon.vue 的 `ICONS` 一一对应,未做任何视觉改动。 + /// `currentColor` 在生成 SVG 时替换为 [color] 的实际色值。 + static const Map paths = { + 'dashboard': + '', + 'groups': + '', + 'calendar': + '', + 'person': '', + 'bolt': '', + 'search': + '', + 'add': '', + 'location': + '', + 'notification': + '', + 'back': + '', + 'forward': + '', + 'more': '', + 'domain': + '', + 'clock': + '', + 'warning': '', + 'camera': + '', + 'photo': + '', + 'send': '', + 'check': + '', + 'construction': + '', + 'verified': + '', + 'edit': '', + 'delete': '', + 'call': + '', + 'schedule': '', + 'filter': '', + 'chart': '', + 'check-circle': + '', + 'business': + '', + 'category': '', + 'person-add': + '', + 'trend-up': + '', + 'close': + '', + }; + + static final Map _svgCache = {}; + + static String _hex(Color color) => + '#${(color.toARGB32() & 0xFFFFFF).toRadixString(16).padLeft(6, '0')}'; + + /// 生成 (图标, 颜色) 组合对应的 SVG 字符串,带缓存避免重复拼接。 + static String svgFor(String name, Color color) { + final key = '$name|${color.toARGB32()}'; + return _svgCache.putIfAbsent(key, () { + // 兼容旧调用:borg 与 bolt 是同一个闪电图标 + final body = (paths[name] ?? paths['close']!).replaceAll( + 'currentColor', + _hex(color), + ); + return '$body'; + }); + } + + @override + Widget build(BuildContext context) { + return SizedBox( + width: size, + height: size, + child: SvgPicture.string( + svgFor(name, color), + width: size, + height: size, + fit: BoxFit.contain, + ), + ); + } +} \ No newline at end of file diff --git a/lib/shared/widgets/x_top_bar.dart b/lib/shared/widgets/x_top_bar.dart new file mode 100644 index 0000000..dfbefaf --- /dev/null +++ b/lib/shared/widgets/x_top_bar.dart @@ -0,0 +1,138 @@ +import 'package:flutter/material.dart'; + +import '../../core/theme/app_colors.dart'; +import '../../core/theme/app_typography.dart'; +import 'x_icon.dart'; + +/// 固定顶栏。对应各页面 `.topbar`:高 56 + 状态栏内边距,白底 + 1px 下边框。 +/// +/// 两种形态: +/// - [XTopBar.brand] 一级 Tab 顶栏:左侧闪电图标 + 品牌/模块名(左对齐),右侧通知图标 +/// - [XTopBar.nav] 二级页顶栏:左侧返回,中间标题,右侧操作位 +class XTopBar extends StatelessWidget { + const XTopBar._({ + required this.title, + required this.leading, + required this.trailing, + required this.titleStyle, + required this.titleAlign, + }); + + /// 一级 Tab 顶栏。 + factory XTopBar.brand({ + Key? key, + required String title, + Color iconColor = AppColors.primary, + String trailingIcon = 'notification', + Color trailingColor = AppColors.onSurfaceVariant, + VoidCallback? onTrailingTap, + }) { + return XTopBar._( + title: title, + leading: Row( + mainAxisSize: MainAxisSize.min, + children: [ + XIcon('bolt', size: 24, color: iconColor), + const SizedBox(width: 6), + Text( + title, + style: AppTypography.headlineMdMobile.copyWith( + color: iconColor, + letterSpacing: 1, + ), + ), + ], + ), + trailing: GestureDetector( + onTap: onTrailingTap, + behavior: HitTestBehavior.opaque, + child: XIcon(trailingIcon, size: 22, color: trailingColor), + ), + titleStyle: AppTypography.headlineMdMobile, + titleAlign: TextAlign.left, + ); + } + + /// 二级页顶栏:返回 + 居中标题 + 右侧操作位。 + factory XTopBar.nav({ + Key? key, + required String title, + VoidCallback? onBack, + Widget? trailing, + }) { + return XTopBar._( + title: title, + leading: GestureDetector( + onTap: onBack, + behavior: HitTestBehavior.opaque, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const XIcon('back', size: 22, color: AppColors.primary), + Text( + '返回', + style: AppTypography.labelBold.copyWith(color: AppColors.primary), + ), + ], + ), + ), + trailing: trailing ?? const SizedBox.shrink(), + titleStyle: AppTypography.headlineMdMobile, + titleAlign: TextAlign.center, + ); + } + + final String title; + final Widget leading; + final Widget trailing; + final TextStyle titleStyle; + final TextAlign titleAlign; + + @override + Widget build(BuildContext context) { + final topInset = MediaQuery.paddingOf(context).top; + final centered = titleAlign == TextAlign.center; + + return Container( + padding: EdgeInsets.only(top: topInset), + decoration: const BoxDecoration( + color: AppColors.surface, + border: Border(bottom: BorderSide(color: AppColors.borderRule)), + ), + child: SizedBox( + height: 56, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: centered + ? Row( + children: [ + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: leading, + ), + ), + Text(title, style: titleStyle), + Expanded( + child: Align( + alignment: Alignment.centerRight, + child: trailing, + ), + ), + ], + ) + : Row( + children: [ + leading, + const Spacer(), + Align( + alignment: Alignment.centerRight, + child: trailing, + ), + ], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..b6fd688 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,967 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d" + url: "https://pub.dev" + source: hosted + version: "93.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b + url: "https://pub.dev" + source: hosted + version: "10.0.1" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + cli_config: + dependency: transitive + description: + name: cli_config + sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec + url: "https://pub.dev" + source: hosted + version: "0.2.0" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + coverage: + dependency: transitive + description: + name: coverage + sha256: "956a3de0725ca232ad353565a8290d3357592bf4250f6f298a185e2d949c5d3d" + url: "https://pub.dev" + source: hosted + version: "1.15.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6 + url: "https://pub.dev" + source: hosted + version: "0.3.5+5" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + dbus: + dependency: transitive + description: + name: dbus + sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383 + url: "https://pub.dev" + source: hosted + version: "0.7.15" + dio: + dependency: "direct main" + description: + name: dio + sha256: "852ec3b48cc431ac04fff978413c541502b67ffc3e26921e74e3d994694192c1" + url: "https://pub.dev" + source: hosted + version: "5.11.1" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "3a1b2cd7be71086f38504956e3ebcd2837288d231ff454bafa78021244102bfc" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab + url: "https://pub.dev" + source: hosted + version: "0.9.4+1" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: d57c62362766b5e7ae739448650b66c6aab7a68ba7ecc65e04018652645ae0f4 + url: "https://pub.dev" + source: hosted + version: "0.9.5+1" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec + url: "https://pub.dev" + source: hosted + version: "0.9.3+6" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_localizations: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785" + url: "https://pub.dev" + source: hosted + version: "2.0.35" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "9255e1e3ad6e38906a1b4f8287678f95f378744c5b46b1985588543f3f19046e" + url: "https://pub.dev" + source: hosted + version: "3.3.2" + flutter_svg: + dependency: "direct main" + description: + name: flutter_svg + sha256: "35882981abcbfb8c15b286f0cd690ff25bac12d95eff3e25ee207f37d4c42e7f" + url: "https://pub.dev" + source: hosted + version: "2.3.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + geoclue: + dependency: transitive + description: + name: geoclue + sha256: c2a998c77474fc57aa00c6baa2928e58f4b267649057a1c76738656e9dbd2a7f + url: "https://pub.dev" + source: hosted + version: "0.1.1" + geolocator: + dependency: "direct main" + description: + name: geolocator + sha256: "4e41ad6bc072364ff01822531dac47936c065e5bf8f928f240a25bb51256ada0" + url: "https://pub.dev" + source: hosted + version: "14.1.1" + geolocator_android: + dependency: transitive + description: + name: geolocator_android + sha256: b449e3bd4ebdc7fcc1d8377848dd1486a07bfccd8eeff9c1bf66b1c6d8fde7d1 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + geolocator_apple: + dependency: transitive + description: + name: geolocator_apple + sha256: "853803d6bb1713c094e935b4a5ae5f19c0308acf81da13fa9ff84fb4c70c0b73" + url: "https://pub.dev" + source: hosted + version: "2.3.14" + geolocator_linux: + dependency: transitive + description: + name: geolocator_linux + sha256: "3da7420f11c3496511a5bd3c18fd67b88e5659f12e46b7ce00a788f6996e850a" + url: "https://pub.dev" + source: hosted + version: "0.2.6" + geolocator_platform_interface: + dependency: transitive + description: + name: geolocator_platform_interface + sha256: b640b6b687b14c66f51fe1130b1c2e8babbd408e0158052b92006b6675ca77fc + url: "https://pub.dev" + source: hosted + version: "4.4.0" + geolocator_web: + dependency: transitive + description: + name: geolocator_web + sha256: "19e485a0f8d6a88abcf9c53cba3a4105e14b7435ed8ac1c108c067b938fe8429" + url: "https://pub.dev" + source: hosted + version: "4.1.4" + geolocator_windows: + dependency: transitive + description: + name: geolocator_windows + sha256: "175435404d20278ffd220de83c2ca293b73db95eafbdc8131fe8609be1421eb6" + url: "https://pub.dev" + source: hosted + version: "0.2.5" + glob: + dependency: transitive + description: + name: glob + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + go_router: + dependency: "direct main" + description: + name: go_router + sha256: d7a3576cb312649eaa51f2356450aed686085fb58fcdebda5b359aa951eef7ea + url: "https://pub.dev" + source: hosted + version: "17.5.0" + gsettings: + dependency: transitive + description: + name: gsettings + sha256: "1b0ce661f5436d2db1e51f3c4295a49849f03d304003a7ba177d01e3a858249c" + url: "https://pub.dev" + source: hosted + version: "0.2.8" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: d8402284df184bc05f4a2210c6c23983b0720f4cd87cbd05c5390a78af602667 + url: "https://pub.dev" + source: hosted + version: "1.2.3" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: d5b3e1774af29c9ab00103afb0d4614070f924d2e0057ac867ec98800114793f + url: "https://pub.dev" + source: hosted + version: "0.8.13+17" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: "815921d05ef87d64dc64e9f7f855967614a9a67086d0c60fa27d47a1cd9a8896" + url: "https://pub.dev" + source: hosted + version: "0.8.13+9" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + intl: + dependency: transitive + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" + io: + dependency: transitive + description: + name: io + sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 + url: "https://pub.dev" + source: hosted + version: "2.1.0" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + package_info_plus: + dependency: transitive + description: + name: package_info_plus + sha256: "127e1751e37ffb2ff4658beeaca77bad0c27bf5f932bd3a501c2296926d4b481" + url: "https://pub.dev" + source: hosted + version: "10.2.1" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 + url: "https://pub.dev" + source: hosted + version: "4.1.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" + url: "https://pub.dev" + source: hosted + version: "1.5.3" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "17100416c51db7810c71a7bb2c34d1f881faa0074fd452afb0c4db6f8f126c76" + url: "https://pub.dev" + source: hosted + version: "3.3.2" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.dev" + source: hosted + version: "2.5.5" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + url: "https://pub.dev" + source: hosted + version: "2.4.23" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea" + url: "https://pub.dev" + source: hosted + version: "2.5.7" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 + url: "https://pub.dev" + source: hosted + version: "1.1.3" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b + url: "https://pub.dev" + source: hosted + version: "2.1.2" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "14c2945847669b44089bb1222f66873d7ff7103c58911917f2a63c5a62327898" + url: "https://pub.dev" + source: hosted + version: "0.10.14" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test: + dependency: transitive + description: + name: test + sha256: "280d6d890011ca966ad08df7e8a4ddfab0fb3aa49f96ed6de56e3521347a9ae7" + url: "https://pub.dev" + source: hosted + version: "1.30.0" + test_api: + dependency: transitive + description: + name: test_api + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + url: "https://pub.dev" + source: hosted + version: "0.7.10" + test_core: + dependency: transitive + description: + name: test_core + sha256: "0381bd1585d1a924763c308100f2138205252fb90c9d4eeaf28489ee65ccde51" + url: "https://pub.dev" + source: hosted + version: "0.6.16" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + uuid: + dependency: transitive + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + vector_graphics: + dependency: transitive + description: + name: vector_graphics + sha256: "9d0e3b9cb16542ad660daee871e726a10d13a93b7b5391677c3160e8f5e83935" + url: "https://pub.dev" + source: hosted + version: "1.2.3" + vector_graphics_codec: + dependency: transitive + description: + name: vector_graphics_codec + sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146" + url: "https://pub.dev" + source: hosted + version: "1.1.13" + vector_graphics_compiler: + dependency: transitive + description: + name: vector_graphics_compiler + sha256: "4dca4feb77dc3ec7f6e27e49c53241eb8217f55e4f9b12599a27f8903bca5682" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0" + url: "https://pub.dev" + source: hosted + version: "15.3.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + win32: + dependency: transitive + description: + name: win32 + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d + url: "https://pub.dev" + source: hosted + version: "6.4.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4" + url: "https://pub.dev" + source: hosted + version: "7.0.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" +sdks: + dart: ">=3.11.5 <4.0.0" + flutter: ">=3.41.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..6aff5c2 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,98 @@ +name: smart_grid_iot_manage_app_flutter +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.11.5 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + flutter_localizations: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + flutter_riverpod: ^3.3.2 + go_router: ^17.5.0 + dio: ^5.11.1 + shared_preferences: ^2.5.5 + image_picker: ^1.2.3 + geolocator: ^14.1.1 + flutter_svg: ^2.3.0 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..57ada67 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,25 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:smart_grid_iot_manage_app_flutter/app/app.dart'; +import 'package:smart_grid_iot_manage_app_flutter/core/providers.dart'; +import 'package:smart_grid_iot_manage_app_flutter/core/storage/token_storage.dart'; + +void main() { + testWidgets('未登录时进入登录页', (WidgetTester tester) async { + SharedPreferences.setMockInitialValues({}); + final storage = await TokenStorage.open(); + + await tester.pumpWidget( + ProviderScope( + overrides: [tokenStorageProvider.overrideWithValue(storage)], + child: const SmartGridApp(), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('鑫潼智电'), findsOneWidget); + expect(find.text('登 录'), findsOneWidget); + }); +} \ No newline at end of file