utils.dart 15.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';

import 'package:common_utils/common_utils.dart';
import 'package:connectivity/connectivity.dart';
import 'package:device_info/device_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:one_key/pages/login/web_page.dart';
import 'package:one_key/provider/user_model.dart';
import 'package:one_key/utils/dialog_util.dart';
import 'package:one_key/utils/misc.dart';
import 'package:one_key/utils/navigator_util.dart';
import 'package:one_key/widgets/loading.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../app.dart';

typedef BookTimeSetCallback = void Function(bool needChange);

class Utils {
  /**
     * 获取图片后缀
     *
     * @param img_path 图片或者视频路径
     * @return
     */
  static String getPicSuffix(String img_path) {
    if (img_path == null || img_path.indexOf(".") == -1) {
      return ""; //如果图片地址为null或者地址中没有"."就返回""
    }
    return img_path
        .substring(img_path.lastIndexOf(".") + 1)
        .trim()
        .toLowerCase();
  }

  ///手机号码格式验证
  static bool phoneRegExp(String phone) {
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    return exp.hasMatch(phone);
  }

  ///生成随机验证码
  static randomBit(int len) {
    String scopeF = '123456789'; //首位
    String scopeC = '0123456789'; //中间
    String result = '';
    for (int i = 0; i < len; i++) {
      if (i == 0) {
        result = scopeF[Random().nextInt(scopeF.length)];
      } else {
        result = result + scopeC[Random().nextInt(scopeC.length)];
      }
    }
    return result;
  }

  //时间转换 将秒转换为小时分钟
  static String durationTransform(int seconds) {
    Duration d = Duration(seconds: seconds);
    List<String> parts = d.toString().split(':');
    return '${parts[1]}:${parts[2].substring(0, 2)}';
    // int minute = seconds % 3600 ~/ 60;
    // // 如果用到秒的话计算
    // int second = seconds % 60;
    // return '${minute}:${second}';
  }

  static getDeviceInfoSystem() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      print('Running on ${iosInfo.utsname.machine}');
      return iosInfo.systemVersion;
    } else if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      print('Running on ${androidInfo.model}');
      return androidInfo;
    }
  }

  ///检测是否有相机或者相册权限
  static getPickPermission(BuildContext context, VoidCallback callback,
      PermissionGroup permissionGroup) async {
    if (!(await checkPermission(permissionGroup))) {
      String title = '相册';
      if (permissionGroup == PermissionGroup.camera) {
        title = '相机';
      } else if (permissionGroup == PermissionGroup.location) {
        title = '位置';
      }
      PermissionStatus status = await permissionStatus(permissionGroup);
      if (status == PermissionStatus.neverAskAgain) {
        //用户选择不在弹出权限提示框
        print('never');
        Navigator.pop(context);
        DialogUtil.openAlertDialog(
            context, '未获得${title}权限', "请在手机的权限管理里,将${title}权限开启", '去设置', 340.0,
            onTap: () {
          openSetting();
          Navigator.pop(context, '');
        });
      } else {
        // 申请权限
        bool canContacts = await requestPermission(permissionGroup);
        if (canContacts) {
          callback();
        } else {
          Navigator.pop(context);
          //拒绝通讯录权限 , 苹果拒绝权限后,不再提示权限框,进入此处
          DialogUtil.openAlertDialog(context, '未获得${title}权限',
              "请在手机的权限管理里,将${title}权限开启。", '去设置', 340.0, onTap: () {
            openSetting();
            Navigator.pop(context, '');
          });
        }
      }
    } else {
      callback();
    }
  }

  ///value: 文本内容;fontSize : 文字的大小;fontWeight:文字权重;maxWidth:文本框的最大宽度;maxLines:文本支持最大多少行
  static double calculateTextHeight(
      String value,
      fontSize,
      FontWeight fontWeight,
      double maxWidth,
      int maxLines,
      BuildContext context) {
    // value = filterText(value);
    TextPainter painter = TextPainter(

        ///AUTO:华为手机如果不指定locale的时候,该方法算出来的文字高度是比系统计算偏小的。
        locale: Localizations.localeOf(context, nullOk: true),
        maxLines: maxLines,
        textDirection: TextDirection.ltr,
        text: TextSpan(
            text: value,
            style: TextStyle(
              fontWeight: fontWeight,
              fontSize: fontSize,
            )));
    painter.layout(maxWidth: maxWidth);

    ///文字的宽度:painter.width
    return painter.height;
  }

  static getDateStrFromJiekou(String ms) {
    return DateUtil.formatDate(
        DateTime.fromMillisecondsSinceEpoch(int.parse(ms) * 1000),
        format: DateFormats.full);
  }

  static setBarStatus(bool isDarkIcon,
      {Color color: Colors.transparent}) async {
    if (Platform.isAndroid) {
      if (isDarkIcon) {
        SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
            statusBarColor: color,
            statusBarIconBrightness: Brightness.dark,
            statusBarBrightness: Brightness.dark);
        SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
      } else {
        SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
            statusBarColor: color,
            statusBarIconBrightness: Brightness.light,
            statusBarBrightness: Brightness.light);
        SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
      }
    }
  }

  static void showToast(String msg) {
    Fluttertoast.showToast(
        msg: msg, toastLength: Toast.LENGTH_LONG, gravity: ToastGravity.CENTER);
  }

  //本地图片资源路径
  static String getImgPath(String name, {String format: 'png'}) {
    return 'assets/$name.$format';
  }

  //给数字前面加0
  static String addZeroNumber(int num) {
    return num < 10 ? "0" + num.toString() : num.toString();
  }

  //转换日期数字
  static String formatWeekDayNum(int num) {
    switch (num) {
      case 1:
        return "一";
      case 2:
        return "二";
      case 3:
        return "三";
      case 4:
        return "四";
      case 5:
        return "五";
      case 6:
        return "六";
      case 7:
        return "日";
      default:
        return "";
    }
  }

  // 改变状态栏背景颜色,默认改变为透明
  static changeStatusColor({Color color: Colors.white}) async {
    try {
      await FlutterStatusbarcolor.setStatusBarColor(color, animate: false);
      if (useWhiteForeground(color)) {
        FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
      } else {
        FlutterStatusbarcolor.setStatusBarWhiteForeground(false);
      }
    } on PlatformException catch (e) {
      debugPrint(e.toString());
    }
  }

  //跳转拨打电话页面
  static goPhone(String phoneNum) async {
    String url = "tel:$phoneNum";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      LogUtil.e("Could not launch $url");
    }
  }

  //跳转小程序包间类型置满管理
  static goMiniProgramZm(BuildContext context, String subPath) {
    UserModel model = Provider.of<UserModel>(context, listen: false);
    launchWeChatMiniProgram(
        username: "gh_487873d353b3",
        path:
            "pack-book/pages/book/b_index?seller_id=${model.user.sellerid}&seller_openid=seller_openid&manager_id=&goPath=${subPath}",
        miniProgramType: WXMiniProgramType.RELEASE);
  }

  //分享已点菜品
  static goShareOrderFoodToWeChat(BuildContext context,
      {String title, String rid, String img}) async {
    Loading.showLoading(context);
    String _webPageUrl = "http://colorcun.com/";
    String _thumbnail = img;
    String _title = title;
    String _userName = "gh_487873d353b3";
    String _path =
        "pack-cookbook/pages/success?rid=$rid&identity=2&hasOnlyShow=1";
    String _description = "OneKey";
    var model = new WeChatShareMiniProgramModel(
        webPageUrl: _webPageUrl,
        userName: _userName,
        title: _title,
        path: _path,
        description: _description,
        thumbnail: WeChatImage.network(_thumbnail));
    bool isShare = await shareToWeChat(model);
    print(isShare);
    Loading.hideLoading(context);
  }

  //拉起小程序已点菜品
  static goMiniProgramOrderFood({String rid}) {
    launchWeChatMiniProgram(
        username: "gh_487873d353b3",
        path: "pack-cookbook/pages/success?rid=$rid&identity=2",
        miniProgramType: WXMiniProgramType.RELEASE);
  }

  //跳转拨打电话页面
  static goHelp(BuildContext context) async {
    NavigatorUtil.goWebviewPage(context);
  }

  //获取应用版本昊
  static Future<String> getCurrVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
    return version;
  }

  //获取当前构建版本号
  static Future<int> getCurrBuildNum() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return int.parse(packageInfo.buildNumber);
  }

  //获取唯一标识
  static Future<String> getUUID() async {
    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidDeviceInfo = await deviceInfoPlugin.androidInfo;
      return androidDeviceInfo.androidId;
    } else {
      IosDeviceInfo iosDeviceInfo = await deviceInfoPlugin.iosInfo;
      return iosDeviceInfo.identifierForVendor;
    }
  }

  //比较两个日期是否同一天
  static isOneDay(DateTime one, DateTime two) {
    if (one.year == two.year && one.month == two.month && one.day == two.day)
      return true;
    return false;
  }

  //分享邀请函
  static goShareInvicationToWeChat(String rid, String uid) async {
    String _webPageUrl = "http://colorcun.com/";
    // String _thumbnail =
    //     "https://xt04.colorcun.com/h5/index.html#/?id=163854&hasInvitation=1";
    String _thumbnail =
        "https://qn.colorcun.com/reserve/images/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_201911151148572.jpg";
    String _title = "用餐已为您安排";
    String _userName = "gh_487873d353b3";
    String _path =
        "pages/customer/index?id=$rid&hasInvitation=1&hasSellerShare=1&uid=$uid";
    String _description = "进入查看包间详情,转发同行好友,还可一键导航到饭店";
    //跳转小程序
    var model = new WeChatShareMiniProgramModel(
        webPageUrl: _webPageUrl,
        userName: _userName,
        title: _title,
        path: _path,
        description: _description,
        thumbnail: WeChatImage.network(_thumbnail)
        // thumbnail: WeChatImage.binary(image)
        );
    //分享链接
    // var model = WeChatShareWebPageModel(
    //   // 'https://xt04.colorcun.com/h5/index.html#/?id=$rid&hasInvitation=1',
    //   'https://xt04.colorcun.com/h5/index.html?id=$rid&hasInvitation=1&hasSellerShare=1',
    //   title: _title,
    //   description: _description,
    //   thumbnail: WeChatImage.network(_thumbnail),
    //   scene: WeChatScene.SESSION,
    // );

    bool isSuccess = await shareToWeChat(model);
    return isSuccess;
  }

  //检查网络连接
  static Future<bool> checkConnectiviy() async {
    var connectivityResult = await (new Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      // I am connected to a mobile network.
      return true;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      // I am connected to a wifi network.
      return true;
    }
    return false;
  }

  static String listToString(List<String> list) {
    if (list == null) {
      return null;
    }
    String result;
    list.forEach((string) {
      if (result == null) {
        result = string;
      } else {
        result = '$result,$string';
      }
    });
    return result.toString();
  }

  static String listToStringEnglish(List<String> list) {
    if (list == null) {
      return null;
    }
    String result;
    list.forEach((string) {
      if (result == null) {
        result = string;
      } else {
        result = '$result,$string';
      }
    });
    return result.toString();
  }

  /// 获取日期  今天  明天  后天等等
  static int getDdate(List dateList) {
    String ymyStr = ""; //年月日
    //今天 明天 其他天
    for (var item in dateList) {
      if (item['select'] == true) {
        ymyStr = item['title'];
      }
    }
    String timeStr = ymyStr + ' ' + "00:00:00";
    int ddate = DateUtil.getDateMsByTimeStr(timeStr); //筛选日期时间戳
    return ddate;
  }

  /// 获取早餐、午餐、晚餐字段 1 ,2, 3
  static String getDdateSolt(List sunDateList) {
    String ddateSolt = '';
    for (var item in sunDateList) {
      if (item['isSelect']) {
        ddateSolt = '${item['ddateSolt']}';
      }
    }
    return ddateSolt;
  }

  ///  选中前面的按钮获取人数,输入的自己获取
  static String getPnum(List personNumList) {
    String pnum = '6';
    for (var item in personNumList) {
      if (item['isSelect']) {
        pnum = item['dateText'];
      }
    }
    if (pnum == '更多') {
      pnum = '6';
    }
    return pnum;
  }

  ///工具
  ///  组装成07:00
  static getTimeString(dynamic hour, String minute) {
    return '${hour}:${minute}';
  }

  /// 组装成 07:00-10:00
  static getTimelLongString(String start, String end) {
    return '${start}-${end}';
  }

  /// 从07:00中获取07
  static getHourFromhourAndMinute(String hourAndMinute) {
    return hourAndMinute.substring(0, 2);
  }

  ///从深夜00时中获取00
  static getHourFromTitle(String title) {
    return title.substring(2, 4);
  }

  /// 0 还是 30
  /// 从07:00中获取0 或者 30
  static getMinuteFromhourAndMinute(String hourAndMinute) {
    return hourAndMinute.substring(3, 5);
  }

  /// a < b  则 a = b
  static compareDateTime(String a, String b, BookTimeSetCallback callback) {
    String tempa = '${DateUtil.getNowDateStr().substring(0, 10)} ${a}:00';
    String tempb = '${DateUtil.getNowDateStr().substring(0, 10)} ${b}:00';
    int aMs = DateUtil.getDateMsByTimeStr(tempa);
    int bMs = DateUtil.getDateMsByTimeStr(tempb);
    if (aMs < bMs) {
      callback(true);
    } else {
      callback(false);
    }
  }

  ///获取时间选择器数据
  static getPickerData(String lastTime, List dateData) {
    String hour = Utils.getHourFromhourAndMinute(lastTime);
    String minute = Utils.getMinuteFromhourAndMinute(lastTime);
    if (minute == '30') {
      hour = '${int.parse(hour) + 1}';
    }
    List tempList = List();
    tempList.addAll(dateData);
    tempList.removeRange(0, int.parse(hour));
    if (tempList.length == 0) {
      tempList = [
        {
          '晚上23时': [30]
        }
      ];
    }
    return tempList;
  }
}