import React from 'react';
import { Upload, Modal, message } from 'antd';
import { $http } from 'containers/config/https';
import '../style/Secondary.less';


// @inject("GlobalStore", "HealthStore") @observer
class BasicUpload extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            fileList: [],
            userData: JSON.parse(sessionStorage.getItem('userData'))? JSON.parse(sessionStorage.getItem('userData')) : {},
            actionUrl: "",
            imgList:[],
            imgPicture:'',
        };
    }

    componentDidMount() {
        this.props.onRef(this);
        // const { userData } = this.props.GlobalStore;
        let p = {
            params: [{
                userID: this.state.userData.userID || '',
                locID: this.state.userData.locID || '',
                groupID: this.state.userData.groupID,
                hospID: this.state.userData.hospID
            }]
        }
        // if(this.props.HealthStore){
        //     this.props.HealthStore.uploadImg(p).then(data => {
        //         if (data.errorCode == "0") {
        //             this.setState({ actionUrl: data.result });
        //         }
        //     })
        // }

    }

    beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传JPG/PNG文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片大小不能超过2MB!');
        }
        return false;
    }

    getBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await this.getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });

    };

    onChange = (info) => {
        if (this.props.HealthStore !== "") {
            if (info.file.status == "removed") {
                let a=  this.state.fileList.filter(data=>{
                     if(data.status !== "removed"){
                         return data;
                     }
                 });
                 this.setState({fileList:a});
                }else{
                    // this.setState({fileList:info.fileList});
                    let formData = new FormData();
                    formData.append("file", info.file);
                    const option = {
                        method: 'post',
                        mode: 'cors',
                        headers: {},
                        body: formData
                    };
                    // console.log('optionoption',option)
                    // http://218.17.212.34:53774/uploadFile?fileType=health
                    // let url  = "http://172.18.100.86:3008/uploadFile?fileType=health";
                    // console.log('this.props.HealthStore',this.props.HealthStore)
                    let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
                    let fetchUrl = this.props && this.props.HealthStore ? (this.props.HealthStore.indexOf("http") !== -1 ? this.props.HealthStore : windowHost + this.props.HealthStore) : "";
                    fetch(fetchUrl, option).then(response=>{
                    // fetch(this.props.HealthStore, option).then(response=>{
                            if (response.ok) {
                                console.log('suc')
                                return response.text();
                            } else {
                                console.log('网络错误，请稍后再试');
                                return;
                            }
                        }).then(data=> {
                            let dataS = JSON.parse(data);
                            // let str = this.props.HealthStore.match(/(\S*)\/uploadFile/)[1];
                            let str = fetchUrl.match(/(\S*)\/uploadFile/)[1];
                            let obj = { uid: this.state.fileList.length + 1, name: "health", status: 'done', url: str + "/images/health/" + dataS.filePath }
                            // console.log('121212313',obj);
                            this.state.fileList.push(obj);
                            this.setState({imgList:this.state.imgList});
                            this.props.that.setState({text:true})
                            window.sessionStorage.setItem("changeValue",JSON.stringify(true));
                        })

                }
            }
    }

    getImgStr = ()=>{
        let newList = this.state.fileList.map(data => {
            let myUrl = data.url.split("/");
            let hh = myUrl[myUrl.length - 1]
            return hh;
        });
        let str = newList.join("&");
        if(str){
            return str;
        }else{
            return ''
        }

     }

     tranList = (str)=>{
        if (str) {
            let strArray = str.split("&");
            let newArray = strArray.map((data, index) => {
                return { uid: index, name: "health" + index, status: 'done', url: data }
            });
            this.setState({ fileList: newArray });
        }
     }

    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const uploadButton = (
            <div>
                {/* <PlusOutlined /> */}
                <div className="ant-upload-text">上传</div>
            </div>
        );
        return (
            <div className="clearfix deleteIcon">
                <Upload
                    // showUploadList={{showRemoveIcon:false}}
                    //   action={this.state.actionUrl}
                    accept="image/jpeg,image/png"
                    listType="picture-card"
                    fileList={ fileList}
                    // onPreview={this.handlePreview}
                    beforeUpload={this.beforeUpload}
                    onChange={this.onChange}
                >
                    {fileList.length >= 3 ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}
                >
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}

export default BasicUpload;
