提交 0d9e986a authored 作者: 吴强's avatar 吴强

人口上传头像,有点问题,就是无法改名字

上级 3b113569
apply plugin: "com.android.application" apply plugin: "com.android.application"
import com.android.build.OutputFile import com.android.build.OutputFile
/** /**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets). * and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build * These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations * bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the * and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line. * `apply from: "../../node_modules/react-native/react.gradle"` line.
* *
* project.ext.react = [ * project.ext.react = [
* // the name of the generated asset file containing your JS bundle * // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle", * bundleAssetName: "index.android.bundle",
* *
* // the entry file for bundle generation * // the entry file for bundle generation
* entryFile: "index.android.js", * entryFile: "index.android.js",
* *
* // whether to bundle JS and assets in debug mode * // whether to bundle JS and assets in debug mode
* bundleInDebug: false, * bundleInDebug: false,
* *
* // whether to bundle JS and assets in release mode * // whether to bundle JS and assets in release mode
* bundleInRelease: true, * bundleInRelease: true,
* *
* // whether to bundle JS and assets in another build variant (if configured). * // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats * // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}' * // 'bundleIn${buildType}'
* // bundleInFreeDebug: true, * // bundleInFreeDebug: true,
* // bundleInPaidRelease: true, * // bundleInPaidRelease: true,
* // bundleInBeta: true, * // bundleInBeta: true,
* *
* // whether to disable dev mode in custom build variants (by default only disabled in release) * // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured) * // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true, * devDisabledInStaging: true,
* // The configuration property can be in the following formats * // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}' * // 'devDisabledIn${buildType}'
* *
* // the root of your project, i.e. where "package.json" lives * // the root of your project, i.e. where "package.json" lives
* root: "../../", * root: "../../",
* *
* // where to put the JS bundle asset in debug mode * // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
* *
* // where to put the JS bundle asset in release mode * // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release", * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
* *
* // where to put drawable resources / React Native assets, e.g. the ones you use via * // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode * // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
* *
* // where to put drawable resources / React Native assets, e.g. the ones you use via * // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode * // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
* *
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle * // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here. * // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"], * inputExcludes: ["android/**", "ios/**"],
* *
* // override which node gets called and with what additional arguments * // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"], * nodeExecutableAndArgs: ["node"],
* *
* // supply additional arguments to the packager * // supply additional arguments to the packager
* extraPackagerArgs: [] * extraPackagerArgs: []
* ] * ]
*/ */
project.ext.react = [ project.ext.react = [
entryFile: "index.js" entryFile: "index.js"
] ]
apply from: "../../node_modules/react-native/react.gradle" apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle" apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
project.ext.vectoricons = [ project.ext.vectoricons = [
iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Name of the font files you want to copy iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Name of the font files you want to copy
] ]
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
/** /**
* Set this to true to create two separate APKs instead of one: * Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices * - An APK that only works on ARM devices
* - An APK that only works on x86 devices * - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB. * The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download * Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device. * the correct one based on the CPU architecture of their device.
*/ */
def enableSeparateBuildPerCPUArchitecture = false def enableSeparateBuildPerCPUArchitecture = false
/** /**
* Run Proguard to shrink the Java bytecode in release builds. * Run Proguard to shrink the Java bytecode in release builds.
*/ */
def enableProguardInReleaseBuilds = false def enableProguardInReleaseBuilds = false
Properties properties = new Properties() Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream()) properties.load(project.rootProject.file('local.properties').newDataInputStream())
android { android {
compileSdkVersion 25 compileSdkVersion 25
buildToolsVersion "25.0.3" buildToolsVersion "25.0.3"
defaultConfig { defaultConfig {
applicationId "com.bolanmanagerapp" applicationId "com.bolanmanagerapp"
minSdkVersion 16 minSdkVersion 16
targetSdkVersion 25 targetSdkVersion 25
multiDexEnabled true multiDexEnabled true
versionCode 1 versionCode 1
versionName "1.0.2" versionName "1.0.4"
ndk { ndk {
abiFilters "armeabi-v7a", "x86" abiFilters "armeabi-v7a", "x86"
} }
} }
dexOptions { dexOptions {
javaMaxHeapSize "2G" javaMaxHeapSize "2G"
} }
signingConfigs { signingConfigs {
release { release {
storeFile file("app.jks") storeFile file("app.jks")
storePassword "proland305\$" storePassword "proland305\$"
keyAlias "bolan" keyAlias "bolan"
keyPassword "proland305\$" keyPassword "proland305\$"
} }
} }
splits { splits {
abi { abi {
reset() reset()
enable enableSeparateBuildPerCPUArchitecture enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86" include "armeabi-v7a", "x86"
} }
} }
buildTypes { buildTypes {
debug { debug {
buildConfigField "String", "CODEPUSH_KEY", 'null' buildConfigField "String", "CODEPUSH_KEY", 'null'
} }
releaseStaging { releaseStaging {
signingConfig signingConfigs.release signingConfig signingConfigs.release
buildConfigField "String", "CODEPUSH_KEY", '"' + properties.getProperty("code_push.key_staging") + '"' buildConfigField "String", "CODEPUSH_KEY", '"' + properties.getProperty("code_push.key_staging") + '"'
} }
release { release {
minifyEnabled enableProguardInReleaseBuilds minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
signingConfig signingConfigs.release signingConfig signingConfigs.release
buildConfigField "String", "CODEPUSH_KEY", '"' + properties.getProperty("code_push.key_production") + '"' buildConfigField "String", "CODEPUSH_KEY", '"' + properties.getProperty("code_push.key_production") + '"'
} }
} }
// applicationVariants are e.g. debug, release // applicationVariants are e.g. debug, release
applicationVariants.all { variant -> applicationVariants.all { variant ->
variant.outputs.each { output -> variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here: // For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = ["armeabi-v7a":1, "x86":2] def versionCodes = ["armeabi-v7a":1, "x86":2]
def abi = output.getFilter(OutputFile.ABI) def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride = output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
} }
} }
} }
} }
dependencies { dependencies {
compile project(':react-native-background-upload') compile project(':react-native-background-upload')
compile project(':react-native-code-push') compile project(':react-native-code-push')
compile project(':react-native-device-info') compile project(':react-native-device-info')
compile fileTree(dir: "libs", include: ["*.jar"]) compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:25.4.0" compile "com.android.support:appcompat-v7:25.4.0"
compile 'com.android.support:multidex:1.0.1' compile 'com.android.support:multidex:1.0.1'
compile "com.facebook.react:react-native:+" // From node_modules compile "com.facebook.react:react-native:+" // From node_modules
compile project(':react-native-vector-icons') // 2017-10-31 wq add compile project(':react-native-vector-icons') // 2017-10-31 wq add
compile project(':react-native-splash-screen') //2017-11-7 wq Add for welcome screen compile project(':react-native-splash-screen') //2017-11-7 wq Add for welcome screen
compile project(':react-native-camera') compile project(':react-native-camera')
} }
// Run this once to be able to run the application with BUCK // Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use // puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) { task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile from configurations.compile
into 'libs' into 'libs'
} }
import React from 'react'; import React from 'react';
import { import {
View, View,
StatusBar, StatusBar,
StyleSheet, StyleSheet,
Image, Image,
Dimensions, Dimensions,
} from 'react-native'; } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons'; import Icon from 'react-native-vector-icons/MaterialIcons';
import Camera from 'react-native-camera'; import Camera from 'react-native-camera';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
flex: 1, flex: 1,
}, },
preview: { preview: {
flex: 1, flex: 1,
justifyContent: 'flex-end', justifyContent: 'flex-end',
alignItems: 'center', alignItems: 'center',
}, },
previewPic: { previewPic: {
flex: 1, flex: 1,
}, },
overlay: { overlay: {
position: 'absolute', position: 'absolute',
padding: 16, padding: 16,
right: 0, right: 0,
left: 0, left: 0,
alignItems: 'center', alignItems: 'center',
}, },
topOverlay: { topOverlay: {
top: 0, top: 0,
flex: 1, flex: 1,
flexDirection: 'row', flexDirection: 'row',
justifyContent: 'space-between', justifyContent: 'space-between',
alignItems: 'center', alignItems: 'center',
}, },
bottomOverlay: { bottomOverlay: {
bottom: 0, bottom: 0,
backgroundColor: 'rgba(0,0,0,0.4)', backgroundColor: 'rgba(0,0,0,0.4)',
flexDirection: 'row', flexDirection: 'row',
justifyContent: 'center', justifyContent: 'center',
alignItems: 'center', alignItems: 'center',
}, },
captureButton: { captureButton: {
padding: 15, padding: 15,
backgroundColor: 'white', backgroundColor: 'white',
borderRadius: 40, borderRadius: 40,
}, },
typeButton: { typeButton: {
padding: 5, padding: 5,
}, },
}); });
class CameraComponent extends React.Component { class CameraComponent extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.camera = null; this.camera = null;
this.state = { this.state = {
camera: { camera: {
aspect: Camera.constants.Aspect.fill, aspect: Camera.constants.Aspect.fill,
captureTarget: Camera.constants.CaptureTarget.cameraRoll, captureTarget: Camera.constants.CaptureTarget.cameraRoll,
type: Camera.constants.Type.back, type: Camera.constants.Type.back,
orientation: Camera.constants.Orientation.auto, orientation: Camera.constants.Orientation.auto,
}, },
isRecording: false, isRecording: false,
imageURI: '', imageURI: '',
}; };
this.switchCam = this.switchCam.bind(this); this.switchCam = this.switchCam.bind(this);
this.recording = this.recording.bind(this); this.recording = this.recording.bind(this);
this.takePicture = this.takePicture.bind(this); this.takePicture = this.takePicture.bind(this);
this.uploadImage = this.uploadImage.bind(this); // this.uploadImage = this.uploadImage.bind(this);
this.clear = this.clear.bind(this); this.clear = this.clear.bind(this);
this.goToUpload = this.goToUpload.bind(this); this.goToUpload = this.goToUpload.bind(this);
} }
typeIcon= () => { typeIcon= () => {
const { back, front } = Camera.constants.Type; const { back, front } = Camera.constants.Type;
if (this.state.camera.type === back) { if (this.state.camera.type === back) {
return 'camera-front'; return 'camera-front';
// icon = require('./assets/ic_camera_rear_white.png'); // icon = require('./assets/ic_camera_rear_white.png');
} else if (this.state.camera.type === front) { } else if (this.state.camera.type === front) {
return 'camera-rear'; return 'camera-rear';
} }
}; };
camButton= () => { camButton= () => {
if (!this.state.isRecording) { if (!this.state.isRecording) {
return 'videocam'; return 'videocam';
} else { } else {
return 'stop'; return 'stop';
} }
}; };
switchCam() { switchCam() {
let newType; let newType;
const { back, front } = Camera.constants.Type; const { back, front } = Camera.constants.Type;
if (this.state.camera.type === back) { if (this.state.camera.type === back) {
newType = front; newType = front;
} else if (this.state.camera.type === front) { } else if (this.state.camera.type === front) {
newType = back; newType = back;
} }
this.setState({ this.setState({
camera: { camera: {
...this.state.camera, ...this.state.camera,
type: newType, type: newType,
}, },
}); });
} }
recording() { recording() {
console.log(!this.state.isRecording); console.log(!this.state.isRecording);
if (!this.state.isRecording) { if (!this.state.isRecording) {
if (this.camera) { if (this.camera) {
this.camera.capture({ mode: Camera.constants.CaptureMode.video }) this.camera.capture({ mode: Camera.constants.CaptureMode.video })
.then(data => console.log(data)) .then(data => console.log(data))
.catch(err => console.error(err)); .catch(err => console.error(err));
this.setState({ isRecording: true }); this.setState({ isRecording: true });
} }
console.log('recording'); console.log('recording');
} else { } else {
if (this.camera) { if (this.camera) {
this.camera.stopCapture(); this.camera.stopCapture();
this.setState({ isRecording: false }); this.setState({ isRecording: false });
} }
console.log('stopped'); console.log('stopped');
} }
} }
takePicture() { takePicture() {
const options = { mode: Camera.constants.CaptureMode.still }; const options = { mode: Camera.constants.CaptureMode.still };
this.camera.capture({ metadata: options }) this.camera.capture({ metadata: options })
.then((data) => { console.log(data); this.setState({ imageURI: data.path }); }) .then((data) => { console.log(data); this.setState({ imageURI: data.path }); })
.catch(err => console.error(err)); .catch(err => console.error(err));
} }
// uploadImage() { // uploadImage() {
// let token; // let token;
// getToken().then((Apptoken) => { // getToken().then((Apptoken) => {
// if (!Apptoken) { // if (!Apptoken) {
// return Promise.reject(errors.tokenMissing()); // return Promise.reject(errors.tokenMissing());
// } // }
// token = encrypt(Apptoken); // token = encrypt(Apptoken);
// const uri = `${config.apiContextPath}/resource/${token}`; // const uri = `${config.apiContextPath}/resource/${token}`;
// const formData = new global.FormData(); // const formData = new global.FormData();
// const file = { uri: this.state.imageURI, type: 'image/jpg', name: 'tupian.jpg' }; // const file = { uri: this.state.imageURI, type: 'image/jpg', name: 'tupian.jpg' };
// //
// formData.append('file', file); // formData.append('file', file);
// console.info(formData); // console.info(formData);
// futch(uri, { // futch(uri, {
// method: 'POST', // method: 'POST',
// headers: { // headers: {
// 'Content-Type': 'multipart/form-data', // 'Content-Type': 'multipart/form-data',
// }, // },
// body: formData, // body: formData,
// }, (progressEvent) => { // }, (progressEvent) => {
// const progress = progressEvent.loaded / progressEvent.total; // const progress = progressEvent.loaded / progressEvent.total;
// }) // })
// .then(request => request.responseText)// response.text()) // .then(request => request.responseText)// response.text())
// .then((responseData) => { // .then((responseData) => {
// const response = JSON.parse(responseData); // const response = JSON.parse(responseData);
// if (response.errorCode === 0) { // if (response.errorCode === 0) {
// const name = 'addTags';// 添加标签 // const name = 'addTags';// 添加标签
// const PicUri = `${config.apiContextPath}/api/interface/user/${name}/invoke`; // const PicUri = `${config.apiContextPath}/api/interface/user/${name}/invoke`;
// console.info(PicUri); // console.info(PicUri);
// const postjson = { uri: response.data[0], tags: ['当事人信息', '当事人信息'] }; // const postjson = { uri: response.data[0], tags: ['当事人信息', '当事人信息'] };
// console.info(JSON.stringify(postjson)); // console.info(JSON.stringify(postjson));
// userApi.invokeInterface(name, postjson) // userApi.invokeInterface(name, postjson)
// // futch(PicUri, { // // futch(PicUri, {
// // method: 'POST', // // method: 'POST',
// // headers: { // // headers: {
// // 'Content-Type': 'application/json', // // 'Content-Type': 'application/json',
// // }, // // },
// // body: JSON.stringify(postjson), // // body: JSON.stringify(postjson),
// // }, (progressEvent) => { // // }, (progressEvent) => {
// // console.info(progressEvent); // // console.info(progressEvent);
// // }) // // })
// .then(request => console.info(request));// response.text()) // .then(request => console.info(request));// response.text())
// // 这里需要调用接口,对图片数据进行绑定,等待完善 // // 这里需要调用接口,对图片数据进行绑定,等待完善
// // 页面跳转,跳转到前面的详情的页面 // // 页面跳转,跳转到前面的详情的页面
// console.info('跳转'); // console.info('跳转');
// this.props.navigation.navigate('DSRInfoDetail', this.props.navigation.state.params.pID); // this.props.navigation.navigate('DSRInfoDetail', this.props.navigation.state.params.pID);
// } // }
// }) // })
// .catch((error) => { // .catch((error) => {
// console.info(error); // console.info(error);
// }); // });
// }); // });
// } // }
clear() { clear() {
this.setState({ imageURI: '' }); this.setState({ imageURI: '' });
} }
goToUpload() { goToUpload() {
this.props.navigation.navigate('DSRInfoTuPian', { imageURI: this.state.imageURI, pID: this.props.navigation.state.params.pID, TableName: this.props.navigation.state.params.TableName }); this.props.navigation.navigate('DSRInfoTuPian', { imageURI: this.state.imageURI, pID: this.props.navigation.state.params.pID, tableName: this.props.navigation.state.params.tableName });
} }
render() { render() {
if (this.state.imageURI === '') { if (this.state.imageURI === '') {
return ( return (
<View style={styles.container}> <View style={styles.container}>
<StatusBar animated hidden /> <StatusBar animated hidden />
<Camera <Camera
ref={(cam) => { ref={(cam) => {
this.camera = cam; this.camera = cam;
}} }}
style={styles.preview} style={styles.preview}
aspect={this.state.camera.aspect} aspect={this.state.camera.aspect}
captureTarget={this.state.camera.captureTarget} captureTarget={this.state.camera.captureTarget}
type={this.state.camera.type} type={this.state.camera.type}
defaultTouchToFocus defaultTouchToFocus
mirrorImage={false} mirrorImage={false}
/> />
<View style={[styles.overlay, styles.topOverlay]}> <View style={[styles.overlay, styles.topOverlay]}>
<Icon.Button name={this.typeIcon()} size={36} backgroundColor="transparent" onPress={this.switchCam} /> <Icon.Button name={this.typeIcon()} size={36} backgroundColor="transparent" onPress={this.switchCam} />
</View> </View>
<View style={[styles.overlay, styles.bottomOverlay]}> <View style={[styles.overlay, styles.bottomOverlay]}>
<Icon.Button name="photo-camera" size={48} backgroundColor="transparent" onPress={this.takePicture} /> <Icon.Button name="photo-camera" size={48} backgroundColor="transparent" onPress={this.takePicture} />
<Icon.Button name={this.camButton()} size={48} backgroundColor="transparent" onPress={this.recording} /> <Icon.Button name={this.camButton()} size={48} backgroundColor="transparent" onPress={this.recording} />
</View> </View>
</View> </View>
); );
} else { } else {
return ( return (
<View style={styles.container}> <View style={styles.container}>
<Image <Image
style={{ height: Dimensions.get('window').height, width: Dimensions.get('window').width }} style={{ height: Dimensions.get('window').height, width: Dimensions.get('window').width }}
source={{ uri: this.state.imageURI, isStatic: true }} source={{ uri: this.state.imageURI, isStatic: true }}
/> />
<View style={[styles.overlay, styles.bottomOverlay]}> <View style={[styles.overlay, styles.bottomOverlay]}>
<Icon.Button name="clear" size={48} backgroundColor="transparent" onPress={this.clear} /> <Icon.Button name="clear" size={48} backgroundColor="transparent" onPress={this.clear} />
<Icon.Button name="done" size={48} backgroundColor="transparent" onPress={this.goToUpload} /> <Icon.Button name="done" size={48} backgroundColor="transparent" onPress={this.goToUpload} />
</View> </View>
</View> </View>
); );
} }
} }
} }
export default CameraComponent; export default CameraComponent;
import React, { Component } from 'react'; import React, { Component } from 'react';
import PhotoBrowser from 'react-native-photo-browser'; import {
Platform,
export default class HomeScreen extends Component { ActionSheetIOS,
static navigationOptions = { } from 'react-native';
header: null, import PhotoBrowser from 'react-native-photo-browser';
};
export default class HomeScreen extends Component {
// onSelectionChanged = (media, index, selected) => { static navigationOptions = {
// console.info(`${media.photo} selection status: ${selected}`); header: null,
// }; };
// onActionButton = (media, index) => { onSelectionChanged = (media, index, selected) => {
// if (Platform.OS === 'ios') { console.info(`${media.photo} selection status: ${selected}`);
// ActionSheetIOS.showShareActionSheetWithOptions( };
// {
// url: media.photo, onActionButton = (media, index) => {
// message: media.caption, if (Platform.OS === 'ios') {
// }, ActionSheetIOS.showShareActionSheetWithOptions(
// () => {}, {
// () => {}, url: media.photo,
// ); message: media.caption,
// } else { },
// console.info(`handle sharing on android for ${media.photo}, index: ${index}`); () => {},
// } () => {},
// }; );
} else {
render() { console.info(`handle sharing on android for ${media.photo}, index: ${index}`);
const { }
media, };
initialIndex,
displayNavArrows, render() {
displayActionButton, const {
displaySelectionButtons, media,
startOnGrid, initialIndex,
enableGrid, displayNavArrows,
alwaysDisplayStatusBar, displayActionButton,
} = this.props.navigation.state.params.example; displaySelectionButtons,
startOnGrid,
return ( enableGrid,
<PhotoBrowser alwaysDisplayStatusBar,
onBack={this.props.navigation.pop} } = this.props.navigation.state.params.example;
mediaList={media} return (
initialIndex={initialIndex} <PhotoBrowser
displayNavArrows={displayNavArrows} onBack={this.props.navigation.pop}
displaySelectionButtons={displaySelectionButtons} mediaList={media}
displayActionButton={displayActionButton} initialIndex={initialIndex}
startOnGrid={startOnGrid} displayNavArrows={displayNavArrows}
enableGrid={enableGrid} displaySelectionButtons={displaySelectionButtons}
useCircleProgress displayActionButton={displayActionButton}
onSelectionChanged={this.onSelectionChanged} startOnGrid={startOnGrid}
onActionButton={this.onActionButton} enableGrid={enableGrid}
alwaysDisplayStatusBar={alwaysDisplayStatusBar} useCircleProgress
customTitle={(index, rowCount) => `${index} sur ${rowCount}`} onSelectionChanged={this.onSelectionChanged}
/> onActionButton={this.onActionButton}
); alwaysDisplayStatusBar={alwaysDisplayStatusBar}
} customTitle={(index, rowCount) => `${index} sur ${rowCount}`}
} />
);
}
}
import React, { PureComponent } from 'react'; import React, { PureComponent } from 'react';
import { import {
View, View,
StyleSheet, StyleSheet,
Text, Text,
TouchableOpacity, TouchableOpacity,
Image, Image,
Platform, Platform,
ScrollView, ScrollView,
} from 'react-native'; } from 'react-native';
import TagInput from 'react-native-tag-input'; import TagInput from 'react-native-tag-input';
import { InputItem } from 'antd-mobile'; import { InputItem } from 'antd-mobile';
import { createOperations, editResource, uploadResource } from '../services/resource'; import { createOperations, editResource, uploadResource } from '../services/resource';
import { currentDomain } from '../services/domain';
const styles = StyleSheet.create({
container: { const styles = StyleSheet.create({
flex: 1, container: {
}, flex: 1,
view_header_container: { },
height: 56, view_header_container: {
backgroundColor: 'white', height: 56,
flexDirection: 'row', backgroundColor: 'white',
alignItems: 'center', flexDirection: 'row',
justifyContent: 'space-around', alignItems: 'center',
}, justifyContent: 'space-around',
text_right_title: { },
color: '#000', text_right_title: {
}, color: '#000',
text_left_title: { },
color: '#000', text_left_title: {
}, color: '#000',
text_title: { },
color: '#000', text_title: {
fontSize: 18, color: '#000',
}, fontSize: 18,
// uploadImage: { },
// height: Dimensions.get('window').height, // uploadImage: {
// width: Dimensions.get('window').width, // height: Dimensions.get('window').height,
// }, // width: Dimensions.get('window').width,
}); // },
const inputProps = { });
keyboardType: 'default', const inputProps = {
placeholder: '如:身份证', keyboardType: 'default',
autoFocus: true, placeholder: '如:身份证',
style: { autoFocus: true,
fontSize: 14, style: {
marginVertical: Platform.OS === 'ios' ? 10 : -2, fontSize: 14,
}, marginVertical: Platform.OS === 'ios' ? 10 : -2,
}; },
class UploadPageComponent extends PureComponent { };
constructor(props) { class UploadPageComponent extends PureComponent {
super(props); constructor(props) {
const { imageURI, tableName, pID } = this.props.navigation.state.params; super(props);
this.state = { const { imageURI, tableName, pID } = this.props.navigation.state.params;
imageURI, this.state = {
tableName, imageURI,
pID, tableName,
tags: ['身份证', '红本', '绿本'], pID,
text: '', tags: ['身份证', '红本', '绿本'],
imageName: '', text: '',
}; imageName: '',
} };
}
onChangeTags = (tags) => {
this.setState({ tags }); onChangeTags = (tags) => {
}; this.setState({ tags });
onChangeText = (text) => { };
this.setState({ text }); onChangeText = (text) => {
this.setState({ text });
const lastTyped = text.charAt(text.length - 1);
const parseWhen = [',', ' ', ';', '\n']; const lastTyped = text.charAt(text.length - 1);
const parseWhen = [',', ' ', ';', '\n'];
if (parseWhen.indexOf(lastTyped) > -1) {
this.setState({ if (parseWhen.indexOf(lastTyped) > -1) {
tags: [...this.state.tags, this.state.text], this.setState({
text: '', tags: [...this.state.tags, this.state.text],
}); text: '',
} });
}; }
};
onCancel = () => {
this.props.onCancel(); onCancel = () => {
}; this.props.onCancel();
onUploadPhoto = () => { };
uploadResource( onUploadPhoto = () => {
this.state.imageURI, uploadResource(
(uploadId, arg) => { this.state.imageURI,
editResource(arg, createOperations().setName(this.state.imageName).setTags(this.state.tags).use(`rel://path/${this.state.tableName}/${this.state.pID}`)).then().catch(err => console.info(`上传后改名字改tag:${err}`)); (uploadId, arg) => console.info(arg),
console.info('跳转'); (uploadId, arg) => {
this.props.navigation.navigate('DSRInfoDetail', this.props.navigation.state.params.pID); currentDomain()
}, .then((result) => {
(uploadId, arg) => console.info(arg), editResource(arg, createOperations().setName(this.state.imageName).setTags(this.state.tags).use(`rel://${result.path}/${this.state.tableName}/${this.state.pID}`)).then(cc => console.info(cc)).catch(err => console.info(`上传后改名字改tag:${err}`));
) console.info('跳转');
.then(uploadId => console.log(`start task ${uploadId}`)) this.props.navigation.navigate('DSRInfoDetail', { id: this.props.navigation.state.params.pID });
.catch(err => console.log(`上传失败:${err}`)); })
}; .catch(err => console.info(err));
setImageName = (val) => { },
console.info(`val:${val}`); )
this.setState({ imageName: val }); .then(uploadId => console.log(`start task ${uploadId}`))
} .catch(err => console.log(`上传失败:${err}`));
labelExtractor = tag => tag; };
renderHeaderMenu = () => { setImageName = (val) => {
return ( console.info(`val:${val}`);
<View style={[styles.view_header_container, { backgroundColor: 'lightgray' }]}> this.setState({ imageName: val });
<TouchableOpacity }
onPress={this.onCancel} labelExtractor = tag => tag;
> renderHeaderMenu = () => {
<Text style={[styles.text_left_title, { color: '#2196F3' }]}>取消</Text> return (
</TouchableOpacity> <View style={[styles.view_header_container, { backgroundColor: 'lightgray' }]}>
<Text style={styles.text_title}>传照片</Text> <TouchableOpacity
<TouchableOpacity onPress={this.onCancel}
onPress={this.onUploadPhoto} >
> <Text style={[styles.text_left_title, { color: '#2196F3' }]}>取消</Text>
<Text style={[styles.text_right_title, { color: '#2196F3' }]}> </TouchableOpacity>
上传 <Text style={styles.text_title}>传照片</Text>
</Text> <TouchableOpacity
</TouchableOpacity> onPress={this.onUploadPhoto}
</View> >
); <Text style={[styles.text_right_title, { color: '#2196F3' }]}>
} 上传
render() { </Text>
return ( </TouchableOpacity>
<View style={styles.container}> </View>
{this.renderHeaderMenu()} );
<ScrollView> }
<Image render() {
style={{ height: 80, width: 80 }} return (
source={{ uri: this.state.imageURI, isStatic: true }} <View style={styles.container}>
/> {this.renderHeaderMenu()}
<InputItem <ScrollView>
placeholder="如:张三" <Image
data-seed="logId" style={{ height: 80, width: 80 }}
onChange={this.setImageName} source={{ uri: this.state.imageURI, isStatic: true }}
>照片名称 />
</InputItem> <InputItem
<View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: 'lightgray' }}> placeholder="如:张三"
<Text>类型</Text> data-seed="logId"
<TagInput onChange={this.setImageName}
value={this.state.tags} >照片名称
onChange={this.onChangeTags} </InputItem>
labelExtractor={this.labelExtractor} <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: 'lightgray' }}>
text={this.state.text} <Text>类型</Text>
onChangeText={this.onChangeText} <TagInput
tagColor="blue" value={this.state.tags}
tagTextColor="white" onChange={this.onChangeTags}
inputProps={inputProps} labelExtractor={this.labelExtractor}
maxHeight={75} text={this.state.text}
/> onChangeText={this.onChangeText}
</View> tagColor="blue"
</ScrollView> tagTextColor="white"
</View> inputProps={inputProps}
); maxHeight={75}
} />
} </View>
</ScrollView>
</View>
export default UploadPageComponent; );
}
}
export default UploadPageComponent;
import { NavigationActions } from 'react-navigation'; import { NavigationActions } from 'react-navigation';
import { login, userInfo } from '../services/login'; import { login, userInfo } from '../services/login';
import { errors } from '../utils/error'; import { errors } from '../utils/error';
import { setToken, setUser } from '../utils/auth'; import { setToken, setUser } from '../utils/auth';
export default { export default {
namespace: 'login', namespace: 'login',
state: {}, state: {},
reducers: { reducers: {
}, },
effects: { effects: {
*login({ payload }, { call, put }) { // 这里的put 代表 跟dispatch一样的功能,只是在effects中叫做put *login({ payload }, { call, put }) { // 这里的put 代表 跟dispatch一样的功能,只是在effects中叫做put
const payloads = { ...payload, type: 'userName', authType: 'password' }; const payloads = { ...payload, type: 'userName', authType: 'password' };
console.info(payloads); const result = yield call(login, payloads);
const result = yield call(login, payloads); const { tokenId, authResponse, remainedAuthRequirements } = result;
const { tokenId, authResponse, remainedAuthRequirements } = result; if (authResponse.status !== 'authed' && authResponse.status !== 'skipped') {
if (authResponse.status !== 'authed' && authResponse.status !== 'skipped') { throw errors.wrongPassword();
throw errors.wrongPassword(); }
} const { requirements } = remainedAuthRequirements;
console.log(authResponse); if (requirements.length > 0) {
const { requirements } = remainedAuthRequirements; throw errors.unsupportedAuthType(requirements);
if (requirements.length > 0) { }
throw errors.unsupportedAuthType(requirements); yield call(setToken, tokenId);// 这里的yield ,跟C#中的await一样
} const uInfo = yield call(userInfo);
console.log(requirements); yield call(setUser, uInfo.id, uInfo.name); // 保存用户名密码
yield call(setToken, tokenId);// 这里的yield ,跟C#中的await一样 yield put(NavigationActions.navigate({
const uInfo = yield call(userInfo); routeName: 'Main',
console.log(uInfo); }));
yield call(setUser, uInfo.id, uInfo.name); // 保存用户名密码 },
yield put(NavigationActions.navigate({ },
routeName: 'Main', subscriptions: {},
})); };
},
},
subscriptions: {},
};
/** /**
* Created by zhouhuan on 2017/10/30. * Created by zhouhuan on 2017/10/30.
*/ */
import { Toast } from 'antd-mobile'; import { Toast } from 'antd-mobile';
import { unionBy } from 'lodash'; import { unionBy } from 'lodash';
import { NavigationActions } from 'react-navigation'; import { NavigationActions } from 'react-navigation';
import { getData, getMeta } from '../../utils/DataTemplate'; import { getData, getMeta } from '../../utils/DataTemplate';
import { datasourceApi } from '../../services/datasource'; import { datasourceApi } from '../../services/datasource';
import { scan } from '../../services/idcard'; import { scan } from '../../services/idcard';
import {createOperations, editResource, uploadResource} from "../../services/resource"; import { createOperations, editResource, uploadResource } from '../../services/resource';
import { currentDomain } from '../../services/domain';
export default { import { processError } from '../../utils/error';
namespace: 'peopleInfo',
state: { export default {
sourceData: [], namespace: 'peopleInfo',
metas: [], state: {
detailData: {}, sourceData: [],
editable: false, metas: [],
disabled: true, detailData: {},
types: '', editable: false,
peopleID: '', disabled: true,
searchValue: '', types: '',
}, peopleID: '',
effects: { searchValue: '',
*jumpPage({ payload: id }, { put }) { },
yield put({ type: 'setPeopPleID', payload: id }); effects: {
yield put(NavigationActions.navigate({ *jumpPage({ payload: id }, { put }) {
routeName: 'peopleInfoDetail', yield put({ type: 'setPeopPleID', payload: id });
params: { id }, yield put(NavigationActions.navigate({
})); routeName: 'peopleInfoDetail',
}, params: { id },
*getPeopleInfo({ payload }, { put, call, select, take }) { }));
const { clear, pxingMing } = payload; },
if (clear === 'clear') { *getPeopleInfo({ payload }, { put, call, select, take }) {
yield put({ type: 'clearList', payload: {} }); const { clear, pxingMing } = payload;
} if (clear === 'clear') {
const { sourceData } = yield select(state => state.peopleInfo); yield put({ type: 'clearList', payload: {} });
const size = sourceData.length; }
const coordinate = { const { sourceData } = yield select(state => state.peopleInfo);
containerType: 'module', const size = sourceData.length;
containerName: 'query-RKInfo', const coordinate = {
datasourceName: 'QueryRKTable', containerType: 'module',
}; containerName: 'query-RKInfo',
try { datasourceName: 'QueryRKTable',
const result = yield call(getData, coordinate, { pst: size, psz: 10, params: { pxingMing } }); };
const meta = yield call(getMeta, coordinate); try {
yield put({ type: 'setMetas', payload: meta }); const result = yield call(getData, coordinate, { pst: size, psz: 10, params: { pxingMing } });
for (const row of result) { const meta = yield call(getMeta, coordinate);
yield put({ type: 'addPeople', payload: row }); yield put({ type: 'setMetas', payload: meta });
yield take('addPeople/@@end'); for (const row of result) {
} yield put({ type: 'addPeople', payload: row });
} catch (err) { yield take('addPeople/@@end');
} }
}, } catch (err) {
*addPeople({ payload }, { put }) { }
yield put({ type: 'setPeopleList', payload: { arrayData: [payload] } }); },
}, *addPeople({ payload }, { put }) {
*getPeopleDetail({ payload }, { put, call }) { yield put({ type: 'setPeopleList', payload: { arrayData: [payload] } });
const coordinate = { },
containerType: 'module', *getPeopleDetail({ payload }, { put, call }) {
containerName: 'query-RKInfo', const coordinate = {
datasourceName: 'QueryRKDetails', containerType: 'module',
}; containerName: 'query-RKInfo',
const result = yield call(getData, coordinate, { params: { pID: payload } }); datasourceName: 'QueryRKDetails',
yield put({ type: 'getPeopleDetailInfo', payload: { ...result[0] } }); };
yield put({ type: 'setEdit', payload: false }); const result = yield call(getData, coordinate, { params: { pID: payload } });
}, yield put({ type: 'getPeopleDetailInfo', payload: { ...result[0] } });
*savePeopleInfo({ payload }, { put, select, call }) { yield put({ type: 'setEdit', payload: false });
const coordinate = { },
containerType: 'module', *savePeopleInfo({ payload }, { put, select, call }) {
containerName: 'query-RKInfo', const coordinate = {
datasourceName: 'QueryRKDetails', containerType: 'module',
}; containerName: 'query-RKInfo',
const api = datasourceApi(coordinate); datasourceName: 'QueryRKDetails',
const result = yield call(api.create, payload); };
console.info(result); const api = datasourceApi(coordinate);
const { detailData } = yield select(state => state.peopleInfo); const result = yield call(api.create, payload);
console.info(detailData); const { detailData } = yield select(state => state.peopleInfo);
try { if (result === null) {
const { arg } = yield call(uploadResource, detailData.photoUri); Toast.fail('信息重复!', 2);
yield call(editResource, arg, createOperations().setName(detailData.identityCard).setTags('身份证头像').use(`rel://DangShiRenRenKouXinXi/${result}`)); } else {
} catch (e) { try {
console.info(e); yield call(uploadResource, detailData.photoUri, () => {}, (uploadId, uri) => {
} currentDomain().then(({ path }) => {
if (result === null) { const operations = createOperations()
Toast.fail('信息重复!', 2); .setName(detailData.identityCard)
} else { .setTags('身份证头像')
Toast.success('录入成功!', 1); .use(`rel://${path}/DangShiRenRenKouXinXi/${result}`);
} return editResource(uri, operations);
yield put(NavigationActions.navigate({ }).catch(err => console.info(err));
routeName: 'peopleInfoList', });
})); } catch (e) {
}, processError(e);
*addPeopleInfo(ignore, { put }) { }
yield put({ type: 'getPeopleDetailInfo', payload: {} }); Toast.success('录入成功!', 1);
yield put(NavigationActions.navigate({ }
routeName: 'addPeoppleInfo', yield put(NavigationActions.navigate({
})); routeName: 'peopleInfoList',
}, }));
*GoToPeopleDetailEditScreen({ payload: id }, { put }) { },
yield put({ type: 'setPeopPleID', payload: id }); *addPeopleInfo(ignore, { put }) {
yield put(NavigationActions.navigate({ yield put({ type: 'getPeopleDetailInfo', payload: {} });
routeName: 'peopleInfoDetailEdit', yield put(NavigationActions.navigate({
})); routeName: 'addPeoppleInfo',
}, }));
*updateDSRDetail({ payload }, { call, put }) { },
const coordinate = { *GoToPeopleDetailEditScreen({ payload: id }, { put }) {
containerType: 'module', yield put({ type: 'setPeopPleID', payload: id });
containerName: 'query-RKInfo', yield put(NavigationActions.navigate({
datasourceName: 'QueryRKDetails', routeName: 'peopleInfoDetailEdit',
}; }));
const api = datasourceApi(coordinate); },
yield call(api.update, payload.id, payload.singularData); *updateDSRDetail({ payload }, { call, put }) {
Toast.success('修改成功!', 0.5); const coordinate = {
yield put(NavigationActions.navigate({ containerType: 'module',
routeName: 'peopleInfoList', containerName: 'query-RKInfo',
})); datasourceName: 'QueryRKDetails',
yield put({ type: 'getPeopleInfo', payload: 'clear' }); };
yield put({ type: 'setDisabled', payload: true }); const api = datasourceApi(coordinate);
}, yield call(api.update, payload.id, payload.singularData);
*onEBack({ payload }, { put, call, select, take }) { Toast.success('修改成功!', 0.5);
if (payload === 'clear') { yield put(NavigationActions.navigate({
yield put({ type: 'clearList', payload: {} }); routeName: 'peopleInfoList',
} }));
const coordinate = { yield put({ type: 'getPeopleInfo', payload: 'clear' });
containerType: 'module', yield put({ type: 'setDisabled', payload: true });
containerName: 'query-RKInfo', },
datasourceName: 'QueryRKTable', *onEBack({ payload }, { put, call, select, take }) {
}; if (payload === 'clear') {
const { sourceData } = yield select(state => state.peopleInfo); yield put({ type: 'clearList', payload: {} });
const size = sourceData.length; }
const result = yield call(getData, coordinate, { pst: size, psz: 10 }); const coordinate = {
const meta = yield call(getMeta, coordinate); containerType: 'module',
yield put({ type: 'setMetas', payload: meta }); containerName: 'query-RKInfo',
for (const row of result) { datasourceName: 'QueryRKTable',
yield put({ type: 'addPeople', payload: row }); };
yield take('addPeople/@@end'); const { sourceData } = yield select(state => state.peopleInfo);
} const size = sourceData.length;
yield put(NavigationActions.navigate({ const result = yield call(getData, coordinate, { pst: size, psz: 10 });
routeName: 'peopleInfoList', const meta = yield call(getMeta, coordinate);
})); yield put({ type: 'setMetas', payload: meta });
yield put({ type: 'setDisabled', payload: true }); for (const row of result) {
}, yield put({ type: 'addPeople', payload: row });
*DuKa(ignored, { call, put }) { yield take('addPeople/@@end');
try { }
Toast.loading('读卡中...', 0); yield put(NavigationActions.navigate({
const result = yield call(scan); routeName: 'peopleInfoList',
console.info(result); }));
if (result) { yield put({ type: 'setDisabled', payload: true });
yield put({ type: 'setdetailData', payload: result }); },
} *DuKa(ignored, { call, put }) {
Toast.loading('读卡完成...', 2); try {
} catch (e) { Toast.loading('读卡中...', 0);
Toast.loading('读卡失败', 10); const result = yield call(scan);
} console.info(result);
// if (result) {
}, yield put({ type: 'setdetailData', payload: result });
}, }
reducers: { Toast.loading('读卡完成...', 2);
setPeopPleID(state, { payload }) { } catch (e) {
return { Toast.loading('读卡失败', 10);
...state, }
peopleID: payload, //
}; },
}, },
// 下拉刷新用到的,清空列表的数据 reducers: {
clearList(state) { setPeopPleID(state, { payload }) {
return { ...state, sourceData: [] }; return {
}, ...state,
getPeopleDetailInfo(state, { payload }) { peopleID: payload,
return { };
...state, },
detailData: payload, // 下拉刷新用到的,清空列表的数据
}; clearList(state) {
}, return { ...state, sourceData: [] };
setdetailData(state, { payload: { peopleName, idcard, birthDay, people, sex, addr, photoUri } }) { },
const detailData = { getPeopleDetailInfo(state, { payload }) {
xingMing: peopleName, return {
identityCard: idcard, ...state,
birthday: birthDay, detailData: payload,
minZu: people, };
xingBie: sex, },
huJiDiZhi: addr, setdetailData(state, { payload: { peopleName, idcard, birthDay, people, sex, addr, photoUri } }) {
photoUri, const detailData = {
}; xingMing: peopleName,
return { ...state, detailData }; identityCard: idcard,
}, birthday: birthDay,
setPeopleList(state, { payload: { arrayData } }) { minZu: people,
const newSourceData = unionBy(state.sourceData, arrayData, 'id'); xingBie: sex,
return { ...state, sourceData: newSourceData }; huJiDiZhi: addr,
}, photoUri,
setMetas(state, { payload }) { };
return { ...state, metas: payload }; return { ...state, detailData };
}, },
setDSRList(state, { payload }) { setPeopleList(state, { payload: { arrayData } }) {
return { const newSourceData = unionBy(state.sourceData, arrayData, 'id');
...state, return { ...state, sourceData: newSourceData };
sourceData: payload, },
}; setMetas(state, { payload }) {
}, return { ...state, metas: payload };
setEdit(state, { payload }) { },
return { setDSRList(state, { payload }) {
...state, return {
editable: payload, ...state,
}; sourceData: payload,
}, };
setDisabled(state, { payload }) { },
return { setEdit(state, { payload }) {
...state, return {
disabled: payload, ...state,
}; editable: payload,
}, };
setTypes(state, { payload }) { },
return { setDisabled(state, { payload }) {
...state, return {
types: payload, ...state,
}; disabled: payload,
}, };
setSearchValue(state, { payload }) { },
return { setTypes(state, { payload }) {
...state, return {
searchValue: payload, ...state,
}; types: payload,
}, };
}, },
}; setSearchValue(state, { payload }) {
return {
...state,
searchValue: payload,
};
},
},
};
import { AsyncStorage } from 'react-native'; import { AsyncStorage } from 'react-native';
import { NavigationActions } from 'react-navigation'; import { NavigationActions } from 'react-navigation';
// import codePush from 'react-native-code-push'; // import codePush from 'react-native-code-push';
import { checkUpdate } from '../services/update'; import { checkUpdate } from '../services/update';
import { update } from '../native/Updater'; import { update } from '../native/Updater';
import config from '../utils/config'; import config from '../utils/config';
import { encrypt } from '../utils/helper'; import { encrypt } from '../utils/helper';
import app from '../index'; import app from '../index';
export default { export default {
namespace: 'welcome', namespace: 'welcome',
state: { state: {
percent: 0, percent: 0,
}, promptText: '',
reducers: { },
setPercent(state, { payload }) { reducers: {
return { setPercent(state, { payload }) {
...state, return {
percent: payload.progress, ...state,
}; percent: payload.progress,
}, };
}, },
effects: { setPromptText(state, { payload }) {
*init(ignored, { put, call }) { return {
try { ...state,
// yield call(codePush.sync); promptText: payload.promptText,
// const result = yield call(checkUpdate); };
// const { action, deploymentInfo, tokenId } = result; },
// if (action === 'update') { },
// const token = encrypt(tokenId); effects: {
// // console.info(`${config.updateContextPath}/resource/${token}/${encodeURIComponent(deploymentInfo.uri)}`); *init(ignored, { put, call }) {
// console.log('开始'); try {
// yield call( // yield call(codePush.sync);
// update, `${config.updateContextPath}/resource/${token}/${encodeURIComponent(deploymentInfo.uri)}`, const result = yield call(checkUpdate);
// (event) => { console.info(result);
// app.getStore().dispatch({ type: 'welcome/setPercent', payload: { progress: event.progress } }); const { action, deploymentInfo, tokenId } = result;
// }, if (action === 'update' || action === 'rollback') {
// ); yield put({ type: 'setPromptText', payload: { promptText: `${action === 'update' ? '更新中...' : '回滚中'}` } });
// console.log('结束结束结束结束结束结束结束结束结束结束'); const token = encrypt(tokenId);
// } yield call(
} catch (e) { update, `${config.updateContextPath}/resource/${token}/${encodeURIComponent(deploymentInfo.uri)}`,
console.log(e); // eslint-disable-line no-console (event) => {
} app.getStore().dispatch({ type: 'welcome/setPercent', payload: { progress: event.progress } });
const token = yield call(AsyncStorage.getItem, 'token'); },
if (!token) { );
yield put(NavigationActions.navigate({ }
routeName: 'Login', } catch (e) {
})); console.log(e); // eslint-disable-line no-console
} else { }
yield put(NavigationActions.navigate({ const token = yield call(AsyncStorage.getItem, 'token');
routeName: 'Main', if (!token) {
})); yield put(NavigationActions.navigate({
} routeName: 'Login',
}, }));
}, } else {
}; yield put(NavigationActions.navigate({
routeName: 'Main',
}));
}
},
},
};
/** @module native/Updater */ /** @module native/Updater */
import { NativeModules, DeviceEventEmitter } from 'react-native'; import { NativeModules, DeviceEventEmitter } from 'react-native';
const { Updater } = NativeModules; const { Updater } = NativeModules;
/** /**
* @typedef {Object} UpdateEvent 下载事件 * @typedef {Object} UpdateEvent 下载事件
* @property {string} status 事件类型,downloading或downloaded * @property {string} status 事件类型,downloading或downloaded
* @property {number} progress 下载进度,0到100的整数 * @property {number} progress 下载进度,0到100的整数
* @property {number} current 已下载字节数 * @property {number} current 已下载字节数
* @property {number} all 总字节数 * @property {number} all 总字节数
*/ */
/** /**
* @callback UpdateCallback 下载回调 * @callback UpdateCallback 下载回调
* @param {UpdateEvent} event 下载事件 * @param {UpdateEvent} event 下载事件
*/ */
/** /**
* 下载更新包并自动安装, 下载过程中会发送Updater/downloading事件,下载完成时会发送Updater/downloaded事件 * 下载更新包并自动安装, 下载过程中会发送Updater/downloading事件,下载完成时会发送Updater/downloaded事件
* @param {string} url 更新地址 * @param {string} url 更新地址
* @param {UpdateCallback} cb 下载回调 * @param {UpdateCallback} cb 下载回调
* @returns {Promise.<void>} * @returns {Promise.<void>}
*/ */
export const update = async (url, cb) => { export const update = async (url, cb) => {
let handle1; let handle1;
let handle2; let handle2;
if (cb) { if (cb) {
handle1 = DeviceEventEmitter.addListener('Updater/downloading', (event) => { handle1 = DeviceEventEmitter.addListener('Updater/downloading', (event) => {
cb({ cb({
...event, ...event,
status: 'downloading', status: 'downloading',
}); });
}); });
handle2 = DeviceEventEmitter.addListener('Updater/downloaded', (event) => { handle2 = DeviceEventEmitter.addListener('Updater/downloaded', (event) => {
cb({ cb({
...event, ...event,
status: 'downloaded', status: 'downloaded',
}); });
}); });
} }
await Updater.update(url); console.info(Updater);
if (handle1) { await Updater.update(url);
handle1.remove(); if (handle1) {
} handle1.remove();
if (handle2) { }
handle2.remove(); if (handle2) {
} handle2.remove();
}; }
};
/**
* 取消当前更新进程 /**
* @returns {Promise.<void>} * 取消当前更新进程
*/ * @returns {Promise.<void>}
export const cancel = async () => { */
return Updater.cancel(); export const cancel = async () => {
}; return Updater.cancel();
};
/** /**
* Created by zhouhuan on 2017/10/30. * Created by zhouhuan on 2017/10/30.
*/ */
import React from 'react'; import React from 'react';
import { createForm } from 'rc-form'; import { createForm } from 'rc-form';
import { View, ScrollView } from 'react-native'; import { View, ScrollView } from 'react-native';
import { List, InputItem, Toast, WhiteSpace, WingBlank } from 'antd-mobile'; import { List, InputItem, Toast, WhiteSpace, WingBlank } from 'antd-mobile';
import Icon from 'react-native-vector-icons/FontAwesome'; import Icon from 'react-native-vector-icons/FontAwesome';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { createAction } from '../../../utils'; import { createAction } from '../../../utils';
import { currentDomain } from '../../../services/domain';
@connect(({ DSRInfoDetail }) => ({ DSRInfoDetail }))
class DSRInfoDetailScreen extends React.Component { @connect(({ DSRInfoDetail }) => ({ DSRInfoDetail }))
componentDidMount() { class DSRInfoDetailScreen extends React.Component {
const { id } = this.props.navigation.state.params; componentDidMount() {
this.props.dispatch(createAction('DSRInfoDetail/getDSRInfoDetail')(id)); const { id } = this.props.navigation.state.params;
} this.props.dispatch(createAction('DSRInfoDetail/getDSRInfoDetail')(id));
onEdit =() => { }
// this.props.dispatch(createAction('DSRInfoDetail/setEnable')(true)); onEdit =() => {
this.props.navigation.navigate('CameraPhoto', { pID: this.props.navigation.state.params, TableName: 'DangShiRenInfo' }); // this.props.dispatch(createAction('DSRInfoDetail/setEnable')(true));
}; this.props.navigation.navigate('CameraPhoto', { pID: this.props.navigation.state.params.id, tableName: 'DangShiRenInfo' });
onSubmit = () => { };
this.props.form.validateFields({ force: true }, (error, value) => { onSubmit = () => {
if (!error) { this.props.form.validateFields({ force: true }, (error, value) => {
this.props.dispatch(createAction('DSRInfoDetail/updateDSRInfoDetail')({ id: this.props.DSRInfoDetail.DSRID, singularData: value })); if (!error) {
} else { this.props.dispatch(createAction('DSRInfoDetail/updateDSRInfoDetail')({ id: this.props.DSRInfoDetail.DSRID, singularData: value }));
Toast.show('Validation failed'); } else {
} Toast.show('Validation failed');
}); }
}; });
goToViewPage =() => { };
// this.props.dispatch(createAction('DSRInfoDetail/setEnable')(true)); goToViewPage =() => {
this.props.navigation.navigate('DSRInfoFileView', { usage: `rel://DangShiRenInfo/${this.props.navigation.state.params.id}` }); currentDomain()
}; .then((result) => {
validateNoNull = (rule, value, callback) => { console.info(result);
if (value) { console.info(`rel://${result.path}/DangShiRenInfo/${this.props.navigation.state.params.id}`);
callback(); this.props.navigation.navigate('DSRInfoFileView', { usage: `rel://${result.path}/DangShiRenInfo/${this.props.navigation.state.params.id}` });
} else { })
callback(new Error('At least four charactors for account')); .catch(err => console.info(err));
} // this.props.dispatch(createAction('DSRInfoDetail/setEnable')(true));
}; };
render() { validateNoNull = (rule, value, callback) => {
const { singularData, metas, enableEdit } = this.props.DSRInfoDetail; if (value) {
const { getFieldProps } = this.props.form; callback();
if (this.props.DSRInfoDetail.enableEdit === true) { } else {
return ( callback(new Error('At least four charactors for account'));
<ScrollView> }
<WhiteSpace /> };
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}> render() {
<Icon.Button const { singularData, metas, enableEdit } = this.props.DSRInfoDetail;
name="id-card" const { getFieldProps } = this.props.form;
backgroundColor="#08BBF9" if (this.props.DSRInfoDetail.enableEdit === true) {
onPress={() => { return (
this.props.dispatch({ type: 'DSRInfoDetail/DuKa' }); <ScrollView>
}} <WhiteSpace />
> <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
读卡 <Icon.Button
</Icon.Button> name="id-card"
</View> backgroundColor="#08BBF9"
<WhiteSpace /> onPress={() => {
<List> this.props.dispatch({ type: 'DSRInfoDetail/DuKa' });
{ }}
metas.map((m) => { >
if (m.required === true) { 读卡
return ( </Icon.Button>
<InputItem </View>
{...getFieldProps(m.key, { <WhiteSpace />
initialValue: singularData[m.key], <List>
rules: [ {
{ required: true, message: '不允许为空' }, metas.map((m) => {
{ validator: this.validateNoNull }, if (m.required === true) {
], return (
})} <InputItem
clear {...getFieldProps(m.key, {
placeholder="请输入" initialValue: singularData[m.key],
editable={enableEdit} rules: [
ref={(el) => { { required: true, message: '不允许为空' },
this.customFocusInst = el; { validator: this.validateNoNull },
}} ],
> })}
姓名 clear
</InputItem> placeholder="请输入"
); editable={enableEdit}
} else { ref={(el) => {
return ( this.customFocusInst = el;
<InputItem }}
{...getFieldProps(m.key, { >
initialValue: singularData[m.key], 姓名
})} </InputItem>
clear );
placeholder="请输入" } else {
editable={enableEdit} return (
ref={(el) => { <InputItem
this.customFocusInst = el; {...getFieldProps(m.key, {
}} initialValue: singularData[m.key],
> })}
{m.label} clear
</InputItem> placeholder="请输入"
); editable={enableEdit}
} ref={(el) => {
})} this.customFocusInst = el;
{[1].map(() => { }}
return ( >
<List.Item> {m.label}
<View style={{ flexDirection: 'row', justifyContent: 'center' }}> </InputItem>
<Icon.Button );
name="save" }
backgroundColor="#08BBF9" })}
onPress={this.onSubmit} {[1].map(() => {
> return (
保存 <List.Item>
</Icon.Button> <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
</View> <Icon.Button
</List.Item> name="save"
); backgroundColor="#08BBF9"
}) onPress={this.onSubmit}
} >
</List> 保存
</ScrollView> </Icon.Button>
); </View>
} else { </List.Item>
return ( );
<ScrollView> })
<WhiteSpace /> }
<WhiteSpace /> </List>
<WingBlank> </ScrollView>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}> );
<Icon.Button } else {
name="edit" return (
backgroundColor="#08BBF9" <ScrollView>
onPress={this.onEdit} <WhiteSpace />
> <WhiteSpace />
资料上传 <WingBlank>
</Icon.Button> <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Icon.Button <Icon.Button
name="eye" name="edit"
backgroundColor="#08BBF9" backgroundColor="#08BBF9"
onPress={this.goToViewPage} onPress={this.onEdit}
> >
资料查看 资料上传
</Icon.Button> </Icon.Button>
</View> <Icon.Button
<WhiteSpace /> name="eye"
<List> backgroundColor="#08BBF9"
{ onPress={this.goToViewPage}
metas.map((m) => { >
return ( 资料查看
<List.Item </Icon.Button>
key={m.key} </View>
extra={singularData[m.key]} <WhiteSpace />
wrap <List>
> {
{m.label} metas.map((m) => {
</List.Item> return (
); <List.Item
}) key={m.key}
} extra={singularData[m.key]}
</List> wrap
</WingBlank> >
</ScrollView> {m.label}
); </List.Item>
} );
} })
} }
</List>
export default createForm()(DSRInfoDetailScreen); </WingBlank>
</ScrollView>
);
}
}
}
export default createForm()(DSRInfoDetailScreen);
/** /**
* Created by zhouhuan on 2017/11/3. * Created by zhouhuan on 2017/11/3.
*/ */
import { StackNavigator } from 'react-navigation'; import { StackNavigator } from 'react-navigation';
import PeopleInfo from './peopelInfo'; import PeopleInfo from './peopelInfo';
import PeopleDetailInfo from './peopleDetailInfo'; import PeopleDetailInfo from './peopleDetailInfo';
import AddPeopleInfo from './addPeopleInfo'; import AddPeopleInfo from './addPeopleInfo';
import peopleDetailEditScreen from "./peopleDetailEditScreen"; import peopleDetailEditScreen from './peopleDetailEditScreen';
import FileViewList from '../dangshireninfo/fileViewList';
const peopleInfoErJiScreen = StackNavigator(
{ const peopleInfoErJiScreen = StackNavigator(
peopleInfoList: { {
screen: PeopleInfo, peopleInfoList: {
}, screen: PeopleInfo,
peopleInfoDetail: { },
screen: PeopleDetailInfo, peopleInfoDetail: {
}, screen: PeopleDetailInfo,
addPeoppleInfo: { },
screen: AddPeopleInfo, addPeoppleInfo: {
}, screen: AddPeopleInfo,
peopleInfoDetailEdit: { },
screen: peopleDetailEditScreen, peopleInfoDetailEdit: {
}, screen: peopleDetailEditScreen,
}, },
{ peopleInfoFileView: {
headerMode: 'none', screen: FileViewList,
navigationOptions: { },
gesturesEnabled: false, },
}, {
}, headerMode: 'none',
); navigationOptions: {
export default peopleInfoErJiScreen; gesturesEnabled: false,
},
},
);
export default peopleInfoErJiScreen;
/** /**
* Created by zhouhuan on 2017/11/2. * Created by zhouhuan on 2017/11/2.
*/ */
import React from 'react'; import React from 'react';
import { View, ScrollView } from 'react-native'; import { View, ScrollView } from 'react-native';
import { List, InputItem, WhiteSpace, WingBlank } from 'antd-mobile'; import { List, WhiteSpace, WingBlank } from 'antd-mobile';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import Icon from 'react-native-vector-icons/FontAwesome'; import Icon from 'react-native-vector-icons/FontAwesome';
import { createAction } from '../../../utils'; import { createAction } from '../../../utils';
import { currentDomain } from '../../../services/domain';
@connect(({ peopleInfo }) => ({ peopleInfo }))
class PeopleDetailInfo extends React.Component { @connect(({ peopleInfo }) => ({ peopleInfo }))
componentDidMount() { class PeopleDetailInfo extends React.Component {
const { id } = this.props.navigation.state.params; componentDidMount() {
this.props.dispatch(createAction('peopleInfo/getPeopleDetail')(id)); const { id } = this.props.navigation.state.params;
} this.props.dispatch(createAction('peopleInfo/getPeopleDetail')(id));
onEdit =() => { }
const { id } = this.props.navigation.state.params; onEdit =() => {
this.props.dispatch(createAction('peopleInfo/GoToPeopleDetailEditScreen')(id)); const { id } = this.props.navigation.state.params;
}; this.props.dispatch(createAction('peopleInfo/GoToPeopleDetailEditScreen')(id));
render() { };
const { detailData, metas } = this.props.peopleInfo; goToViewPage =() => {
return ( currentDomain()
<ScrollView> .then((result) => {
<WhiteSpace /> this.props.navigation.navigate('peopleInfoFileView', { usage: `rel://${result.path}/DangShiRenRenKouXinXi/${this.props.navigation.state.params.id}` });
<WhiteSpace /> })
<WingBlank> .catch(err => console.info(err));
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}> // this.props.dispatch(createAction('DSRInfoDetail/setEnable')(true));
{/* <Icon.Button };
name="edit" render() {
backgroundColor="#08BBF9" const { detailData, metas } = this.props.peopleInfo;
onPress={this.onEdit} return (
> <ScrollView>
编辑 <WhiteSpace />
</Icon.Button> */} <WhiteSpace />
</View> <WingBlank>
<WhiteSpace /> <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
<List> <Icon.Button
{ name="eye"
metas.map((m) => { backgroundColor="#08BBF9"
return ( onPress={this.goToViewPage}
<List.Item >
key={m.key} 资料查看
extra={detailData[m.key]} </Icon.Button>
wrap </View>
> <WhiteSpace />
{m.label} <List>
</List.Item> {
); metas.map((m) => {
}) return (
} <List.Item
</List> key={m.key}
</WingBlank> extra={detailData[m.key]}
</ScrollView> wrap
); >
} {m.label}
} </List.Item>
export default PeopleDetailInfo; );
})
}
</List>
</WingBlank>
</ScrollView>
);
}
}
export default PeopleDetailInfo;
import React, { Component } from 'react'; import React, { Component } from 'react';
import { View, StyleSheet, Text } from 'react-native'; import { View, StyleSheet, Text } from 'react-native';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import SplashScreen from 'react-native-splash-screen'; import SplashScreen from 'react-native-splash-screen';
import { createAction } from '../utils/index'; import { createAction } from '../utils/index';
import PercentageCircle from '../components/roundProgressBarComponent'; import PercentageCircle from '../components/roundProgressBarComponent';
@connect(({ welcome }) => ({ welcome })) @connect(({ welcome }) => ({ welcome }))
class WelcomeScreen extends Component { class WelcomeScreen extends Component {
componentDidMount() { componentDidMount() {
const { dispatch } = this.props; const { dispatch } = this.props;
dispatch(createAction('welcome/init')()); dispatch(createAction('welcome/init')());
SplashScreen.hide();// 隐藏启动平 SplashScreen.hide();// 隐藏启动平
} }
// 待改进,改成启动页,目前因为时间和技术的问题,搁置。wq write IsUpdate = () => {
render() { if (this.props.welcome.promptText !== '') {
return ( return <PercentageCircle radius={60} percent={this.props.welcome.percent} color="#3498db" />;
<View style={styles.container}> }
<Text>wlecome</Text> };
<View> // 待改进,改成启动页,目前因为时间和技术的问题,搁置。wq write
<PercentageCircle radius={60} percent={this.props.welcome.percent} color="#3498db" /> render() {
</View> return (
</View> <View style={styles.container}>
); <Text>{this.props.welcome.promptText === '' ? 'welcome' : this.props.welcome.promptText}</Text>
} <View>
} {
this.IsUpdate()
const styles = StyleSheet.create({ }
container: { </View>
flex: 1, </View>
justifyContent: 'center', );
alignItems: 'center', }
backgroundColor: '#ffffff', }
},
img: { const styles = StyleSheet.create({
flex: 1, container: {
width: 400, flex: 1,
height: 200, justifyContent: 'center',
resizeMode: 'contain', alignItems: 'center',
}, backgroundColor: '#ffffff',
}); },
img: {
flex: 1,
export default WelcomeScreen; width: 400,
height: 200,
resizeMode: 'contain',
},
});
export default WelcomeScreen;
/* eslint-disable no-undef */ /* eslint-disable no-undef */
/** /**
* Created by yaohx_169 on 2017/6/6. * Created by yaohx_169 on 2017/6/6.
*/ */
export const cookie = { export const cookie = {
token: 'token', token: 'token',
userId: 'userId', userId: 'userId',
userName: 'userName', userName: 'userName',
domainPath: 'domainPath', domainPath: 'domainPath',
domainName: 'domainName', domainName: 'domainName',
}; };
export const errors = { export const errors = {
exception: 0x00010000, exception: 0x00010000,
no_such_user: 0x00010001, no_such_user: 0x00010001,
invalid_token: 0x00010003, invalid_token: 0x00010003,
// client error: // client error:
token_missing: 0x00000001, token_missing: 0x00000001,
wrong_password: 0x00000002, wrong_password: 0x00000002,
unsupported_auth_type: 0x00000003, unsupported_auth_type: 0x00000003,
}; };
const defaultDateFormat = 'YYYY-MM-DD'; const defaultDateFormat = 'YYYY-MM-DD';
const defaultTimeFormat = 'HH:mm:ss'; const defaultTimeFormat = 'HH:mm:ss';
const defaultDateTimeFormat = `${defaultDateFormat} ${defaultTimeFormat}`; const defaultDateTimeFormat = `${defaultDateFormat} ${defaultTimeFormat}`;
const config = { const config = {
name: 'Jbpm Demo', name: 'Jbpm Demo',
productId: 'manager-app-sz', productId: 'manager-app-sz',
footerText: '上海铂蓝信息科技有限公司', footerText: '上海铂蓝信息科技有限公司',
contextPath: '', contextPath: '',
updateContextPath: 'http://192.168.1.22:8080/app', updateContextPath: 'http://14.21.68.149:9088/app',
// apiContextPath: 'http://14.21.68.149:9089/test', apiContextPath: 'http://14.21.68.149:9087/sz01',
apiContextPath: 'http://192.168.1.22:8080/sz', // updateContextPath: 'http://192.168.1.22:8080/app',
defaultDateFormat, // apiContextPath: 'http://192.168.1.22:8080/sz',
defaultTimeFormat, defaultDateFormat,
defaultDateTimeFormat, defaultTimeFormat,
pubKey: '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+/Rs6dYmdtETjHCZq4LF3QjLM/DocRAXrqtMULZf+579dAn+CiM8noLplZT/DRwvfK822eq8sypH+a4NqP7942pPVjOudVvKfiJvmm2TOQHvQ7vi3iyZVdlsxX72JNFo1Ocqwj48aIC/OJ4bMf/VyCKrmKrU2iXND+I4BN8cfhwIDAQAB-----END PUBLIC KEY-----', defaultDateTimeFormat,
}; pubKey: '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+/Rs6dYmdtETjHCZq4LF3QjLM/DocRAXrqtMULZf+579dAn+CiM8noLplZT/DRwvfK822eq8sypH+a4NqP7942pPVjOudVvKfiJvmm2TOQHvQ7vi3iyZVdlsxX72JNFo1Ocqwj48aIC/OJ4bMf/VyCKrmKrU2iXND+I4BN8cfhwIDAQAB-----END PUBLIC KEY-----',
};
export default config;
export default config;
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论