/** * 基础工具库 * author jiang_wz */ //@ts-nocheck import { useEffect, useCallback, useRef } from 'react'; import { Dimensions, Platform, PixelRatio, StatusBar, Keyboard, Alert, Vibration } from 'react-native'; // import Toast from 'react-native-simple-toast'; import { getStatusBarHeight, isIphoneX } from 'react-native-iphone-x-helper'; import Toast from 'react-native-root-toast'; import { BjTypeFrequencyTableRow, BjTypeSampleSquareResearchTableRow, BjTypeSpeciesBookTableRow } from './types'; import redux from './../redux/store'; const height = Number(Dimensions.get('window').height); const width = Number(Dimensions.get('window').width); const version = { //版本标识 type: 4, //1 内测-test 2 预览-rlease 3-api 正式预选版本 4-api正式上线版本 version_counter: 14, //版本号 version_name: '1.3.1', //版本名 rcVersion: 0, //预选版本 platform: 'apple' }; const BaseUrl = 'https://personal-api.zhbhd.cn'; //开发调试环境 const size = { base_width: 375, head_height: px2dp(48), tab_height: px2dp(56), } const colors = { blackColor: '#333333', normalBlackColor: '#555', normalBlackColor6: '#666', // themeColor: '#00D38F', //rgba(0, 211, 143, 1) themeColor: '#33C18B', //rgba(0, 211, 143, 1) // themeColor: '#FAC724', //rgba(0, 211, 143, 1) blueColor: 'rgba(47, 137, 183, 1)', greenColor: '#1FD175', greenTextColor: '#16AA85', red: '#ff6262', yellowColor: '#FAC724', redColor: '#D81E06', placeholderColor: '#bfbfbf', opacityRed: '#FFEFF3', brown: '#D16700', brownText: '#FFC38D', priceColor: '#FF245F', bgColor: '#f7f7f7', lightBgColor: '#fff', borderColor: '#E8E8E8', borderLineColor: '#E8E8E8', tableBorderColor: '#E5E5E5', tableHeaderTextColor: '#333', tableHeaderBgColor: '#f7f7f7', tableHaderCellHeight: px2dp(46), tableContentCellHeight: px2dp(64), tableContentTextColor: '#333', }; function px2dp(px: Number) { try { let w = px * width / 375; w = Number(w); w = Number(w.toFixed(1)) - 0; // const sizeList = [12, 13, 12.5, 375, 350] // if(sizeList.includes(px)){ // return Number(w) // } return Number(w); } catch (e) { return 10 } }; function isPad() { // 屏幕宽度 const screenWidth = width; // 屏幕高度 const screenHeight = height; // const x = Math.pow(screenWidth / PixelRatio.get(), 2); // const y = Math.pow(screenHeight / PixelRatio.get(), 2); // 屏幕尺寸 // const screenInches = Math.sqrt(x + y); console.log("screenInches", screenHeight / screenWidth) const screenInches = screenHeight / screenWidth; // 大于6尺寸则为Pad //2.1342592592592595 if (screenInches >= 1.8) { return false; } return true; } var iosHeight: number = isIphoneX() ? getStatusBarHeight() + px2dp(6) : getStatusBarHeight(); console.log("iosHeight------>", iosHeight) const platStatusBarHeight: any = StatusBar.currentHeight; const statusBarHeight: number = (Platform.OS === 'ios' ? iosHeight : platStatusBarHeight); const onePx = 1 / PixelRatio.get(); function isIos() { if (Platform.OS === 'ios') { return true } return false; } const isEmpty = (value: any) => { try { if (value === null || value === undefined || value === "" || JSON.stringify(value) === '{}') { return true }; return false; } catch (e) { return true; } }; const distributionLocationPoint = (locationPoint: string) => { // console.log("locationPoint", locationPoint) locationPoint = locationPoint + ''; var i = locationPoint.indexOf('.'); var strDu = i < 0 ? locationPoint : locationPoint.substring(0, i);//获取度 var strFen = 0; var strMiao = 0; if (i > 0) { var strFen = "0" + locationPoint.substring(i); strFen = strFen * 60 + ""; i = strFen.indexOf('.'); if (i > 0) { strMiao = "0" + strFen.substring(i); strFen = strFen.substring(0, i);//获取分 strMiao = strMiao * 60 + ""; i = strMiao.indexOf('.'); strMiao = strMiao.substring(0, i + 4);//取到小数点后面三位 strMiao = parseFloat(strMiao).toFixed(2);//精确小数点后面两位 } } return strDu + "°" + strFen + "′" + strMiao; }; const adaptLocationPoint = (longitude: number, latitude: number, wrap?: boolean) => { try { if (longitude && latitude) { if(wrap){ return `${distributionLocationPoint(longitude)}″E \n ${distributionLocationPoint(latitude)}″N` } return `${distributionLocationPoint(longitude)}″E ${distributionLocationPoint(latitude)}″N` } else { return "暂无定位" } } catch (e) { console.log("格式化坐标信息失败", e) return "格式化坐标信息失败" } }; const toastShort = (msg: string) => { Toast.show(msg, { duration: Toast.durations.SHORT, position: px2dp(-200), shadow: true, animation: true, hideOnPress: true, delay: 0, backgroundColor: 'rgb(17, 17, 17)', opacity: 0.8, onShow: () => { // calls on toast\`s appear animation start }, onShown: () => { // calls on toast\`s appear animation end. }, onHide: () => { // calls on toast\`s hide animation start. }, onHidden: () => { // calls on toast\`s hide animation end. } }); }; const toast = (msg: string) => { Toast.show(msg, { duration: Toast.durations.SHORT, position: px2dp(-200), shadow: true, animation: true, hideOnPress: true, delay: 0, backgroundColor: 'rgb(17, 17, 17)', opacity: 0.8, onShow: () => { // calls on toast\`s appear animation start }, onShown: () => { // calls on toast\`s appear animation end. }, onHide: () => { // calls on toast\`s hide animation start. }, onHidden: () => { // calls on toast\`s hide animation end. } }); }; const filterEmoji = (text: string) => { try { let newText = text.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig, ''); return newText; } catch (e) { toastShort("未完全过滤非法字符,请您检查输入内容") return text; } } const adaptFilePath = (filePath: string) => { if (isIos()) { let RNFS_BASE_PATH = null; if (filePath.includes("Library/Caches")) { RNFS_BASE_PATH = RNFS.CachesDirectoryPath + '/Camera/'; } else if (filePath.includes("/Documents/")) { RNFS_BASE_PATH = RNFS.DocumentDirectoryPath; } else { RNFS_BASE_PATH = ''; } if (isEmpty(RNFS_BASE_PATH)) { return filePath; } let contentList = filePath.split('/'); const imageFileName = contentList[contentList.length - 1]; return RNFS_BASE_PATH + "/" + imageFileName; } else { return filePath; } } const getCurrentDateNs = (): number => { let timeNs = parseInt(new Date().getTime() / 1000); console.log("getCurrentDateNs", timeNs) return timeNs } const getFileType = (file_path: string) => { try { let index = file_path.lastIndexOf("."); let fileType = '.' + file_path.substr(index + 1); if (fileType.length > 5) { return '.jpg' } return fileType; } catch (e) { return '' } }; const checkIsJSON = (json_value: string) => { try { JSON.parse(json_value); return true; } catch (e) { return false; } }; const parseImageList = (imageListJSON: String) => { try { console.log("parseImageList------>", deepCopy(imageListJSON)) let imageListResult = []; if (isArray(imageListJSON) && imageListJSON.length === 0) { console.log("parseImageList---->1") imageListResult = imageListJSON; } else if (isArray(imageListJSON) && imageListJSON[0] && imageListJSON[0].imagePath) { console.log("parseImageList---->2") imageListResult = imageListJSON; } else if (checkIsJSON(imageListJSON)) { console.log("parseImageList---->3") const imageList: Array = JSON.parse(imageListJSON); console.log("解析之后的图片是---->", imageList) imageListResult = imageList; } else if (imageListJSON.includes("[") && imageListJSON[0] != "'") { console.log("parseImageList---->4") let imageList = imageListJSON.replace(/\'/g, '"'); imageList = JSON.parse(imageList) imageListResult = imageList; } else if (imageListJSON[0] && imageListJSON[1] && imageListJSON[0] == "'" && imageListJSON[1] === '[') { console.log("parseImageList---->5") const imgListStr = imageListJSON.substring(1, imageListJSON.length - 1); console.log("imgListStr", imgListStr) let imageList = imgListStr.replace(/\'/g, '"'); imageList = imageList.replace(/\\/g, ''); console.log("imageList", imageList); imageListResult = JSON.parse(imageList); } else if (imageListJSON.includes('[{')) { // alert(2) } else if (!imageListJSON.includes('[')) { // alert(3) console.log("parseImageList---->6") // let tempImageList = imageListJSON.splice(','); // let imageList = []; // tempImageList.forEach(ele => { // imageList.push({ // url: ele // }) // }) imageListResult = []; } return imageListResult; } catch (e) { console.log("解析图片数据失败,请联系管理员", e) toastShort("解析图片数据失败,请联系管理员") return [] } }; const uuid = () => { try { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = "-"; var uuid = s.join(""); return 'app-' + new Date().getTime() + '-' + uuid; } catch (e) { return 'app-' + new Date().getTime(); } } function isArray(arr) { return Object.prototype.toString.call(arr) === '[object Array]' } const deepCopy = (data: any): any => { return JSON.parse(JSON.stringify(data)); } const filterSqlRows = (res) => { try { var len = res.rows.length; let rows = new Array; for (let i = 0; i < len; i++) { let row = res.rows.item(i); rows.push(row); // console.log(`Employee name: ${row.name}, Dept Name: ${row.deptName}`); }; return rows; } catch (e) { return [] } } const dispatchSerialNumber = (serialNumberAndCode: string, index: 0 | 1): string => { try { if (!isEmpty(serialNumberAndCode)) { return serialNumberAndCode.split('-')[index]; } return '' } catch (err) { return ''; } } function getLocalTime(type: 'year' | 'month' | 'day' | 'YY:MM:DD' | 'YY:MM:DD HH:MM', nS) { var now; // console.log("toString(nS).length", (nS + '').length) if ((nS + '').length == 10) { // console.log("为10 * 1000") nS = nS * 1000 } if (nS) { now = new Date(nS); } else { now = new Date(); //获得当前时间 }; let month = (now.getMonth() + 1).toString(); let day = now.getDate().toString(); let hour = now.getHours().toString(); let min = now.getMinutes().toString(); let sec = now.getSeconds().toString(); if (Number(month) < 10) { month = '0' + month; }; if (Number(day) < 10) { day = '0' + day; } if (Number(hour) < 10) { hour = '0' + hour; } if (Number(min) < 10) { min = '0' + min; } if (Number(sec) < 10) { sec = '0' + sec; } switch (type) { case 'year': return now.getFullYear(); case 'month': return month; case 'day': return day; case 'YY:MM:DD': return now.getFullYear().toString() + '-' + month + '-' + day; case 'YY:MM:DD HH:MM': return now.getFullYear().toString() + '-' + month + '-' + day + ' ' + hour + ':' + min; }; }; const handleDismissKeyboard = () => { Keyboard.dismiss(); }; /* * @param {Object} data title, confirmText, confirmFun, cancelFun || 标题, 确认文本,确认执行方法 * */ const myConfirm = (data: { title: string, cancelFun?: Function, confirmText: string, confirmFun?: Function }) => { // if (isIos()) { const { title, cancelFun, confirmText, confirmFun } = data; Alert.alert( "提示", title ? title : "提示内容", [ { text: "取消", onPress: cancelFun && cancelFun(), style: "cancel" }, { text: confirmText ? confirmText : "确定", onPress: () => confirmFun && confirmFun() } ] ); // } else { // DeviceEventEmitter.emit('customer-confirm', { data: data }) // } } const validResponseCode = (res) => { console.log("validResponseCode", JSON.stringify(res)) try { switch (res.ykk_code) { case 10000: return true; break; case 10001: toastShort('必填参数为空') return false; break; default: toastShort(res.msg) break; } } catch (e) { return toastShort("操作失败,请稍后重试") } } const isEmptyStr = (str: any) => { try { str = str.replace(/\s*/g, ""); if (str === null || str === undefined || str === "" || JSON.stringify(str) === '{}') { return true }; return false; } catch (e) { return true; } } const parseVoiceList = (voiceListJSONstr): Array => { try { console.log("voiceListJSONstr----->parseVoiceList", voiceListJSONstr + "") if (voiceListJSONstr == " " || isEmpty(voiceListJSONstr) || voiceListJSONstr === "'[]'") { console.log("数据为空返回") return [] } let voiceList: Array = []; if (isArray(voiceListJSONstr) && voiceListJSONstr.length === 0) { imageListResult = voiceListJSONstr; } else if (isArray(voiceListJSONstr) && voiceListJSONstr[0] && voiceListJSONstr[0].audioPath) { voiceList = voiceListJSONstr; } else if (voiceListJSONstr[0] == "'" && voiceListJSONstr.includes('[')) { voiceListJSONstr = voiceListJSONstr + ""; let voiceListStr = voiceListJSONstr.substring(1, voiceListJSONstr.length - 1); let voiceListStr1 = voiceListStr.replace(/\'/g, '"'); let voiceListStr2 = voiceListStr1.replace(/\\/g, ''); voiceList = JSON.parse(voiceListStr2); } else { console.log("正常格式解析是----->", voiceListJSONstr) if (voiceListJSONstr.includes("'")) { voiceListJSONstr = voiceListJSONstr.replace(/\'/g, '"'); voiceListJSONstr = voiceListJSONstr.replace(/\\/g, ''); } voiceList = JSON.parse(voiceListJSONstr); voiceList.forEach(voice => { if (!voice.duration) { voice.duration = 60; } }) } console.log("voiceList解析成功", voiceList) return voiceList; } catch (e) { // console.log("解析音频数据失败,请联系管理---->", e) toastShort("解析音频数据失败,请联系管理员") return [] } }; const getUniqueListBySepeciesName = (originList: Array) => { let uniqueList: Array = []; originList.forEach((row, rowIndex) => { const findExist = uniqueList.find(ele => { return ele.speciesName === row.speciesName; }) if (!findExist && row.speciesName && row.speciesName !== "待鉴定") { uniqueList.push({ speciesName: row.speciesName }) } }); return uniqueList; }; const filterUniqueListBySepeciesName = (originList: Array) => { let uniqueList: Array = []; originList.forEach((row, rowIndex) => { const findExist = uniqueList.find(ele => { return ele.speciesName === row.speciesName; }) if (!findExist && row.speciesName && row.speciesName !== "待鉴定") { uniqueList.push(row) } }); return uniqueList; }; const adapatTypeName = (type) => { const typeMap = { "actualMeasurementResearch": "实(全)测法", "communityProfileResearch": "群落概况", "sampleSquareResearch": "样方(圆)法", "sampleLineResearch": "样线(带)法", }; return typeMap[type]; } const getUserId = () => { try{ const userMsg = redux.getState().userMsg; return userMsg && userMsg.userInfo && userMsg.userInfo.id }catch(e){ return 'unknow' } }; const copyText = (text = '') => { try { Clipboard.setString(text); toastShort("复制成功!") } catch (e) { toastShort("很抱歉,复制失败!") } }; const handleVibration = (timeNs) => { Vibration.vibrate([0, timeNs], false) } export { version, size, width, height, statusBarHeight, colors, onePx, BaseUrl, px2dp, isIos, isEmpty, adaptLocationPoint, toast, toastShort, filterEmoji, adaptFilePath, getCurrentDateNs, getFileType, parseImageList, uuid, isArray, deepCopy, filterSqlRows, dispatchSerialNumber, getLocalTime, handleDismissKeyboard, myConfirm, validResponseCode, checkIsJSON, isEmptyStr, parseVoiceList, isPad, getUniqueListBySepeciesName, filterUniqueListBySepeciesName, adapatTypeName, getUserId, copyText, distributionLocationPoint, handleVibration }