punchin.dart 18 KB

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