Public.ts 10.8 KB
import nettyApi from '@/constants/api/ms-netty/netty.api';
import InterFaceFactory from '@/public/factory/InterFaceFactory';
import systemApi from '@/constants/api/ms-system/system.api';

/**
 * 工具类
 */
const Public = {
  /**
   * 获取地理位置信息(同步方法)
   * @return {Object} {lng, lat, address} 当前位置信息的经度、纬度、地理位置
   */
  getLocation() {
    let locInfos;
    if (window.plus && window.plus.os.name === 'iOS') {
      locInfos = this.parseLocation(window.plus.iOSMapNav.getLocation());
    } else if (window.plus && window.plus.os.name === 'Android') {
      locInfos = this.parseLocation((window as any).SMMP.getLocation('2'));
    } else {
      locInfos = {
        lng: '#',
        lat: '#',
        address: '暂无位置信息'
      };
    }
    return locInfos;
  },
  /**
   * 获取当前位置信息(异步方法),支持iOS设备
   * @param {Function} successCallback 成功回调
   * @param {Function} errorCallback 失败回调
   */
  getCurrentPosition(successCallback: any, errorCallback: any) {
    if (window.plus) {
      if (window.plus.os.name === 'iOS') {
        window.plus.iOSMapNav.getCurrentPosition(
          function(result: any) {
            let locInfos = result.split('');
            let newResult = {};
            let myPosition;
            if (locInfos.length === 2) {
              myPosition = locInfos[1];
            } else {
              myPosition = locInfos[0];
            }
            // 经度
            (newResult as any).lng = myPosition.split('')[1];
            // 维度
            (newResult as any).lat = myPosition.split('')[2];
            // 地址
            (newResult as any).address = myPosition.split('')[3];
            if (typeof successCallback === 'function') {
              successCallback(newResult);
            }
          },
          function(result: any) {
            console.debug(result);
            if (typeof errorCallback === 'function') {
              errorCallback(result);
            }
          }
        );
      }
    }
  },
  /**
   * 解析位置信息
   * @param {String} locInfoStr 位置信息,格式:2020-08-13 14:22:33▓113.356552▓22.946032▓中国广东省广州市番禺区北丽园六街◆2020-08-13 14:27:33▓113.356552▓22.946032▓中国广东省广州市番禺区北丽园六街
   * @return {Object} {lng, lat, address} 当前位置信息的经度、纬度、地理位置
   */
  parseLocation(locInfoStr: any) {
    let newResult = {};
    if (typeof locInfoStr === 'string') {
      let locInfos = locInfoStr.split('');
      let curPosition;
      if (locInfos.length === 2) {
        curPosition = locInfos[1];
      } else {
        curPosition = locInfos[0];
      }
      // 经度
      (newResult as any).lng = curPosition.split('')[1];
      // 维度
      (newResult as any).lat = curPosition.split('')[2];
      // 地址
      (newResult as any).address = curPosition.split('')[3];
    }
    return newResult;
  },
  /**
   * 检测距离
   * @param {String} curDistance 当前距离
   * @param {String} targerDistance 目标距离
   */
  detectDistance(curDistance: any, targerDistance: any) {
    if (curDistance < targerDistance) {
      return true;
    }
    return false;
  },
  /**
   * 获取两点距离
   * @author liuxiaoyu
   * @param {String} curLon 当前经度
   * @param {String} curLat 当前纬度
   * @param {String} oldLon 上次经度
   * @param {String} oldLat 上次纬度
   */
  getLongDistance(curLon: any, curLat: any, oldLon: any, oldLat: any) {
    let ew1,
      ns1,
      ew2,
      ns2,
      distance,
      DEF_PI180 = 0.01745329252, //PI / 180
      DEF_R = 6371003.5; //地球半径
    // 角度转换为弧度
    ew1 = curLon * DEF_PI180;
    ns1 = curLat * DEF_PI180;
    ew2 = oldLon * DEF_PI180;
    ns2 = oldLat * DEF_PI180;
    // 求大圆劣弧与球心所夹的角(弧度)
    distance = Math.sin(ns1) * Math.sin(ns2) + Math.cos(ns1) * Math.cos(ns2) * Math.cos(ew1 - ew2);
    // 调整到[-1..1]范围内,避免溢出
    if (distance > 1.0) distance = 1.0;
    else if (distance < -1.0) distance = -1.0;
    // 求大圆劣弧长度
    distance = (DEF_R * Math.acos(distance)) / 1000;
    return distance.toFixed(2);
  },
  /** 格式化金额*/
  formatMoney: function(s: any, split: any) {
    if (isNaN(s)) return;
    if (typeof s == 'undefined' || s == null || s == '') return '';
    if (s == 0) return '0.00';
    s = parseFloat(s);
    if (typeof s != 'number') return '';
    s = s.toFixed(2).toString();
    if (!split) split = ',';
    var l = s
        .split('.')[0]
        .split('')
        .reverse(),
      r = s.split('.')[1];
    var t = '';
    for (var i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? ',' : '');
    }
    return (
      t
        .split('')
        .reverse()
        .join('') +
      '.' +
      r
    );
  },
  /**计算年龄 */
  getAge: function(identityCard: any) {
    var len = (identityCard + '').length;
    if (len == 0) {
      return 0;
    } else {
      if (len != 15 && len != 18) {
        //身份证号码只能为15位或18位其它不合法
        return 0;
      }
    }
    var strBirthday = '';
    if (len == 18) {
      //处理18位的身份证号码从号码中得到生日和性别代码
      strBirthday = identityCard.substr(6, 4) + '/' + identityCard.substr(10, 2) + '/' + identityCard.substr(12, 2);
    }
    if (len == 15) {
      strBirthday =
        '19' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2);
    }
    //时间字符串里,必须是“/”
    var birthDate = new Date(strBirthday);
    var nowDateTime = new Date();
    var age = nowDateTime.getFullYear() - birthDate.getFullYear();
    //再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1
    if (
      nowDateTime.getMonth() < birthDate.getMonth() ||
      (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())
    ) {
      age--;
    }
    return age;
  },
  /**
   * 16进制转字符串
   * @author zhangmk
   * @time 2021年11月17日10:39:58
   */
  hexToString: function(hex: any) {
    var encoding = 'utf-8';
    var trimedStr = hex.trim();
    var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
    var len = rawStr.length;
    if (len % 2 !== 0) {
      return '';
    }
    var curCharCode;
    var resultStr = [];
    for (var i = 0; i < len; i = i + 2) {
      curCharCode = parseInt(rawStr.substr(i, 2), 16);
      resultStr.push(curCharCode);
    }
    // encoding为空时默认为utf-8
    var bytesView = new Uint8Array(resultStr);
    var str = new TextDecoder(encoding).decode(bytesView);
    return str;
  },
  /**ahtuor:pd
   * 工商证件类型码值转换
   * 2021年11月25日12:17:24
   */

  getGScode(code: any) {
    const tycode = '202'; //统一信用代码--工商
    const zzcode = '200'; //组织机构代码--工商
    if (code == '26') {
      //信贷统一信用代码
      return tycode;
    } else if (code == '20') {
      //组织机构代码--信贷
      return zzcode;
    } else {
      return code;
    }
  },

  /**
   *author:pd
   *组装交易编号SvrCode
   */
  getSvrCode(tc: any) {
    return this.getProdId() + '_' + tc;
  },
  /**
   *author:pd
   *ProdId产品编号
   */
  getProdId() {
    const ProdId = 'MCEP';
    return ProdId;
  },
  /**
   *
   *author:zhangmk
   *判断是否分支行
   */
  getIfBranch() {
    var NO = sessionStorage.getItem('branchNo') || '';
    var array = ['9100', '9200', '9300', '2222', '0000', '9999'];
    //从登录返回的数据中获取机构后调整
    if (NO.length == 9) {
      NO = NO.substring(5, NO.length);
      if (array.indexOf(NO) != -1) {
        return false;
      } else return true;
    } else {
      if (NO.substring(0, 4) == '9999') {
        return false;
      } else {
        if (NO.substring(0, 4) == '9999') {
          return false;
        } else {
          return true;
        }
      }
    }
  },
  /**
   * zhangmingkun
   * 2021年12月08日10:39:18
   * 查询树结构内容
   * treedicField:树结构名称: 行业:STD_GB_4754-2011
   * treedicKey: 值
   * 案例:Public.getTreeValue('STD_GB_4754-2002', '0330', function(res) {
        console.log(res);
      });
   */
  getTreeValue(treedicField: any, treedicKey: any, callback: any) {
    let param = {
      tc: 'MCEP',
      treedictField: treedicField,
      treedictKey: treedicKey
    };
    InterFaceFactory.transferDataInter(systemApi.treeRq, param).then((res: any) => {
      if (res.code == '1') {
        let dataDic = res.data;
        callback(dataDic);
      }
    });
  },
  /**
  *@Desc 功能描述:根据图片路径将图片转file格式
  *@Author XWH
  *Date 2022/2/19 17:29
  */
  imgUrlToFile(imgUrl: any, fileName: string){
    const canvas = document.createElement("canvas"),
      ctx = canvas.getContext("2d")!,
      img = new Image();
    img.setAttribute("crossOrigin", "*");
    let dataURL = "";
    img.onload = () => {
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0);
      dataURL = canvas.toDataURL("image/jpg");
      // console.log(dataURL); //Base64码  一般用这个就行
      return this.base64toFile(dataURL, fileName);
    };
    img.src = imgUrl;
  },
  /**
  *@Desc 功能描述:base64格式图片转file
  *@Author XWH
  *Date 2022/2/19 17:30
  */
  base64toFile(url: any, fileName: string){
      let arr = url.split(','),    //dataUrl是传入的base64格式数据
        mime = arr[0].match(/:(.*?);/)[1],
        suffix = mime.split('/')[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while(n--){
      u8arr[n] = bstr.charCodeAt(n);
    }
    let file = new File([u8arr],`${fileName}.${suffix}`,{  //${fileName}为传入的参数,写死为file
      type: mime
    });
    return file
  },
  /**
   *@Description 功能描述:根据父id获取菜单
   *@Author XWH
   *@Date 2022/1/17 16:21
   */
  getMenuBySuperID(superID: any, menuType: any) {
    let menuList: any = sessionStorage.getItem('menuType'),
      menuData = JSON.parse(menuList),
      menuArr = [];
    for (let data of menuData) {
      const obj: any = {};
      if (data.menuSupId == superID) {
        obj.name = data.frontMenuName;
        obj.path = data.menuUrl;
        obj.iconName = data.menuIcon;
        obj.menuId = data.menuId;
        if (data.moveMenuType == menuType) {
          if (menuType == 'CommonFunctions' || menuType == 'CommonUpcoming') {
            obj.iconName = require('@/assets/images/' + obj.iconName + '.png');
          } else if (menuType == 'secondRow') {
            obj.info = '当前待处理';
            obj.num = 0;
          }
          menuArr.push(obj);
        }
      }
    }
    return menuArr;
  }
};
export default Public;