import React, {Component} from 'react';
import {
    View,
    Text,
    TouchableOpacity,
    StyleSheet,
    Dimensions,
    FlatList,
    Modal, Alert, ToastAndroid,
} from 'react-native';

import CameraRoll from '@react-native-community/cameraroll';
import {createAction} from '../../utils';
import {connect} from 'react-redux';
import {ActivityIndicator, Provider} from '@ant-design/react-native';
import {CachedImage} from 'react-native-cached-images-zzly';

import ImageViewer from 'react-native-image-zoom-viewer';
import RNFS from 'react-native-fs';
import SyncStorage from 'sync-storage';

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

//const IMAGE_PLACEHOLDER = require('../../../assets/images/bg_mine_header.png');
let subjectImages = [];
let _subjectRows = {};

class Row extends Component {

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
        };
    }

    setVisible = (visible) => {
        // this.props.visible = visible
        this.setState({visible: visible});
    };

    calcSize = (item) => {
        let width, height = 0;
        if (item.width < SCREEN_WIDTH) {
            width = item.width;
        } else {
            width = SCREEN_WIDTH - 20;
        }
        height = Math.floor((width * item.height) / item.width);
        return {marginHorizontal: 5, marginVertical: 5, width, height};
    };

    render() {
        const {row, id} = this.props;
        const baseURL = SyncStorage.get('baseURL');
        const style = this.calcSize(row);
        const height = Math.floor((SCREEN_WIDTH * row.height) / row.width) + 20;
        const url = baseURL + row.picture
        //console.log('id=' + id, 'visible=' + this.state.visible)
        // if(!this.state.visible){
        //     //取消网络图片的加载
        //     ImageCache.get().cancel(row.uri);
        // }
        return (
            <View style={{borderBottomWidth: 10, borderBottomColor: '#f5f5f5', height}}>
                {
                    this.state.visible && <CachedImage source={{uri: url}} style={style}/>
                }
            </View>
        );
    }

}

@connect(customer => ({...customer}))
class BrowseImage extends Component {
    // 进度浏览图片
    constructor(props) {
        super(props);
        this.state = {
            id: this.props.navigation.state.params.id,
            subjectVisible: false,
            saveImgVisible: false,
            saveToLocal: '',
            imageIndex: 0,
        };
    }

    _keyExtractorSubject = (item, index) => String(index);

    componentDidMount() {
        this._fetchData();
    }

    _fetchData = () => {
        this.props.dispatch(createAction('customer/fetchProcessImage')({id: this.state.id}));
    };

    _zoomImage = (id, type) => {
        this.setState({subjectVisible: true, imageIndex: id});
    };

    renderSubjectItem(item, index) {
        const baseURL = SyncStorage.get('baseURL');
        subjectImages.push({url: baseURL+item.picture});
        return (
                <TouchableOpacity onPress={() => this._zoomImage(index, 'S')}>
                    <Row
                        ref={el => {
                            let key = String(index);
                            _subjectRows[key] = el;
                        }}
                        id={index}
                        row={item}
                    />
                </TouchableOpacity>
        );
    }

    onViewableSubjectsChanged(info) {
        info.changed.forEach((currentValue, index, arr) => {
            _subjectRows[currentValue.key].setVisible(currentValue.isViewable);
        });
    }

    _imgViewRender = () => {
        return (
            <View style={{
                flexDirection: 'row',
                justifyContent: 'flex-end',
                margin: 20,
            }}>
                <Text style={{color: '#ff6633', marginRight: 10}}>长按保存图片</Text>
                <TouchableOpacity style={{
                    borderRadius: 20,
                    borderWidth: 1,
                    borderColor: '#ff6633',
                }} onPress={() => this.setState({answerVisible: false, subjectVisible: false})}>
                    <Text style={{
                        fontFamily: 'iconfont',
                        color: '#ff6633',
                        fontSize: 20,
                        textAlign: 'center',
                    }}>{'\ue606'}</Text>
                </TouchableOpacity>
            </View>
        );
    };
    _saveImgRender = (cancel, saveToLocal) => {
        return (
            <View style={{
                flexDirection: 'row',
                justifyContent: 'center',
                margin: 20,
                marginTop: SCREEN_HEIGHT - 200,
            }}>
                <TouchableOpacity style={{
                    borderRadius: 20,
                    backgroundColor: '#eee',
                    paddingHorizontal: 10,
                    paddingVertical: 5,
                    borderColor: '#ff6633',
                    borderWidth: 1,
                    marginRight: 10,
                }} onPress={() => cancel()}>
                    <Text style={{
                        fontFamily: 'iconfont',
                        color: '#ff6633',
                        fontSize: 20,
                        textAlign: 'center',
                    }}>取消</Text>
                </TouchableOpacity>
                <TouchableOpacity style={{
                    borderRadius: 20,
                    backgroundColor: '#eee',
                    paddingHorizontal: 10,
                    paddingVertical: 5,
                    borderColor: '#ff6633',
                    borderWidth: 1,
                    marginRight: 10,
                }} onPress={() => saveToLocal()}>
                    <Text style={{
                        fontFamily: 'iconfont',
                        color: '#ff6633',
                        fontSize: 20,
                        textAlign: 'center',
                    }}>保存</Text>
                </TouchableOpacity>

            </View>
        );
    };
    savePhoto = (url) => {
        const imgFile = url.split('/');
        const imgDIR = `${RNFS.DocumentDirectoryPath}/${imgFile[imgFile.length - 1]}`;
        const ret = RNFS.downloadFile(
            {
                fromUrl: url,
                toFile: imgDIR,
            });
        ret.promise.then(res => {
            if (res && res.statusCode === 200) {
                let promise = CameraRoll.saveToCameraRoll('file://' + imgDIR, 'photo');
                promise.then(function (result) {
                    ToastAndroid.show('已保存到相册', ToastAndroid.SHORT);
                    // Alert.alert('友情提醒', '已保存到相册！',
                    //     [
                    //         {text: '我知道了', style: 'cancel'},
                    //     ]);
                }).catch(function (error) {
                    console.log(4444444444, error);
                    // alert('保存失败！\n' + error);
                    Alert.alert('友情提醒', '保存失败！',
                        [
                            {text: '我知道了', style: 'cancel'},
                        ]);
                });
            }
        });
    };

    render() {
        const {processImageData, loading} = this.props.customer;

        subjectImages = [];

        let subjectsRender = '';
        if (loading) {
            subjectsRender = <Text style={styles.uploadText}>
                努力加载中...
            </Text>;
        } else {
            subjectsRender = <FlatList
                data={processImageData}
                renderItem={({item, index}) => this.renderSubjectItem(item, index)}
                onViewableItemsChanged={this.onViewableSubjectsChanged}
                keyExtractor={this._keyExtractorSubject}
            />;

        }

        return (
            <Provider>
                {loading ?
                    <ActivityIndicator
                        animating={true}
                        toast
                        size="large"
                        text="加载中..."
                    /> :
                    <View key="subject" backgroundColor='#fff'>
                        {subjectsRender}
                    </View>
                }
                <Modal
                    visible={this.state.subjectVisible}
                    transparent={true}
                    animationType={'fade'}
                    onRequestClose={() => this.setState({subjectVisible: false})}>
                    <ImageViewer
                        style={{menuContainer: -20}}
                        imageUrls={subjectImages}
                        index={this.state.imageIndex}
                        renderHeader={() => this._imgViewRender()}
                        saveToLocalByLongPress={true}
                        menus={({cancel, saveToLocal}) => this._saveImgRender(cancel, saveToLocal)}
                        onSave={(url) => this.savePhoto(url)}
                    />
                </Modal>

            </Provider>
        );

    }
}

export const styles = StyleSheet.create({
    uploadStyle: {
        justifyContent: 'center',
        padding: 10,
        marginVertical: 10,
    },
    uploadText: {
        textAlign: 'center',
        padding: 3,
        paddingTop: 10,
        borderRadius: 5,
        height: 35,
        marginLeft: 2,
        borderWidth: 1,
        borderColor: '#ddd',
        overflow: 'hidden',
        fontFamily: 'iconfont',
        fontSize: 14,
        color: '#333',
    },
});
export default BrowseImage;
