import React from 'react'; import { SafeAreaView, ScrollView, StatusBar, StyleSheet, Text, Image, TouchableOpacity, View, DeviceEventEmitter, ViewStyle } from 'react-native'; import { adaptFilePath, BaseUrl, colors, getCurrentDateNs, getFileType, isArray, isEmpty, isIos, onePx, parseImageList, px2dp, toast, toastShort, uuid } from '../../utils'; import ImagePicker from 'react-native-image-crop-picker'; import RNFetchBlob from 'rn-fetch-blob'; import RNfs from 'react-native-fs'; import { navigate } from '../../NavigationService'; import * as Progress from 'react-native-progress'; import redux from './../../redux/store'; import { BjTypeImage } from '../../utils/types'; interface Props { initImageListStr?: string title?: string isNeeded?: boolean icon?: 'add' | 'camera', hasPermission?: boolean, maxLengthLimit?: number //提供3/4两种选择 handleOffline?: boolean //手动开启离线 inlineLayout?: boolean onImageRecived?: Function } interface State { imgList: Array, fileExistList: Array } export default class KitImageListView extends React.Component { constructor(props: Props) { super(props); }; public delayTimer = null; public imageDeleteListener = null; public currentKitTag = uuid(); public onSelectedImagePickerListener = null; public pureCameraResultListener = null; public readonly state: Readonly = { imgList: [], fileExistList: [], }; componentDidMount() { this.onSelectedImagePickerListener = DeviceEventEmitter.addListener('on-selected-image-picker', (a) => { if (a.type && a.tag) { if (a.tag === this.currentKitTag) { console.log(a.type) this.selectWay(a.type) } } }) this.imageDeleteListener = DeviceEventEmitter.addListener("on-delete-img", (a) => { let imgList = this.state.imgList; imgList.splice(a.deleteIndex, 1); this.setState({ imgList }) }) this.pureCameraResultListener = DeviceEventEmitter.addListener('pure-camera-result', (a) => { if (this.currentKitTag == a.key) { let imgList = this.state.imgList; // alert(a.uri) // console.log("原始图片", a.uri) // RNfs.copyFile('/var/mobile/Containers/Data/Application/67151EA6-EC10-4D20-BF63-84F500ADEDA9/Library/Caches/Camera/32824D9E-E131-4E4F-860A-B8B3670073B9.jpg', RNfs.DocumentDirectoryPath + '/beijihua/photolib/' + uuid() + getFileType(a.uri)) // .then(res => { // console.log("图片存储成功", res) // }) // .catch(err => { // console.log("图片存储失败", err) // }) // copyText(RNfs.DocumentDirectoryPath + '/beijihua/photolib/' + uuid() + getFileType(a.uri)); // alert(RNfs.DocumentDirectoryPath + '/beijihua/photolib/' + uuid() + getFileType(a.uri)); let imgObj: BjTypeImage = { imagePath: a.uri, id: uuid(), progress: 0, url: a.uri } imgList.push(imgObj); this.setState({ imgList }) } }) }; componentWillUnmount() { this.delayTimer && clearTimeout(this.delayTimer); this.imageDeleteListener && this.imageDeleteListener.remove(); this.onSelectedImagePickerListener && this.onSelectedImagePickerListener.remove(); this.pureCameraResultListener && this.pureCameraResultListener.remove(); this.setState = (state, callback) => { return; } } getImageList() { const { handleOffline } = this.props; let { imgList } = this.state; return imgList; //非离线数据模式,且非外部手动强制离线 // if (!this.checkHasOffLine() && !handleOffline) { // const findUploadingImage = imgList.find(ele => { // return ele.progress < 1; // }); // if (findUploadingImage) { // toastShort("请等待图片上传完毕"); // return false; // } // } else { // imgList.map(ele => { // ele.url = ele.img_url; // }) // } return imgList; }; checkFileExist = async (filePath) => { const fileExist = await RNfs.exists(filePath); // console.log("fileExist----->", fileExist) return fileExist; }; checkHasOffLine = (): boolean => { try { return redux.getState().AppConfig.hasOffLine; } catch (e) { return false; } }; openCamera() { // Per navigate('PureCamera', { key: this.currentKitTag }) return false; if (!isIos()) { DeviceEventEmitter.emit('open-select-image-picker', { tag: this.currentKitTag }) } else { navigate('PureCamera', { key: this.currentKitTag }) } // const { hasPermission = true, handleOffline = false } = this.props; // if (!hasPermission) { // return toast("很抱歉,您暂无此操作权限") // } } ///private/var/mobile/Containers/Data/Application/ //3D87348C-D961-4CA3-8253-7B6D840AD30A/tmp/ //react-native-image-crop-picker/99C3D55D-84E6-47D4-8146-7680E77BA8D4.jpg ///var/mobile/Containers/Data/Application/ //38A58037-75BB-408A-A7C9-1B0B45A64785/Documents/1662857875.jpg selectWay(type: 'photoLib' | 'camera') { switch (type) { case 'camera': ImagePicker.openCamera({ multiple: false, waitAnimationEnd: true, cropping: false, compressImageMaxWidth: 1080, compressImageMaxHeight: 1920, mediaType: 'photo', includeBase64: false, }) .then(image => { if (image) { console.log("拍摄----->", image) // alert(image.path) let imgList = this.state.imgList; let imgObj: BjTypeImage = { imagePath: image.path, id: uuid(), progress: 0, url: image.path } imgList.push(imgObj); // if (this.checkHasOffLine() || handleOffline) { // //toastShort("当前已切换到本地暂存模式,图片不做立即上传处理") // } else { // this.startUploadImage(imgObj); // } this.setState({ imgList }) } }) .catch(err => { }) break; case 'photoLib': ImagePicker.openPicker({ multiple: false, waitAnimationEnd: true, cropping: false, compressImageMaxWidth: 1080, compressImageMaxHeight: 1920, mediaType: 'photo', includeBase64: false, }) .then(image => { if (image) { let imgList = this.state.imgList; let imgObj: BjTypeImage = { imagePath: image.path, id: uuid(), progress: 0, url: image.path } imgList.push(imgObj); this.setState({ imgList }) } }) .catch(err => { }) break; } }; setImageList(imgList) { console.log("setImageList", imgList) try { const imageList = parseImageList(imgList) this.setState({ imgList: imageList }) } catch (err) { console.log("解析图片失败", err) } }; setMergeImageList(_imgList) { let { imgList } = this.state; if (imgList.length < 4) { imgList = _imgList.concat(imgList) } else { toast("照片已达到四张, 请删除后重试!") } this.setState({ imgList }) }; startUploadImage(img: BjTypeImage) { let { imgList } = this.state; const fetchUrl = BaseUrl + '/fontapi/file/upload'; //拼接接口地址 let body = [ { name: 'file', filename: getFileType(img.imagePath), data: RNFetchBlob.wrap(img.imagePath) }, { name: "type", data: "1" } ]; RNFetchBlob .fetch('POST', fetchUrl, { }, body) .progress((written, total) => { }) .uploadProgress((received, total) => { console.log(received, total) let perent = received / total; console.log('文件上传', perent); imgList.forEach(ele => { if (ele.id == img.id) { ele.progress = Number(perent); } }); console.log("处理后的imglist", imgList) this.setState({ imgList }) }) .then((response) => response.json()) .then((res) => { console.log("文件上传结果", res) if (res.ykk_code == 10000) { imgList.forEach(ele => { if (ele.id == img.id) { ele.progress = 1; } }); this.setState({ imgList }) this.delayTimer = setTimeout(() => { imgList.forEach(ele => { if (ele.id == img.id) { ele.url = res.info.url; } }); this.setState({ imgList }) }, 200); } else { toastShort(res.msg) } }) .catch((error) => { }); }; showPreViewer(index) { const { imgList } = this.state; let _imgList = imgList.map(ele => { return { url: ele.url ? this.adaptImagePath(ele.url) : this.adaptImagePath(ele.imagePath) } }); navigate("ImagePreviewPage", { imgList: _imgList, index }) }; getImgBlockStyle(index: number): ViewStyle { const { maxLengthLimit = 8, inlineLayout } = this.props; let styleObj: ViewStyle = { position: 'relative', width: px2dp(90), height: px2dp(90), borderRadius: px2dp(2), justifyContent: 'center', alignItems: 'center', borderWidth: onePx, borderColor: colors.borderLineColor, overflow: 'hidden', backgroundColor: colors.bgColor }; if (maxLengthLimit == 3) { styleObj.width = px2dp(90); styleObj.height = px2dp(90) } else { styleObj.width = px2dp(76); styleObj.height = px2dp(76); if ((index + 1) % 4 != 0) { styleObj.marginRight = px2dp(6); } styleObj.marginBottom = px2dp(8) } return styleObj; } adaptImagePath(imagePath: string) { // let contentList = imagePath.split('/'); // const imageFileName = contentList[contentList.length - 1]; // return RNfs.DocumentDirectoryPath + "/" + imageFileName; return adaptFilePath(imagePath) }; render() { const { title = "拍摄照片", isNeeded = false, icon = "camera", maxLengthLimit = 8, inlineLayout = false } = this.props; const { imgList, fileExistList } = this.state; return ( { title ? {title} {isNeeded && *} : null } { imgList.map((img, index) => { //console.log("this.checkFileExist(img.imagePath)", this.checkFileExist(img.imagePath)) return ( this.showPreViewer(index)} style={this.getImgBlockStyle(index)}> { !img.url ? : null } {/* {img.imagePath && fileExistList[index] ? img.imagePath : img.url } */} ) }) } { imgList.length < maxLengthLimit ? { icon == 'camera' ? : } : null } ) } } const styles = StyleSheet.create({ container: { width: px2dp(350), flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'flex-start', paddingHorizontal: px2dp(10), marginBottom: px2dp(8) }, inlineContainer: { width: px2dp(258), marginBottom: px2dp(0) }, formRowTitle: { fontSize: 16, lineHeight: px2dp(20), color: colors.blackColor, marginTop: px2dp(10), marginBottom: px2dp(6) }, content: { width: '100%', flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', flexWrap: 'wrap' }, icon: { width: px2dp(42), height: px2dp(42), tintColor: "#aaa" }, item: { position: 'relative', width: px2dp(90), height: px2dp(90), borderRadius: px2dp(2), justifyContent: 'center', alignItems: 'center', borderWidth: onePx, borderColor: colors.borderColor, marginRight: px2dp(10), overflow: 'hidden', backgroundColor: colors.bgColor, marginBottom: px2dp(10) }, progressOverlay: { position: 'absolute', left: 0, top: 0, width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center', zIndex: 999, backgroundColor: "rgba(0,0,0,0.2)", }, itemImage: { width: '100%', height: '100%' } })