punchin.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
  4. import 'package:amap_location_flutter_plugin/amap_location_option.dart';
  5. import 'package:chewie/chewie.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:flutter_screenutil/flutter_screenutil.dart';
  9. import 'package:image_picker/image_picker.dart';
  10. import 'package:liftmanager/internal/wode/wode_router.dart';
  11. import 'package:liftmanager/net/api_service.dart';
  12. import 'package:liftmanager/res/colors.dart';
  13. import 'package:liftmanager/routers/fluro_navigator.dart';
  14. import 'package:liftmanager/utils/fast_notification.dart';
  15. import 'package:liftmanager/utils/oss_upload.dart';
  16. import 'package:liftmanager/utils/theme_utils.dart';
  17. import 'package:liftmanager/utils/toast.dart';
  18. import 'package:liftmanager/utils/utils.dart';
  19. import 'package:liftmanager/widgets/app_bar.dart';
  20. import 'package:liftmanager/widgets/selected_video_change.dart';
  21. import 'package:orientation/orientation.dart';
  22. import 'package:permission_handler/permission_handler.dart';
  23. import 'package:video_player/video_player.dart';
  24. class Punchin extends StatefulWidget {
  25. Punchin(this.id);
  26. final String id;
  27. @override
  28. State<StatefulWidget> createState() {
  29. return PunchinState();
  30. }
  31. }
  32. class PunchinState extends State<Punchin> {
  33. String videoUrl;
  34. String str;
  35. String imagesUrl;
  36. double percent = 0.0;
  37. Map<String, Object> _locationResult;
  38. StreamSubscription<Map<String, Object>> _locationListener;
  39. AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();
  40. var latitude;
  41. var longitude;
  42. String address;
  43. @override
  44. void initState() {
  45. super.initState();
  46. ///移除定位监听
  47. if (null != _locationListener) {
  48. _locationListener.cancel();
  49. }
  50. ///销毁定位
  51. if (null != _locationPlugin) {
  52. _locationPlugin.destroy();
  53. }
  54. _locationListener = _locationPlugin
  55. .onLocationChanged()
  56. .listen((Map<String, Object> result) {
  57. setState(() {
  58. _locationPlugin.stopLocation();
  59. _locationResult = result;
  60. // address latitude longitude
  61. latitude = _locationResult["latitude"];
  62. longitude = _locationResult["longitude"];
  63. address = _locationResult["address"];
  64. });
  65. });
  66. initGetLocation();
  67. }
  68. void _setLocationOption() {
  69. if (null != _locationPlugin) {
  70. AMapLocationOption locationOption = new AMapLocationOption();
  71. ///是否单次定位
  72. locationOption.onceLocation = true;
  73. ///是否需要返回逆地理信息
  74. locationOption.needAddress = true;
  75. ///逆地理信息的语言类型
  76. locationOption.geoLanguage = GeoLanguage.DEFAULT;
  77. ///设置Android端连续定位的定位间隔
  78. locationOption.locationInterval = 20000;
  79. ///设置Android端的定位模式<br>
  80. ///可选值:<br>
  81. ///<li>[AMapLocationMode.Battery_Saving]</li>
  82. ///<li>[AMapLocationMode.Device_Sensors]</li>
  83. ///<li>[AMapLocationMode.Hight_Accuracy]</li>
  84. locationOption.locationMode = AMapLocationMode.Hight_Accuracy;
  85. ///设置iOS端的定位最小更新距离<br>
  86. locationOption.distanceFilter = -1;
  87. ///设置iOS端期望的定位精度
  88. /// 可选值:<br>
  89. /// <li>[DesiredAccuracy.Best] 最高精度</li>
  90. /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
  91. /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
  92. /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
  93. /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
  94. locationOption.desiredAccuracy = DesiredAccuracy.NearestTenMeters;
  95. ///设置iOS端是否允许系统暂停定位
  96. locationOption.pausesLocationUpdatesAutomatically = false;
  97. ///将定位参数设置给定位插件
  98. _locationPlugin.setLocationOption(locationOption);
  99. }
  100. }
  101. VideoPlayerController _controller;
  102. VideoPlayerController _controllerFile;
  103. ChewieController _chewieController;
  104. ///选择图片
  105. void selectPicker() {
  106. showDialog(
  107. context: context,
  108. builder: (BuildContext context) {
  109. return SimpleDialog(
  110. title: Text("选择方式"),
  111. children: ["拍照", '从手机相册选择'].map((String value) {
  112. print("$value");
  113. return SimpleDialogOption(
  114. child: Text(
  115. "${value}",
  116. style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
  117. ),
  118. onPressed: () {
  119. _getImage(value == '拍照' ? 1 : 0);
  120. Navigator.of(context).pop();
  121. },
  122. );
  123. }).toList(),
  124. );
  125. },
  126. );
  127. }
  128. void _getImage(int key) async {
  129. print(key);
  130. print(333);
  131. try {
  132. await ImagePicker.pickVideo(
  133. source: key == 1 ? ImageSource.camera : ImageSource.gallery,
  134. ).then((File f) async {
  135. if (f != null) {
  136. _controllerFile = VideoPlayerController.file(f);
  137. _controllerFile.initialize().then((val) {
  138. _controllerFile.setLooping(true);
  139. int seconds = _controllerFile.value.duration.inSeconds;
  140. print("视频时长:$seconds");
  141. int fileSize = f.lengthSync(); //单位B
  142. print("视频大小:${fileSize}");
  143. print("视频大小:${f.path}");
  144. if (seconds <= 300) {
  145. _uploadImage(f.path);
  146. // upLoadFileOnce(_imageFile.path);
  147. // setState(() {});
  148. } else {
  149. toasts("视频时长不能大于5分钟!");
  150. }
  151. }).catchError((error) {
  152. print(error);
  153. print("error");
  154. toasts("上传失败,不支持此格式");
  155. });
  156. }
  157. });
  158. } catch (e) {
  159. toasts("没有权限,无法打开相册!");
  160. }
  161. }
  162. upLoadFileOnce(path) {
  163. showLoading(context, "正在上传...");
  164. NewApiService().upload(path, onSuccess: (res) {
  165. dismissLoading(context);
  166. setState(() {
  167. videoUrl = res.pathUrl;
  168. imagesUrl = res.coverUrl;
  169. settingVideoVc();
  170. });
  171. }, onError: (code, msg) {
  172. dismissLoading(context);
  173. toasts(msg);
  174. });
  175. }
  176. void _uploadImage(filePath) async {
  177. showPercent(context, () {
  178. dismissLoading(context);
  179. toasts("上传失败");
  180. }, () {
  181. if (videoUrl == null && str != null) {
  182. setState(() {
  183. videoUrl = str;
  184. settingVideoVc();
  185. print("videoUrl:" + videoUrl);
  186. dismissLoading(context);
  187. toasts("上传成功");
  188. });
  189. }
  190. });
  191. String uploadName = OssUtil.instance.getImageUploadName(filePath);
  192. await NewApiService.uploadImage(context, uploadName, filePath).then((data) {
  193. if (data.statusCode == 200) {
  194. str = NewApiUrl.URL_UPLOAD_IMAGE_OSS + "/" + uploadName;
  195. print("str:" + str);
  196. print(videoUrl);
  197. if (str != null) {
  198. Map obj = {"uploadName": uploadName, "success": true};
  199. FastNotification.push("percent", obj);
  200. }
  201. } else {
  202. Map obj = {"uploadName": uploadName, "success": false};
  203. FastNotification.push("percent", obj);
  204. }
  205. }).catchError((data) {
  206. Map obj = {"uploadName": uploadName, "success": false};
  207. FastNotification.push("percent", obj);
  208. });
  209. }
  210. settingVideoVc() {
  211. _controller?.pause();
  212. _controller?.dispose();
  213. _chewieController?.dispose();
  214. _controller = VideoPlayerController.network(Utils.getImagePath(videoUrl)
  215. // imgFontUrl + detailObj.url
  216. );
  217. _chewieController = ChewieController(
  218. videoPlayerController:
  219. // VideoPlayerController.network(
  220. // imgFontUrl + detailObj.url
  221. // ),
  222. _controller,
  223. aspectRatio: 3 / 2,
  224. autoPlay: false,
  225. looping: true,
  226. showControls: true,
  227. deviceOrientationsAfterFullScreen: [
  228. DeviceOrientation.portraitUp,
  229. ],
  230. // 占位图
  231. // placeholder: Image.network(
  232. // imgFontUrl+detailObj.cover,
  233. // fit: BoxFit.contain,
  234. // ),
  235. // 是否在 UI 构建的时候就加载视频
  236. autoInitialize: true,
  237. // 拖动条样式颜色
  238. materialProgressColors: new ChewieProgressColors(
  239. playedColor: Colors.red,
  240. handleColor: Colors.blue,
  241. backgroundColor: Colors.grey,
  242. bufferedColor: Colors.lightGreen,
  243. ),
  244. );
  245. }
  246. // 获取位置信息
  247. initGetLocation() async {
  248. if (await requestPermission()) {
  249. if (null != _locationPlugin) {
  250. ///开始定位之前设置定位参数
  251. _setLocationOption();
  252. _locationPlugin.startLocation();
  253. }
  254. }
  255. }
  256. // 获取定位权限
  257. Future<bool> requestPermission() async {
  258. final permissions = await PermissionHandler()
  259. .requestPermissions([PermissionGroup.location]);
  260. if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
  261. return true;
  262. } else {
  263. toasts('需要定位权限!');
  264. return false;
  265. }
  266. }
  267. // 获取位置信息
  268. Future<void> getLocation() async {
  269. if (await requestPermission()) {
  270. if (null != _locationPlugin) {
  271. ///开始定位之前设置定位参数
  272. _setLocationOption();
  273. _locationPlugin.startLocation();
  274. if (longitude != null && latitude != null) {
  275. if (videoUrl == null || videoUrl == '') {
  276. toasts("请上传视频");
  277. return;
  278. }
  279. showLoading(context);
  280. NewApiService().chargeToClock({
  281. "id": widget.id,
  282. "lng": longitude,
  283. "lat": latitude,
  284. "beforeRepair": videoUrl,
  285. }, onSuccess: (res) {
  286. dismissLoading(context);
  287. toasts("确认打卡成功");
  288. if (_controller != null) {
  289. _controller.pause();
  290. }
  291. NavigatorUtils.push(
  292. context, "${WodeRouter.orderPageMaster}?checkType=0");
  293. setState(() {});
  294. }, onError: (code, msg) {
  295. dismissLoading(context);
  296. toasts(msg);
  297. });
  298. }
  299. }
  300. }
  301. }
  302. submitApply() {
  303. getLocation();
  304. }
  305. // 文本编辑控制
  306. GlobalKey _formKey = new GlobalKey<FormState>();
  307. @override
  308. void dispose() {
  309. _controller?.pause();
  310. _controller?.dispose();
  311. _chewieController?.dispose();
  312. ///移除定位监听
  313. if (null != _locationListener) {
  314. _locationListener.cancel();
  315. }
  316. ///销毁定位
  317. if (null != _locationPlugin) {
  318. _locationPlugin.destroy();
  319. }
  320. // SystemChrome.setPreferredOrientations([
  321. // DeviceOrientation.portraitUp,
  322. // ]);
  323. OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
  324. super.dispose();
  325. }
  326. @override
  327. Widget build(BuildContext context) {
  328. double width = MediaQuery.of(context).size.width;
  329. double height = MediaQuery.of(context).size.height;
  330. if (width > height) {
  331. // SystemChrome.setPreferredOrientations([
  332. // DeviceOrientation.portraitUp,
  333. // ]);
  334. OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
  335. }
  336. return Scaffold(
  337. resizeToAvoidBottomPadding: false, //不让键盘弹上去
  338. appBar: MyAppBar(
  339. centerTitle: "打卡",
  340. ),
  341. body: Container(
  342. child: ListView(
  343. children: <Widget>[
  344. Form(
  345. key: _formKey, //设置globalKey,用于后面获取FormState
  346. // autovalidate: true, //开启自动校验
  347. child: Column(
  348. children: <Widget>[
  349. Container(
  350. width: width,
  351. padding: EdgeInsets.only(left: 15, top: 15, bottom: 15),
  352. child: Text(
  353. "(建议时长3分钟,建议大小50M)",
  354. style: TextStyle(
  355. color: Colors.red,
  356. fontSize: ScreenUtil().setSp(14),
  357. ),
  358. textAlign: TextAlign.left,
  359. ),
  360. ),
  361. Container(
  362. color: ThemeUtils.getDialogTextFieldColor(context),
  363. child: GridView.builder(
  364. shrinkWrap: true,
  365. padding: const EdgeInsets.fromLTRB(8.0, 12, 8.0, 12.0),
  366. physics: NeverScrollableScrollPhysics(),
  367. gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  368. crossAxisCount: 1, childAspectRatio: 1.18),
  369. itemCount: 1,
  370. itemBuilder: (_, index) {
  371. return Stack(
  372. children: <Widget>[
  373. Center(
  374. child: SelectedVideo(
  375. image: videoUrl,
  376. index: index,
  377. videoPlay: videoPlay(),
  378. onTap: () {
  379. if (videoUrl == null) {
  380. selectPicker();
  381. }
  382. },
  383. ),
  384. ),
  385. videoUrl != null
  386. ? Positioned(
  387. top: 0,
  388. right: 0,
  389. child: GestureDetector(
  390. onTap: () {
  391. setState(() {
  392. videoUrl = null;
  393. str = null;
  394. _controller.pause();
  395. // player.reset();
  396. });
  397. },
  398. child: Icon(
  399. const IconData(0xe651,
  400. fontFamily: "Iconfont"),
  401. size: 24.0,
  402. color: Color(0xff999999),
  403. ),
  404. ),
  405. )
  406. : Container(
  407. child: null,
  408. )
  409. ],
  410. );
  411. },
  412. ),
  413. ),
  414. Container(
  415. width: width,
  416. padding: EdgeInsets.all(15),
  417. child: Text(
  418. "当前打卡位置:" + (address ?? ""),
  419. textAlign: TextAlign.start,
  420. ),
  421. ),
  422. Container(
  423. height: ScreenUtil().setWidth(44),
  424. decoration: BoxDecoration(
  425. color: Colours.blue_app_main,
  426. borderRadius:
  427. BorderRadius.circular(ScreenUtil().setWidth(22)),
  428. // gradient: const LinearGradient(
  429. // colors: [Color(0xFF00D9FF), Color(0xFF0287FF)]),
  430. ),
  431. margin: EdgeInsets.all(20.0),
  432. width: double.infinity,
  433. child: FlatButton(
  434. // padding: EdgeInsets.all(15.0),
  435. child: Text("提交"),
  436. // color: Theme
  437. // .of(context)
  438. // .primaryColor,
  439. textColor: Colors.white,
  440. onPressed: () {
  441. /*
  442. * 如果:context不对。可以使用GlobalKey,
  443. * 通过_formKey.currentState 获取FormState后,
  444. * 调用validate()方法校验用户名密码是否合法,校验
  445. * 通过后再提交数据。
  446. */
  447. if ((_formKey.currentState as FormState).validate()) {
  448. submitApply();
  449. }
  450. },
  451. ),
  452. ),
  453. ],
  454. ),
  455. ),
  456. ],
  457. ),
  458. ),
  459. );
  460. }
  461. Widget videoPlay() {
  462. double width = MediaQuery.of(context).size.width;
  463. if (_controller == null) return Container();
  464. return Container(
  465. width: width,
  466. height: width * 2 / 3,
  467. padding: EdgeInsets.only(
  468. left: ScreenUtil().setWidth(15),
  469. right: ScreenUtil().setWidth(15),
  470. top: ScreenUtil().setWidth(15)),
  471. child: ClipRRect(
  472. borderRadius: BorderRadius.circular(5),
  473. child: new Chewie(controller: _chewieController),
  474. ));
  475. }
  476. }