utils.js 20.8 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 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
/**
 * Created by DEV005 on 2017/8/31.
 */

import React, { Component } from 'react';
import { BackHandler,AppState,StyleSheet,View,Text
    , NativeModules,AsyncStorage,NavigationActions,
    ActivityIndicator,TouchableOpacity,Image,Touch,Platform,Dimensions
} from 'react-native';

import Toast from 'react-native-root-toast';
import AppService from "../service/AppService";
/**
 * 冒一个时间比较短的Toast
 * @param content
 */
export const xnToast = (content) => {
    if (global.toast !== undefined) {
        Toast.hide(toast);
    };
    global.toast = Toast.show(content.toString(), {
        duration: Toast.durations.LONG,
        position: Toast.positions.CENTER,
        shadow: true,
        animation: true,
        hideOnPress: true,
        delay: 0
    });
};

export const formatStringWithHtml = (originString) => {
  if (originString === undefined) {
    return '';
  }
  const newString = originString
    .replace(/ /g, ' ')
    .replace(/"/g, '"')
    .replace(/&/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>');
  return newString;
};
// 获取主题色
export function getHomeColor(){
    if(global.homeColor == undefined){
        // #8A0886 紫色测试
        global.homeColor = "#3399ff";
        return String(global.homeColor);
    }else{
        return String(global.homeColor);
    }
}
// 获取app传入的配置参数,这个方法只需要调用一次
export async function getConfigTheme(){
    try {
        var result= await NativeModules.system.configTheme();
        global.isNew = true;
        global.role = (JSON.parse(result).role ||"" ).toString();
        global.homeColor = (JSON.parse(result).themeColor ||"#3399ff").toString();
        global.weChatBySmallProgramAppId = (JSON.parse(result).WeChatBySmallProgramAppId ||"" ).toString();
        if(Platform.OS === 'ios'){
            global.showWchatShare = JSON.parse(result).showWchatShare || false;
        }else{
            global.showWchatShare = JSON.parse(result).showWchatShare || false;
        }
        // 是否是导航进入
        global.navigateMode = JSON.parse(result).navigateMode || false;
        if(global.navigateMode === 'true' || global.navigateMode == true){
            global.navigateMode = true;
        }else{
            global.navigateMode = false;
        }
        // app分支,默认配置为测试环境
        global.appTarget = (JSON.parse(result).appTarget ||"xntalkTest" ).toString();

    }catch(e){
        global.isNew = false;
        // #8A0886 紫色测试
        global.homeColor = "#3399ff";
        global.showWchatShare = false;
        global.navigateMode = false;
    }finally{
        console.log('getConfigTheme 完成!!!');
        console.log(global.appTarget);
        console.log('-----------------------');
        console.log(global);
    }
}


export function isIphoneX() {
    let dimen = Dimensions.get('window');
    return (
        Platform.OS === 'ios' &&
        !Platform.isPad &&
        !Platform.isTVOS &&
        (dimen.height === 812 || dimen.width === 812)
    );
}

export function isIphoneMax() {
    let dimen = Dimensions.get('window');
    return (
        Platform.OS === 'ios' &&
        !Platform.isPad &&
        !Platform.isTVOS &&
        (dimen.height > 812 || dimen.width > 812)
    );
}


export function getHeaderHeight() {
    if( Platform.OS === 'android'){
        return 48;

    }else if(Platform.OS === 'ios') {

        if(isIphoneX()){
            return 88;

        }else {
            return 64;
        }
    }
}

export function xnBorderWidth() {
    if(isIphoneX()){
        return 1;
    }else if(isIphoneMax()){
        return 1;
    } else {
        return 0.5;
    }
}

export function getHeaderPadding() {
    if( Platform.OS === 'android'){
        return 0;
    }else if(Platform.OS === 'ios') {
        if(isIphoneX()){
            return 44;
        }else {
            return 20;
        }
    }
}

export function getFooterBottom() {
    if( Platform.OS === 'android'){
        return 0;
    }else if(Platform.OS === 'ios') {
        if(isIphoneX()){
            return 0;
        }else if(isIphoneMax()){
            return 34;
        }else{
            return 0;
        }
    }
}

export function toPersonalPageWithUserId(userId){
    if(!!!userId){
        xnToast('无法与该用户私信');
    }else if(userId == global.userId){
        xnToast('不能与自己私信');
    }else{
        let _this = this;
        let vm = {
            userId: userId,
        };
        AppService.getUnionByUserId(vm).then(data => {
            if (data.errors == null || data.errors.length > 0) {
                xnToast(data.errors[0].message);
                return
            }
            console.log(data);

            if(!!data.union){
                let union = data.union;
                if(!!union.imId){
                    NativeModules.system.presentPersonal(union.imId);
                }else{
                    xnToast('无法与该用户私信');
                }
            }else{
                xnToast('无法与该用户私信');
            }
        });
    }
}


//代码如下所示:
export function convertCurrency(money) {
    //汉字的数字
    var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    //基本单位
    var cnIntRadice = new Array('', '拾', '佰', '仟');
    //对应整数部分扩展单位
    var cnIntUnits = new Array('', '万', '亿', '兆');
    //对应小数部分单位
    var cnDecUnits = new Array('角', '分', '毫', '厘');
    //整数金额时后面跟的字符
    var cnInteger = '整';
    //整型完以后的单位
    var cnIntLast = '元';
    //最大处理的数字
    var maxNum = 999999999999999.9999;
    //金额整数部分
    var integerNum;
    //金额小数部分
    var decimalNum;
    //输出的中文金额字符串
    var chineseStr = '';
    //分离金额后用的数组,预定义
    var parts;
    if (money == '') { return ''; }
    money = parseFloat(money);
    if (money >= maxNum) {
        //超出最大处理数字
        return '';
    }
    if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
    }
    //转换为字符串
    money = money.toString();
    if (money.indexOf('.') == -1) {
        integerNum = money;
        decimalNum = '';
    } else {
        parts = money.split('.');
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
    }
    //获取整型部分转换
    if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
            var n = integerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n == '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    chineseStr += cnNums[0];
                }
                //归零
                zeroCount = 0;
                chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                chineseStr += cnIntUnits[q];
            }
        }
        chineseStr += cnIntLast;
    }
    //小数部分
    if (decimalNum != '') {
        var decLen = decimalNum.length;
        for (var i = 0; i < decLen; i++) {
            var n = decimalNum.substr(i, 1);
            if (n != '0') {
                chineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    }
    if (chineseStr == '') {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (decimalNum == '') {
        chineseStr += cnInteger;
    }
    return chineseStr;
}

/**
 * add by hongpeng_dong  2007.05.12
 * 验证金额,成绩等可以带小数点数字的格式
 * @param str(要验证的字符串) num1(整数部分允许的最大长度) num2(小数点后允许的最大长度)
 * num1 num2 要求均为大于0的正整数 否则直接返回false
 * @return 格式正确true 不正确false
 * (正确格式可以为不含小数点的正整数,长度最大为传入的数值;如果str为空,返回true)
 */
export function validateResult(str,num1,num2){
    if('' == trim(str))
        return true;
    if(num1 ==0 || num2 == 0)
        return false;
    var v1 = '';
    var v2 = '';
    if(num1 != 1)
        v1=',' + num1;
    if(num2 != 1)
        v2 = ','+num2;
    var re = new RegExp('\(^[0-9]{1'+v1+'}\\.[0-9]{1'+v2+'}$)|(^[0-9]{1'+v1+'}$)');
    return re.test(str);
}

export function isNotANumber(inputData) {
    if (parseFloat(inputData).toString() == "NaN") {
        //alert(“请输入数字……”);
        return false;
    } else {
        return true;
    }
}

export function isJSONString(str) {
    try {
        let obj = JSON.parse(str);
        return !!obj && typeof obj === 'object';
    } catch (e) {
        return false;
    }
}

export function isIdCard(cardid) {
    var format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
    //号码规则校验
    if (!format.test(cardid)) {
        return false;
    }
    //区位码校验
    //出生年月日校验  前正则限制起始年份为1900;
    var year = cardid.substr(6,4),//身份证年
        month = cardid.substr(10,2),//身份证月
        date = cardid.substr(12,2),//身份证日
        time = Date.parse(month+'-'+date+'-'+year),//身份证日期时间戳date
        now_time = Date.parse(new Date()),//当前时间戳
        dates = (new Date(year,month,0)).getDate();//身份证当月天数
    if(time>now_time||date>dates){
        return false
    }
    //校验码判断
    var c = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);  //系数
    var b = new Array('1','0','X','9','8','7','6','5','4','3','2'); //校验码对照表
    var id_array = cardid.split("");
    var sum = 0;
    for(var k=0;k<17;k++){
        sum+=parseInt(id_array[k])*parseInt(c[k]);
    }
    if(id_array[17].toUpperCase() != b[sum%11].toUpperCase()){
        return false;
    }
    return true;
}

export function Calculate(expression) {
    //this.showArea = document.getElementById("show");
    this.expression = expression;
    /*this.clean = function() {
        this.showArea.value = '0';
        this.expression = '';
    };*/
    /*this.deleteNumber = function() {
        this.expression = this.expression.substring(0,this.expression.length-1);
        this.showArea.value = this.expression;
    };
    this.showExpression = function(expression) {
        this.expression += expression;
        this.showArea.value = this.expression;
    };*/
    /**
     * first step we should remove bracket
     * second step we should remove Multiplic and Division
     * the last step just remove plus and minus,and then result out
     * @returns {undefined}
     */
    this.calculateResult = function() {
//        this.expression = "1.1+(2.1*3)-(((2.2*3)*((1.1+2.2)/3.3)-3.4*6)-(3.5*6))+3.6";
        // 表达式中包含字符
        if (this.hasUpperLowerChat(expression)) {
            this.expression = '';
            return this.expression;
        }
        if (!this.checkOperator(this.expression) || !this.checkFloat(this.expression)) {
            this.expression = '';
            return this.expression;
        }
        if(this.hasBracket(this.expression)) {
            if (!this.checkBracket(this.expression)) {
                this.expression = '';
                return this.expression;
            }
            this.expression = this.removeBracket(this.expression);
        }

        if (this.hasMultiplicOrDivision(this.expression)) {
            this.expression = this.removeMultiplicOrDivision(this.expression);
        }
        if(this.hasPlusOrMinus(this.expression)) {
            this.expression = this.plusOrMinus(this.expression);
        }
        //this.expression = '';
        return this.expression;
    };
    /**
     *
     * @param {type} expression
     * @returns {undefined|Boolean}
     * 检查运算符是否合法,第一个字符是除“-”意外的运算符都是非法的,最后一个字符是运算符,也是非法的;
     * 检查是否含有不合法的多运算符 “**”,“*\/”,"*+","*-","+*","++","+\/"以及两以上的连续运算符都是不允许的
     * 在多运算符里面除了 “--”,“+-”都是不合法的多运算符
     */
    this.checkOperator = function(expression) {
        /**
         * (^[\+\*\/])|([\+\-\*\/]$) 匹配首字符或是最后一个字符是不是运算符
         * ([\+\-\*\/][\+\*\/]+) [+,*,-,/]搭配一个或是多个[+,*,/]
         * ([\*\/](\-)+) [*,/]搭配一个或是多个[-]
         * ([\+\-](\-){2,}) [+,-]搭配两个以上的[-]
         * @type RegExp
         */
        var reg = /(^[\+\*\/])|([\+\-\*\/]$)|([\+\-\*\/][\+\*\/]+)|([\*\/](\-)+)|([\+\-](\-){2,})/;
        if(reg.test(expression)) {
            return false;
        }
        return true;
    };
    /**
     *
     * @param {type} expression
     * @returns {undefined}
     * 检查“.”是否在正确位置,".+","+.","^.",".$","2.2.3.4.5","..","..."都是不允许的。
     */
    this.checkFloat = function (expression) {
        /**
         * (^\.)|(\.$) expression以.开头或结尾
         * ([\+\-\*\/]\.)|(\.[\+\-\*\/]) expression出现".+","+."等情况
         * ((\d+\.+){2,}\d*) expression出现"2.2.3.4.5","..","..."等情况
         */
        var reg = /(^\.)|(\.$)|([\+\-\*\/]\.)|(\.[\+\-\*\/])|((\d+\.+){2,}\d*)/;
        if (reg.test(expression)) {
            return false;
        }
        return true;
    };
    /**
     *
     * @param {type} expression
     * @returns {@this;@call;removeBracket}
     * make sure the expression has bracket
     */
    this.hasBracket = function(expression) {
        var hasBraketReg = /(\(|\))/; //查看表达expression中是否有();
        if (hasBraketReg.test(expression)) {
            return true;
        }
        return false;
    };
    /**
     * 检测表达式中是否有字符串
     * @param expression
     */
    this.hasUpperLowerChat = function (expression) {
        var hasUpperReg = /(.*[A-Z]+.*)/;
        if (hasUpperReg.test(expression)) {
            return true;
        }
        var hasLowerReg = /(.*[Aa-z]+.*)/;
        if (hasLowerReg.test(expression)) {
            return true
        }
        return false;
    };
    /**
     * 检查表达式中的输入的括号输入正确;
     * 1.括号必须与运算符号连接在一起 既“3(”,“(*3”,“3*)”,“)3”,".)",".(","(.",").",是不允许的
     * 2.左括号的数量必须等于右括号的数量
     * @param {type} expression
     * @returns {undefined}
     */
    this.checkBracket = function(expression) {
        var reg = /([\d\.]\()|(\)[\d\.])|(\([\+\-\*\/\.])|([\+\-\*\/\.]\))/;
        if (reg.test(expression)) {
            return false;
        }
        var leftBracket = 0, rightBracket = 0;
        for (var i = 0; i < expression.length; i++) {
            if (expression.charAt(i) === "(") {
                leftBracket++;
            } else if(expression.charAt(i) === ")") {
                rightBracket++;
            }
        }
        if (!(leftBracket === rightBracket)) {
            return false;
        }
        return true;
    };
    /**
     *
     * @param {type} expression
     * remove bracket;
     * @returns {undefined}
     */
    this.removeBracket = function(expression) {
        var regMatch = /\([^\(\)]+\)/g; //这个正则表达式匹配最里面的一层括号,既(这里面是不能包含“(”或是“)”的)
        var childExpression = expression.match(regMatch);
        var mySign = "&mySign&"; //用一个特殊标记记录等会需要替换的位置
        var replaceExpression = expression.replace(regMatch,mySign);
        var subExpression = "";
        for(var i = 0; i < childExpression.length; i++) {
            subExpression = childExpression[i].substring(1,childExpression[i].length-1);
            if (this.hasMultiplicOrDivision(subExpression)) {
                subExpression = this.removeMultiplicOrDivision(subExpression);
            }
            if (this.hasPlusOrMinus(subExpression)) {
                subExpression = this.plusOrMinus(subExpression);
            }
            replaceExpression = replaceExpression.replace(mySign,subExpression);
        }
        expression = replaceExpression;
        if(this.hasBracket(expression)) {
            expression = this.removeBracket(expression);
        } else {
            return expression;
        }
        return expression;
    };

    /**
     *
     * @param {type} expression
     * @returns {@this;@call;removeMultiplicOrDivision}
     * make sure the expression with Multiplic Or Division
     */
    this.hasMultiplicOrDivision = function(expression) {
        var hasMultiplicOrDivisionReg =  /(\*|\/)/;
        if (hasMultiplicOrDivisionReg.test(expression)) {
            return true;
        };
        return false;
    };
    /**
     *
     * @param {type} expression
     * remove Multiplic and Division
     * @returns {unresolved}
     */
    this.removeMultiplicOrDivision = function(expression) {
//        var expression = "1-13*2+3*456/3*15*8/5*4-50-40+32*2/16"; //test data
        var regMatch = /((\d+\.?\d*)(\*|\/))+(\d+\.?\d*)/g;
        var childResult = "";
        var childExpression = expression.match(regMatch);
        var mySign = "&mySign&"; //用一个特殊标记记录等会需要替换的位置
        var replaceExpression = expression.replace(regMatch,mySign);
        for(var i = 0; i < childExpression.length; i++) {
            childResult = this.multiplicOrDivision(childExpression[i]);
            replaceExpression = replaceExpression.replace(mySign,childResult);
        }
        expression = replaceExpression;
        return expression;
    };
    this.multiplicOrDivision = function(expression) {
        var regNumber = /\d+\.?\d*/g;
        var regOperator = /(\*|\/)/g;
        var arrNumbers = expression.match(regNumber);
        var arrOperators = expression.match(regOperator);

        var calResult = parseFloat(arrNumbers[0]);
        for (var i = 0; i < arrOperators.length; i++) {
            if (arrOperators[i] === '*') {
                calResult *= parseFloat(arrNumbers[i+1]);
            } else {
                calResult /= parseFloat(arrNumbers[i+1]);
            }
        }
        return calResult;
    };

    this.hasPlusOrMinus = function(expression) {
        var hasPlusOrMinusReg =  /(\+|\-)/;
        if (hasPlusOrMinusReg.test(expression)) {
            return true;
        };
        return false;
    };
    /**
     *
     * @param {type} expression
     * this is the last step , just has plus or minus , after we done this step, the result out
     * @returns {Calculate.plusOrMinus.calResult}
     */
    this.plusOrMinus = function(expression) {
        /**
         *  如果第一个字符是“-”号,就在expression前面加上一个0即可
         */
        if (expression.charAt(0) === "-") {
            expression = 0 + expression;
        }
        var doubleMinusReg = /\-\-/;  //减去一个负数,等于加一个正数
        if (doubleMinusReg.test(expression)) {
            expression = expression.replace(doubleMinusReg,"+");
        }
        doubleMinusReg = /\+\-/;  //加上一负数,等于减去一个正数
        if (doubleMinusReg.test(expression)) {
            expression = expression.replace(doubleMinusReg,"-");
        }
        var regNumber = /\d+\.?\d*/g;
        var regOperator = /(\+|\-)/g;
        var arrNumbers = expression.match(regNumber);
        var arrOperators = expression.match(regOperator);

        var calResult = parseFloat(arrNumbers[0]);
        for (var i = 0; i < arrOperators.length; i++) {
            if (arrOperators[i] === '+') {
                calResult += parseFloat(arrNumbers[i+1]);
            } else {
                calResult -= parseFloat(arrNumbers[i+1]);
            }
        }
        return calResult;
    };
}

export function LTrim(str)
{
    var whitespace = new String(" \t\n\r");
    var s = new String(str);
    if (whitespace.indexOf(s.charAt(0)) != -1)
    {
        var j=0, i = s.length;
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
        {
            j++;
        }
        s = s.substring(j, i);
    }
    return s;
}
export function RTrim(str)
{
    var whitespace = new String(" \t\n\r");
    var s = new String(str);
    if (whitespace.indexOf(s.charAt(s.length-1)) != -1)
    {
        var i = s.length - 1;
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
        {
            i--;
        }
        s = s.substring(0, i+1);
    }
    return s;
}
export function trim(str)
{
    return RTrim(LTrim(str));
}

const xnUtils={
    xnToast:xnToast,
    isIphoneX:isIphoneX,
    getHeaderHeight:getHeaderHeight,
    getHeaderPadding:getHeaderPadding,
    getFooterBottom:getFooterBottom,
    xnBorderWidth:xnBorderWidth,
}
export default xnUtils;