import React, { Component } from 'react'
import { PermissionsAndroid, StatusBar } from 'react-native';
import { StyleSheet, View, Text, Image } from 'react-native'
import { TouchableOpacity } from 'react-native-gesture-handler';
import ImageViewer from 'react-native-image-zoom-viewer';

import { back } from '../../NavigationService';
import { height, isIos, px2dp, size, toastShort, width } from '../../utils/base';
import Header from '../Header/header';
import RNFetchBlob from 'rn-fetch-blob';
import CameraRoll from "@react-native-community/cameraroll";



export interface Props {
    route: {
        params: {
            imageList: Array<Img>
        }
    }
    // imageList: Array<Img>
}

export interface Img {
    url: string
    props?: {
        sourse?: string
        // Or you can set source directory.
        // source?: require('../background.png')

    }
}

export interface State {
    nowIndex: number
}

export default class ImagePreView extends React.Component<Props, State> {
    constructor(props: Props | Readonly<Props>) {
        super(props);

    }
    componentDidMount() {
    }

    componentWillUnmount() {
    }

    public readonly state: Readonly<State> = {
        nowIndex: 0
    }

    // header = () => {
    //     return (
    //         <View style={styles.headerStyle}>
    //             <TouchableOpacity onPress={back} style={styles.backBtn}>

    //             </TouchableOpacity>
    //         </View>
    //     )
    // }

    onSave = async () => {
        if (!isIos()) {
            console.log(999)
            await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
        };
        let { nowIndex } = this.state;
        let { imageList } = this.props.route.params;
        let nowUrl = imageList[nowIndex] && imageList[nowIndex].url

        console.log("url:", nowUrl)
        RNFetchBlob
            .config({
                fileCache: true,
                appendExt: 'png'
            })
            .fetch('GET', nowUrl)
            .then((res) => {
                // console.log(appendExt)
                // CameraRoll.saveToCameraRoll(res.path()).then(res => console.log("结果是:", res)).catch((err) => console.log("打印错误：", err))
                const localUri = res.path().startsWith('file://') ? res.path() : `file://${res.path()}`;
                console.log('The file saved to ', localUri)

                CameraRoll.save(localUri).then(res => console.log("结果是:", res))
            }).then((e) => {
                console.log("哈哈哈:", e)
                toastShort("已保存到相册")
            }).catch((err) => { console.log(err) })
    }

    onChange = (index) => {
        console.log("indx:", index)

        this.setState({
            nowIndex: index
        })

    }

    render() {
        let { imageList } = this.props.route.params;
        console.log("1", imageList)
        return (
            <View style={styles.main}>
                <StatusBar barStyle={'light-content'} translucent={true} backgroundColor={'rgb(0,0,0)'} />
                <ImageViewer
                    imageUrls={imageList}
                    renderHeader={() => <Header style={{ backgroundColor: "black", height: size.head_height - px2dp(10), position: "absolute", zIndex: 999 }} noBoder mode="light" />}
                    menuContext={{ saveToLocal: "保存到相册", cancel: "取消" }}
                    // enableSwipeDown//启用向下滑动
                    pageAnimateTime={100}//动画时间
                    enablePreload//启用预加载下一张图片
                    useNativeDriver
                    onChange={this.onChange}
                    onLongPress={() => console.log("99999")}

                    onSave={this.onSave}
                // onSaveToCamera={this.onSave}
                // menus={()}
                />
                {/* <ImageViewer
                    cropHeight={height}
                    cropWidth={width}
                    imageWidth={width}
                    imageHeight={px2dp(600)}
                >
                    {
                        imageList.map((item, index) => <Image source={{ uri: item.url }} style={{ width: px2dp(400), height: px2dp(600) }} key={index} />)
                    }
                </ImageViewer> */}
            </View>
        );

    }
}
const styles = StyleSheet.create({
    main: {
        flex: 1
    },

    // headerStyle: {
    //     width: width,
    //     height: size.head_height,
    //     justifyContent: "flex-start",
    //     alignItems: "center",
    //     paddingHorizontal: px2dp(12.5),

    // },

    // backBtn: {
    //     width: px2dp(40),
    //     height: px2dp(40)
    // }
})