punchin.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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:flutter/material.dart';
  6. import 'package:liftmanager/net/api_service.dart';
  7. import 'package:liftmanager/utils/toast.dart';
  8. import 'package:liftmanager/widgets/app_bar.dart';
  9. import 'package:liftmanager/routers/fluro_navigator.dart';
  10. import 'package:liftmanager/widgets/selected_video_change.dart';
  11. import 'package:image_picker/image_picker.dart';
  12. import 'package:flutter_screenutil/flutter_screenutil.dart';
  13. import 'package:liftmanager/internal/wode/wode_router.dart';
  14. import 'package:permission_handler/permission_handler.dart';
  15. import 'package:liftmanager/utils/theme_utils.dart';
  16. import 'package:liftmanager/utils/url.dart';
  17. import 'package:liftmanager/utils/utils.dart';
  18. import 'package:video_player/video_player.dart';
  19. import 'package:chewie/chewie.dart';
  20. import 'package:flutter/services.dart';
  21. import 'package:orientation/orientation.dart';
  22. import 'package:liftmanager/utils/fast_notification.dart';
  23. import 'package:liftmanager/utils/oss_upload.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. ///选择图片
  104. void selectPicker() {
  105. showDialog(
  106. context: context,
  107. builder: (BuildContext context) {
  108. return SimpleDialog(
  109. title: Text("选择方式"),
  110. children: ["拍照", '从手机相册选择'].map((String value) {
  111. print("$value");
  112. return SimpleDialogOption(
  113. child: Text(
  114. "${value}",
  115. style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
  116. ),
  117. onPressed: () {
  118. _getImage(value == '拍照' ? 1 : 0);
  119. Navigator.of(context).pop();
  120. },
  121. );
  122. }).toList(),
  123. );
  124. },
  125. );
  126. }
  127. void _getImage(int key) async {
  128. print(key);
  129. print(333);
  130. try {
  131. await ImagePicker.pickVideo(
  132. source: key == 1 ? ImageSource.camera : ImageSource.gallery,
  133. )
  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. });}
  152. })
  153. ;
  154. } catch (e) {
  155. toasts("没有权限,无法打开相册!");
  156. }
  157. }
  158. upLoadFileOnce(path) {
  159. showLoading(context, "正在上传...");
  160. NewApiService().upload(path, onSuccess: (res) {
  161. dismissLoading(context);
  162. setState(() {
  163. videoUrl = res.pathUrl;
  164. imagesUrl = res.coverUrl;
  165. });
  166. }, onError: (code, msg) {
  167. dismissLoading(context);
  168. toasts(msg);
  169. });
  170. }
  171. void _uploadImage(filePath) async {
  172. showPercent(context, (){
  173. dismissLoading(context);
  174. toasts("上传失败");
  175. },(){
  176. if(videoUrl == null && str != null){
  177. setState(() {
  178. videoUrl = str;
  179. print("videoUrl:"+videoUrl);
  180. dismissLoading(context);
  181. toasts("上传成功");
  182. });
  183. }
  184. });
  185. String uploadName = OssUtil.instance.getImageUploadName(filePath);
  186. await NewApiService.uploadImage(context, uploadName, filePath).then((data) {
  187. if (data.statusCode == 200) {
  188. str = NewApiUrl.URL_UPLOAD_IMAGE_OSS + "/" + uploadName;
  189. print("str:"+str);
  190. print(videoUrl);
  191. if(str != null){
  192. Map obj = {
  193. "uploadName":uploadName,
  194. "success":true
  195. };
  196. FastNotification.push("percent",obj);
  197. }
  198. }else {
  199. Map obj = {
  200. "uploadName":uploadName,
  201. "success":false
  202. };
  203. FastNotification.push("percent",obj);
  204. }
  205. }).catchError((data) {
  206. Map obj = {
  207. "uploadName":uploadName,
  208. "success":false
  209. };
  210. FastNotification.push("percent",obj);
  211. });
  212. }
  213. // 获取位置信息
  214. initGetLocation() async {
  215. if (await requestPermission()) {
  216. if (null != _locationPlugin) {
  217. ///开始定位之前设置定位参数
  218. _setLocationOption();
  219. _locationPlugin.startLocation();
  220. }
  221. }
  222. }
  223. // 获取定位权限
  224. Future<bool> requestPermission() async {
  225. final permissions = await PermissionHandler()
  226. .requestPermissions([PermissionGroup.location]);
  227. if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
  228. return true;
  229. } else {
  230. toasts('需要定位权限!');
  231. return false;
  232. }
  233. }
  234. // 获取位置信息
  235. Future<void> getLocation() async {
  236. if (await requestPermission()) {
  237. if (null != _locationPlugin) {
  238. ///开始定位之前设置定位参数
  239. _setLocationOption();
  240. _locationPlugin.startLocation();
  241. if(longitude!=null && latitude!=null){
  242. if (videoUrl == null || videoUrl == '') {
  243. toasts("请上传视频");
  244. return;
  245. }
  246. showLoading(context);
  247. NewApiService().chargeToClock({
  248. "id": widget.id,
  249. "lng": longitude,
  250. "lat": latitude,
  251. "beforeRepair": videoUrl,
  252. }, onSuccess: (res) {
  253. dismissLoading(context);
  254. toasts("确认打卡成功");
  255. NavigatorUtils.push(context, "${WodeRouter.orderPageMaster}?checkType=0");
  256. setState(() {});
  257. }, onError: (code, msg) {
  258. dismissLoading(context);
  259. toasts(msg);
  260. });
  261. }
  262. }
  263. }
  264. }
  265. submitApply() {
  266. getLocation();
  267. }
  268. // 文本编辑控制
  269. GlobalKey _formKey = new GlobalKey<FormState>();
  270. @override
  271. void dispose() {
  272. _controller.pause();
  273. _controller.dispose();
  274. ///移除定位监听
  275. if (null != _locationListener) {
  276. _locationListener.cancel();
  277. }
  278. ///销毁定位
  279. if (null != _locationPlugin) {
  280. _locationPlugin.destroy();
  281. }
  282. // SystemChrome.setPreferredOrientations([
  283. // DeviceOrientation.portraitUp,
  284. // ]);
  285. OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
  286. super.dispose();
  287. }
  288. @override
  289. Widget build(BuildContext context) {
  290. double width = MediaQuery.of(context).size.width;
  291. double height = MediaQuery.of(context).size.height;
  292. if(width > height){
  293. // SystemChrome.setPreferredOrientations([
  294. // DeviceOrientation.portraitUp,
  295. // ]);
  296. OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
  297. }
  298. return Scaffold(
  299. resizeToAvoidBottomPadding: false, //不让键盘弹上去
  300. appBar: MyAppBar(
  301. centerTitle: "打卡",
  302. ),
  303. body: Container(
  304. child: ListView(
  305. children: <Widget>[
  306. Form(
  307. key: _formKey, //设置globalKey,用于后面获取FormState
  308. // autovalidate: true, //开启自动校验
  309. child: Column(
  310. children: <Widget>[
  311. Container(
  312. width: width,
  313. padding: EdgeInsets.only(left:15,top:15,bottom:15),
  314. child: Text(
  315. "(建议时长3分钟,建议大小50M)",
  316. style: TextStyle(
  317. color: Colors.red,
  318. fontSize:
  319. ScreenUtil()
  320. .setSp(14),
  321. ),
  322. textAlign: TextAlign.left,
  323. ),
  324. ),
  325. Container(
  326. color: ThemeUtils.getDialogTextFieldColor(context),
  327. child: GridView.builder(
  328. shrinkWrap: true,
  329. padding: const EdgeInsets.fromLTRB(8.0, 12, 8.0, 12.0),
  330. physics: NeverScrollableScrollPhysics(),
  331. gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  332. crossAxisCount: 1, childAspectRatio: 1.18),
  333. itemCount: 1,
  334. itemBuilder: (_, index) {
  335. return Stack(
  336. children: <Widget>[
  337. Center(
  338. child: SelectedVideo(
  339. image: videoUrl,
  340. index: index,
  341. videoPlay:videoPlay(),
  342. onTap: () {
  343. if(videoUrl == null){
  344. selectPicker();
  345. }
  346. },
  347. ),
  348. ),
  349. videoUrl != null
  350. ? Positioned(
  351. top: 0,
  352. right: 0,
  353. child: GestureDetector(
  354. onTap: () {
  355. setState(() {
  356. videoUrl = null;
  357. str = null;
  358. _controller.pause();
  359. // player.reset();
  360. });
  361. },
  362. child: Icon(
  363. IconData(0xe62a, fontFamily: "myfont"),
  364. size: 24.0,
  365. color: Color(0xff999999),
  366. ),
  367. ),
  368. )
  369. : Container(
  370. child: null,
  371. )
  372. ],
  373. );
  374. },
  375. ),
  376. ),
  377. Container(
  378. width: width,
  379. padding: EdgeInsets.all(15),
  380. child: Text(
  381. "当前打卡位置:"+ (address??""),
  382. textAlign: TextAlign.start,
  383. ),
  384. ),
  385. Container(
  386. height: ScreenUtil().setWidth(44),
  387. decoration: BoxDecoration(
  388. borderRadius:
  389. BorderRadius.circular(ScreenUtil().setWidth(22)),
  390. gradient: const LinearGradient(
  391. colors: [Color(0xFF00D9FF), Color(0xFF0287FF)]),
  392. ),
  393. margin: EdgeInsets.all(20.0),
  394. width: double.infinity,
  395. child: FlatButton(
  396. // padding: EdgeInsets.all(15.0),
  397. child: Text("提交"),
  398. // color: Theme
  399. // .of(context)
  400. // .primaryColor,
  401. textColor: Colors.white,
  402. onPressed: () {
  403. /*
  404. * 如果:context不对。可以使用GlobalKey,
  405. * 通过_formKey.currentState 获取FormState后,
  406. * 调用validate()方法校验用户名密码是否合法,校验
  407. * 通过后再提交数据。
  408. */
  409. if ((_formKey.currentState as FormState).validate()) {
  410. submitApply();
  411. }
  412. },
  413. ),
  414. ),
  415. ],
  416. ),
  417. ),
  418. ],
  419. ),
  420. ),
  421. );
  422. }
  423. Widget videoPlay() {
  424. _controller = VideoPlayerController.network(
  425. Utils.getImagePath(videoUrl)
  426. // imgFontUrl + detailObj.url
  427. );
  428. double width = MediaQuery.of(context).size.width;
  429. return Container(
  430. width: width,
  431. height: width*2/3,
  432. padding: EdgeInsets.only(
  433. left: ScreenUtil().setWidth(15),
  434. right: ScreenUtil().setWidth(15),
  435. top: ScreenUtil().setWidth(15)),
  436. child: ClipRRect(
  437. borderRadius: BorderRadius.circular(5),
  438. child: new Chewie(
  439. controller: ChewieController(
  440. videoPlayerController:
  441. // VideoPlayerController.network(
  442. // imgFontUrl + detailObj.url
  443. // ),
  444. _controller,
  445. aspectRatio: 3 / 2,
  446. autoPlay: false,
  447. looping: true,
  448. showControls: true,
  449. deviceOrientationsAfterFullScreen:[DeviceOrientation.portraitUp,],
  450. // 占位图
  451. // placeholder: Image.network(
  452. // imgFontUrl+detailObj.cover,
  453. // fit: BoxFit.contain,
  454. // ),
  455. // 是否在 UI 构建的时候就加载视频
  456. autoInitialize: true,
  457. // 拖动条样式颜色
  458. materialProgressColors:
  459. new ChewieProgressColors(
  460. playedColor: Colors.red,
  461. handleColor: Colors.blue,
  462. backgroundColor: Colors.grey,
  463. bufferedColor: Colors.lightGreen,
  464. ),
  465. ),
  466. ),
  467. ));
  468. }
  469. }