AttachmentUpdateView.js 19.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
import React, {Component} from 'react';
import {
    View,
    Text,
    Image,
    TouchableOpacity,
    Modal,
    StyleSheet, Platform, NativeModules,
} from 'react-native';
import {getFooterBottom, xnBorderWidth, xnToast} from "../utils/utils";
import RNFetchBlob from "rn-fetch-blob";
import config from "../config";
import AppService from "../service/AppService";
import {DocumentPicker, DocumentPickerUtil} from "react-native-document-picker";

/**
 * 附件上传
 */
export default class AttachmentUpdateView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            attachmentList:[],
            isLoading: false,
            showSelectModal: false
        }

        this.attrData = this.props.attrData;
        this.extendData = JSON.parse(this.attrData.data)
    }

    // 打开选择遮罩
    openSelectModal() {
        this.setState({
            showSelectModal: true,
        });
    }

    // 关闭选择遮罩
    closeSelectModal() {
        this.setState({
            showSelectModal: false,
        });
    }

    upLoadFile () {
        const _this = this;
        if (Platform.OS === 'android') {
            console.log('upload', '------------android------------');

            // 安卓上传文件
            const FilePickerManager = require('NativeModules').FilePickerManager;
            FilePickerManager.showFilePicker(null, (res) => {
                console.log('Response = ', res);
                if (res.didCancel) {
                    console.log('User cancelled file picker');
                } else if (res.error) {
                    console.log('FilePickerManager Error: ', res.error);
                } else {
                    if (Number(res.fileSize) >= 5 * 1024 * 1024) {
                        xnToast('文件大小超过5M,无法上传');
                        return;
                    }
                    if (res.path && res.path.length > 0) {
                        const ext = res.path.substring(res.path.lastIndexOf('.') + 1).toLowerCase();
                        if (ext.toLowerCase() == 'pdf' || ext.toLowerCase() == 'docx' || ext.toLowerCase() == 'doc' || ext.toLowerCase() == 'rar' || ext.toLowerCase() == 'zip' || ext.toLowerCase() == 'txt'
                            || ext.toLowerCase() == 'ppt' || ext.toLowerCase() == 'xls' || ext.toLowerCase() == 'xlsx' || ext.toLowerCase() == 'jpg' || ext.toLowerCase() == 'jpeg' || ext.toLowerCase() == 'png') {
                        } else {
                            xnToast('暂不支持该格式,无法上传,文件类型支持pdf,docx,doc,rar,zip,txt,ppt,xls,xlsx,jpg,jpeg,png');
                            return;
                        }
                    } else {
                        xnToast('暂不支持该格式,无法上传,文件类型支持pdf,docx,doc,rar,zip,txt,ppt,xls,xlsx,jpg,jpeg,png');
                        return;
                    }
                    const file = {
                        uri: '',
                        name: 'ATTACHMENT',
                        type: 'file',
                    };
                    _this.setState({
                        showSelectModal: false,
                        progressNum: 0,
                        isLoading: true,
                    });

                    RNFetchBlob.fetch('POST', `${config.uploadUrl}?passportId=`+_this.passportId, {
                        // Authorization : "Bearer access-token",
                        //  otherHeader : "foo",
                        'Content-Type': 'multipart/form-data',
                    }, [
                        { name: 'File', filename: res.fileName, type: 'ATTACHMENT', data: RNFetchBlob.wrap(res.path) }, // RNFetchBlob.wrap(response.path), File:file
                        { name: 'FileName', data: res.fileName },
                        { name: 'Type', data: 'ATTACHMENT' },
                        { name: 'Ext', data: res.path ? res.path.substring(res.path.lastIndexOf('.') + 1) : 'tmp' },

                    ])
                        .uploadProgress((written, total) => {
                            _this.setState({
                                progressNum: Math.floor(written / total * 100),
                            });
                            console.log('uploaded', written / total);
                        })
                        .then((resp) => {
                            console.log(JSON.stringify(resp), '------------上传成功------------');
                            let  file=JSON.parse(JSON.parse(JSON.stringify(resp)).data);

                            AppService.uploadbyfileid({
                                fileId: file.id,
                                businessId: _this.state.businessId,
                                businessType:_this.state.item.type=='PICTURE'? "WORKFLOW":'TEMP_TASK_ATTACHMENT',
                                businessCategory:_this.state.item.type=='PICTURE'? "COMMON":'TEMP_TASK',
                            }).then((response) => {
                                _this._setEndProgress();
                                _this.setState({
                                    isLoading: false,
                                }, () => {
                                    const item= response.attachment;
                                    const attachmentList= _this.state.attachmentList||[];
                                    attachmentList.push({
                                        filePath: item.filePath,
                                        type: _this.getAttachmentType(item.displayName),
                                        displayName: item.displayName,
                                        filename : item.displayName.substring(0, item.displayName.lastIndexOf(".")),
                                        fileSize :  file.fileSize,
                                        id:_this.state.item.type=='PICTURE'?file.id:item.id
                                    });
                                    _this.state.item.value = JSON.stringify( attachmentList );
                                    _this.setState({
                                        item:null
                                    });

                                    // _this.setState({
                                    //
                                    // });
                                });
                            }).catch((err) => {
                                _this.setState({
                                    isLoading: false,
                                });
                                xnToast(err.message);
                            });
                        })
                        .catch((err) => {
                            _this.setState({
                                isLoading: false,
                            });
                        });
                }
            });
        } else {
            console.log('upload', '------------ios------------');

            DocumentPicker.show({
                filetype: [__IOS__ ? DocumentPickerUtil.allFiles() : 'public.content'],
            }, (error, res) => {
                if (res.fileSize >= 5 * 1024 * 1024) {
                    xnToast('文件大小超过5M,无法上传');
                    return;
                }
                if (res.fileName && res.fileName.length > 0) {
                    const ext = res.fileName.substring(res.fileName.lastIndexOf('.') + 1).toLowerCase();
                    if (ext.toLowerCase() == 'pdf' || ext.toLowerCase() == 'docx' || ext.toLowerCase() == 'doc' || ext.toLowerCase() == 'rar' || ext.toLowerCase() == 'zip' || ext.toLowerCase() == 'txt'
                        || ext.toLowerCase() == 'ppt' || ext.toLowerCase() == 'xls' || ext.toLowerCase() == 'xlsx' || ext.toLowerCase() == 'jpg' || ext.toLowerCase() == 'jpeg' || ext.toLowerCase() == 'png') {
                    } else {
                        xnToast('暂不支持该格式,无法上传,文件类型支持pdf,docx,doc,rar,zip,txt,ppt,xls,xlsx,jpg,jpeg,png');
                        return;
                    }
                } else {
                    xnToast('暂不支持该格式,无法上传,文件类型支持pdf,docx,doc,rar,zip,txt,ppt,xls,xlsx,jpg,jpeg,png');
                    return;
                }
                _this.setState({
                    showSelectModal: false,
                    isLoading: true,
                });
                _this._setAutoProgress();

                const  fun = async function () {
                    console.warn(JSON.stringify(res));
                    console.warn(JSON.stringify(res));
                    const file = {
                        uri: res.uri,
                        name: 'ATTACHMENT',
                        type: res.type,
                    };
                    const body = new FormData();
                    body.append('File', file);
                    body.append('Type', 'ATTACHMENT');
                    body.append('Ext', res.fileName ? res.fileName.substring(res.fileName.lastIndexOf('.') + 1) : 'tmp');
                    body.append('FileName', 'FileName');

                    const options = {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'multipart/form-data',
                        },
                        body,
                    };
                    const resp = await fetch(`${config.uploadUrl}?passportId=`+_this.passportId, options);
                    const text = await resp.text();
                    console.warn('RESP:', text);
                    const json = JSON.parse(text);
                    // 如果请求失败
                    if (resp.status !== 200) {
                        _this.setState({
                            isLoading: false,
                        });
                        throw new ResponseError(json.message, resp.status, json);
                    } else {
                        _this._setEndProgress();
                        AppService.uploadbyfileid({
                            fileId: json.id,
                            businessId: _this.state.businessId,
                            businessType:_this.state.item.type=='PICTURE'? "WORKFLOW":'TEMP_TASK_ATTACHMENT',
                            businessCategory:_this.state.item.type=='PICTURE'? "COMMON":'TEMP_TASK',
                        }).then((response) => {
                            _this._setEndProgress();
                            setTimeout(function () {
                                _this.setState({
                                    isLoading: false,
                                }, () => {
                                    const item= response.attachment;
                                    const attachmentList= _this.state.attachmentList||[];
                                    attachmentList.push({
                                        filePath: item.filePath,
                                        type: _this.getAttachmentType(item.displayName),
                                        displayName: item.displayName,
                                        filename : item.displayName.substring(0, item.displayName.lastIndexOf(".")),
                                        fileSize :  json.fileSize,
                                        id:_this.state.item.type=='PICTURE'?json.id:item.id
                                    });
                                    _this.state.item.value = JSON.stringify( attachmentList );
                                    _this.setState({
                                        item:null
                                    });
                                });
                            }, 100);
                        }).catch((err) => {
                            _this.setState({
                                isLoading: false,
                            });
                            xnToast(err.message);
                        });
                    }
                };

            });
        }
    }

    viewImg = (type, filePath, fileName, size, imageList, attr, index) => {
        let _this = this;
        if (type == "img") {
            let images = [];
            images.push({"url": filePath})
            _this.setState({
                images: images,
                imagesIndex: index || 0,
                modalVisible: true
            })
        } else {
            NativeModules.system.downlaodFiles(fileName, filePath, size + "")
        }
    }

    _renderAttachmentList = (v, i) => {
        return (
            <View style={styles.attachmentsItemLayout} key={i}>
                <TouchableOpacity style={styles.attachmentsItemBox} activeOpacity={1} onPress={() => {

                    this.viewImg(v.type, v.filePath, v.displayName, v.size)
                }}>
                    <View style={styles.attachmentsItemBoxImg}>
                        {v.type != "img" && v.type == "folder" &&
                        <Image style={styles.attachmentsItemImage} source={require('../img/other.png')}
                               resizeMode="contain"></Image>}
                        {v.type != "img" && v.type == "xls" &&
                        <Image style={styles.attachmentsItemImage} source={require('../img/excle.png')}
                               resizeMode="contain"></Image>}
                        {v.type != "img" && v.type == "doc" &&
                        <Image style={styles.attachmentsItemImage} source={require('../img/word.png')}
                               resizeMode="contain"></Image>}
                        {v.type != "img" && v.type == "ppt" &&
                        <Image style={styles.attachmentsItemImage} source={require('../img/ppt.png')}
                               resizeMode="contain"></Image>}
                        {v.type != "img" && v.type == "txt" &&
                        <Image style={styles.attachmentsItemImage} source={require('../img/txt.png')}
                               resizeMode="contain"></Image>}
                        {v.type != "img" && v.type == "pdf" &&
                        <Image style={styles.attachmentsItemImage} source={require('../img/pdf.png')}
                               resizeMode="contain"></Image>}
                        {v.type != "img" && v.type == "zip" &&
                        <Image style={styles.attachmentsItemImage} source={require('../img/rar.png')}
                               resizeMode="contain"></Image>}
                        {v.type != "img" && v.type == "other" &&
                        <Image style={styles.attachmentsItemImage} source={require('../img/other.png')}
                               resizeMode="contain"></Image>}
                        {v.type == "img" && <Image style={styles.attachmentsItemImage}
                                                   source={{uri: v.filePath + "?x-oss-process=image/resize,m_lfit,w_100,h_100"}}
                                                   resizeMode="contain"></Image>}
                    </View>
                    <View style={styles.attachmentsItemName}>
                        <Text style={styles.attachmentsItemNameInfo} numberOfLines={1} ellipsizeMode='tail'>{v.filename}</Text>
                    </View>
                </TouchableOpacity>
            </View>

        )
    };

    render() {
        let {name, code, type, description, isRequired, isPreview} = this.attrData;

        // fileType all=全部|picture=图片|video=视频|audio=音频|excel|ppt|word|pdf|txt
        let {buttonText, fileType, maxFileSize, showTips, multiUpload} = this.extendData;

        return (
            <View style={{width:'100%',paddingLeft:15,backgroundColor:'#fff',paddingTop:10}}>
                <View style={{flexDirection:'row'}}>
                    {isRequired&&<Text style={{ color: "#FF3030" }}>* {" "}</Text>}
                    {isRequired&&<Text style={{ color: "#fff" }}>* {" "}</Text>}
                    <Text style={{ fontSize: 17, color: "#000", }}>{name ||''}:</Text>
                </View>
                <View style={{flexDirection: "row", flexWrap: "wrap"}}>
                    {/*{item.value&&item.value!=''&&JSON.parse(item.value).map((v, i) => this._renderAttachmentList(v, i))}*/}
                    <View style={styles.attachmentsItemLayout}>
                        <TouchableOpacity style={styles.attachmentsItemBox} activeOpacity={1} onPress={() => {
                            this.state.attachmentList = JSON.parse(this.attrData.value?this.attrData.value:'[]')||[];
                            this.state.item = this.attrData;
                            Platform.OS === 'android' ? this.upLoadFile() : this.openSelectModal();
                        }}>
                            <View style={styles.attachmentsItemBoxImg}>
                                <Image style={styles.attachmentsItemImageAdd} source={require('../img/add-icon.png')}
                                       resizeMode="contain"></Image>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>

                <Modal
                    animationType="none"
                    transparent
                    visible={this.state.showSelectModal}
                    onRequestClose={() => {}}
                >
                    <View style={styles.modalWrap}>
                        <View style={styles.outerContainer}>
                            <TouchableOpacity style={styles.innerRow} onPress={() => this.upLoadImage()}>
                                <Text style={{ fontSize: 16, color: '#666666' }}>本地相册</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.innerRow} onPress={() => this.upLoadFile()}>
                                <Text style={{ fontSize: 16, color: '#666666' }}>iCloud</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[styles.innerRow,{marginTop:5}]} onPress={() => this.closeSelectModal()}>
                                <Text style={{ fontSize: 16, color: '#6B6D75' }}>取消</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </Modal>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    attachmentsItemName: {
        height: 20,
        width: 50,
        justifyContent: "center",
        flexDirection: "row",
        alignItems: "center",
    },
    attachmentsItemBox: {
        height: 70,
        width: 50,
    },
    attachmentsItemLayout: {
        width: "20%",
        height: 70,
        marginBottom: 10,
        justifyContent: "center",
        flexDirection: "row",
    },
    attachmentsItemBoxImg: {
        height: 50,
        width: 50,
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 3,
        borderColor: "#ddd",
        borderStyle: "solid",
        borderWidth: xnBorderWidth(),
    },
    attachmentsItemImageAdd: {
        height: 12,
        width: 12,
    },
    modalWrap: {
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0, 0, 0, 0.3)',
        position: 'absolute',
        left: 0,
        top: 0,
    },
    innerRow: {
        height:50,
        borderBottomColor:"#ddd",
        borderBottomWidth:1,
        justifyContent:"center",
        alignItems:"center",
        backgroundColor: '#fff',
    },
    outerContainer: {
        width: '100%',
        height: 'auto',
        position: 'absolute',
        left: 0,
        bottom: 0,
        paddingBottom: getFooterBottom()
    },
});