punchin.dart 17 KB

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