import React from 'react';
import { ImagePicker, Button, Toast, Icon } from 'antd-mobile';
import { $http } from "containers/config/https";
import './style/index.less';

export default class ImagePickerExample extends React.Component {

    constructor({ history }) {
        super();
        let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
        this.state = {
            userData,
            files1: [],
            files2: [],
            files3: [],
            files4: [],
            multiple: true,
            filesListIDCardZ: '',
            filesListIDCardF: '',
            filesListDocCardZ: '',
            filesListDocCardF: '',
            filesState: ''
        };
        this.IDCardFTime = null;
        this.DocCardZTime = null;
        this.DocCardZTime = null;
        this.DocCardFTime = null;
    }
    componentDidMount() {
        this.initDataList();
    }

    initDataList = (isLoading) => {
        isLoading !== 'N' && Toast.loading('数据加载中...', 30);
        let { userData } = this.state;
        let data = {
            params: [{
                hospCode: userData.hisHospID,
                userCode: "wxsf",
                patNO: userData.hisPatNo,
            }]
        }
        $http.post("urlS", this, {
            code: "130977",
            data: data,
            namespace: "UPP",
            success: function (res) {
                isLoading !== 'N' && Toast.hide();
                if (+res.errorCode === 0 && res.result.length > 0) {
                    // let urlLink='https://chis.e24health.com/patImages/patpicture/';
                    let urlLink = res.result[0].pictureurl;
                    this.setState({
                        filesListIDCardZ: res.result[0].idCardFront,
                        filesListIDCardF: res.result[0].idCardBehind,
                        filesListDocCardZ: res.result[0].ybFront,
                        filesListDocCardF: res.result[0].ybBehind
                    })
                    if (res.result[0].idCardFront) {
                        this.setState({
                            files1: [{ url: urlLink + res.result[0].idCardFront }],
                        })
                    }
                    if (res.result[0].idCardBehind) {
                        this.setState({
                            files2: [{ url: urlLink + res.result[0].idCardBehind }]
                        })
                    }
                    if (res.result[0].ybFront) {
                        this.setState({
                            files3: [{ url: urlLink + res.result[0].ybFront }]
                        })
                    }
                    if (res.result[0].ybBehind) {
                        this.setState({
                            files4: [{ url: urlLink + res.result[0].ybBehind }],
                        })
                    }
                } else {
                    this.setState({
                        files1: [],
                        files2: [],
                        files3: [],
                        files4: [],
                    })
                }
            },
            error: function () {
                isLoading !== 'N' && Toast.hide()
            }
        });
    }

    onChange = (files, type) => {
        if (type === 'IDCardZ') {
            if (files.length > 0) {
                this.setState({
                    filesState: '身份证正面上传中，请稍后',
                    files1: files
                })
            } else {
                this.setState({
                    filesListIDCardZ: '',
                    files1: []
                })
            }
        } else if (type === 'IDCardF') {
            if (files.length > 0) {
                this.setState({
                    filesState: '身份证反面上传中，请稍后',
                    files2: files
                })
            } else {
                this.setState({
                    filesListIDCardF: '',
                    files2: []
                })
            }
        } else if (type === 'DocCardZ') {
            if (files.length > 0) {
                this.setState({
                    filesState: '医保正面上传中，请稍后',
                    files3: files
                })
            } else {
                this.setState({
                    filesListDocCardZ: '',
                    files3: []
                })
            }
        } else if (type === 'DocCardF') {
            if (files.length > 0) {
                this.setState({
                    filesState: '医保反面上传中，请稍后',
                    files4: files
                })
            } else {
                this.setState({
                    filesListDocCardF: '',
                    files4: []
                })
            }
        }
        console.log(files)
        if (files && files.length > 0) {
            this.loadingProgress(files[0].file, type, 30)
        }
    }

    // 图片加载进度
    loadingProgress = (files, type, interval) => {
        let num = 1,
            speed = files.size / 1024 / interval; // 计算加载速度
        // return
        let timer = setInterval(() => {
            let overallProgress = Math.floor(speed * num / (files.size / 1024) * 100); // 总进度
            if (type === 'IDCardZ') {
                this.setState({ IDCardZOverallProgress: overallProgress })
            } else if (type === 'IDCardF') {
                this.setState({ IDCardFOverallProgress: overallProgress })
            } else if (type === 'DocCardZ') {
                this.setState({ DocCardZOverallProgress: overallProgress })
            } else if (type === 'DocCardF') {
                this.setState({ DocCardFOverallProgress: overallProgress })
            }
            num++
        }, 0);

        if (type === "IDCardZ") {
            this.IDCardZTime = timer
        } else if (type === "IDCardF") {
            this.IDCardFTime = timer
        } else if (type === "DocCardZ") {
            this.DocCardZTime = timer
        } else if (type === "DocCardF") {
            this.DocCardFTime = timer
        }

        this.uploadImg(files, type)
    }

    uploadImg = (files, type) => {
        let { userData } = this.state;
        let formData = new FormData();
        formData.append("file", files);
        const option = {
            method: 'post',
            mode: 'cors',
            headers: {},
            body: formData,
            name: 'file',
        };
        // 上传地址  https://chis.e24health.com/uploadFilePatPicture?fileType=patpicture 
        let url = userData && userData.upLoadUrl ? userData.upLoadUrl : "https://hrxylkj.com/RMYY/uploadFile?fileType=patpicture";
        fetch(url, option).then(response => {
            if (response.ok) {
                return response.text();
            } else {
                console.log('网络错误，请稍后再试');
                return;
            }
        }).then(data => {
            let dataS = JSON.parse(data);
            if (type === 'IDCardZ') {
                this.setState({ filesListIDCardZ: dataS.filePath, IDCardZOverallProgress: 100 }, () => {
                    clearInterval(this.IDCardZTime)
                })
            } else if (type === 'IDCardF') {
                this.setState({ filesListIDCardF: dataS.filePath, IDCardFOverallProgress: 100 }, () => {
                    clearInterval(this.IDCardFTime)
                })
            } else if (type === 'DocCardZ') {
                this.setState({ filesListDocCardZ: dataS.filePath, DocCardZOverallProgress: 100 }, () => {
                    clearInterval(this.DocCardZTime)
                })
            } else if (type === 'DocCardF') {
                this.setState({ filesListDocCardF: dataS.filePath, DocCardFOverallProgress: 100 }, () => {
                    clearInterval(this.DocCardFTime)
                })
            }
            this.setState({ filesState: '' })
        }).catch((err) => {
            console.log('cuowu', err)
            this.setState({ filesState: '' })
        })
    }

    saveImgs = () => {
        if (this.state.filesState) {
            Toast.info(this.state.filesState);
            return
        }
        let { userData, filesListIDCardZ, filesListIDCardF, filesListDocCardZ, filesListDocCardF } = this.state;
        // var urlImg = 'https://chis.e24health.com/patImages/patpicture/'
        let data = {
            params: [{
                hospCode: userData.hisHospID,
                userCode: "wxsf",
                hisPatID: userData && userData.hisPatID ? userData.hisPatID : "",
                patNO: userData.hisPatNo,
                patName: userData && userData.patDesc ? userData.patDesc : "",
                patID: userData && userData.patID ? userData.patID : "",
                idCardFront: filesListIDCardZ, //身份证正面
                idCardBehind: filesListIDCardF, //身份证反面
                ybFront: filesListDocCardZ, //医保正面
                ybBehind: filesListDocCardF, //医保反面
            }]
        }
        $http.post("urlS", this, {
            code: "130984",
            data: data,
            namespace: "UPP",
            success: function (res) {
                if (+res.errorCode === 0) {
                    Toast.info(res.errorMessage, 3, () => { }, false);
                    this.initDataList('N');
                } else {
                    Toast.info(res.errorMessage, 3, () => { }, false);
                }
            }
        });
    }
    onFailDel = (e) => {
        console.log('触犯了', e)
    }
    render() {
        const { files1, files2, files3, IDCardZOverallProgress, IDCardFOverallProgress, DocCardZOverallProgress } = this.state;
        return (
            <div className='ImagePicker'>
                <div>
                    <div style={{ padding: '0.5em 0' }}>身份证正面：</div>
                    <div className={!IDCardZOverallProgress || IDCardZOverallProgress === 100 ? '' : "img-parent"}>
                        <ImagePicker
                            files={files1}
                            onChange={(e) => { this.onChange(e, 'IDCardZ') }}
                            onImageClick={(index, fs) => console.log(index, fs)}
                            selectable={files1.length < 1}
                            multiple={this.state.multiple}
                            className={files1.length > 0 ? 'T' : ''}
                            onFail={this.onFailDel}
                        />
                        {!IDCardZOverallProgress || IDCardZOverallProgress === 100 ? "" : <Icon type="loading" size='lg' className="img-loading" />}
                    </div>
                </div>

                <div>
                    <div style={{ padding: '0.5em 0' }}>监护人身份证：</div>
                    <div className={!IDCardFOverallProgress || IDCardFOverallProgress === 100 ? '' : "img-parent"}>
                        <ImagePicker
                            files={files2}
                            onChange={(e) => { this.onChange(e, 'IDCardF') }}
                            onImageClick={(index, fs) => console.log(index, fs)}
                            selectable={files2.length < 1}
                            multiple={this.state.multiple}
                            className={files2.length > 0 ? 'T' : ''}
                        />
                        {!IDCardFOverallProgress || IDCardFOverallProgress === 100 ? "" : <Icon type="loading" size='lg' className="img-loading" />}
                    </div>
                </div>
                <div>
                    <div style={{ padding: '0.5em 0' }}>医保正面：</div>
                    <div className={!DocCardZOverallProgress || DocCardZOverallProgress === 100 ? '' : "img-parent"}>
                        <ImagePicker
                            files={files3}
                            onChange={(e) => { this.onChange(e, 'DocCardZ') }}
                            onImageClick={(index, fs) => console.log(index, fs)}
                            selectable={files3.length < 1}
                            multiple={this.state.multiple}
                            className={files3.length > 0 ? 'T' : ''}
                        />
                        {!DocCardZOverallProgress || DocCardZOverallProgress === 100 ? "" : <Icon type="loading" size='lg' className="img-loading" />}
                    </div>
                </div>
                {/* <div>
                    <div style={{padding:'0.5em 0'}}>医保反面：</div>
                    <div className={!DocCardFOverallProgress || DocCardFOverallProgress === 100  ? '' : "img-parent"}>
                        <ImagePicker
                            files={files4}
                            onChange={(e)=>{this.onChange(e,'DocCardF')}}
                            onImageClick={(index, fs) => console.log(index, fs)}
                            selectable={files4.length < 1}
                            multiple={this.state.multiple}
                            className={files4.length>0 ? 'T' : ''}
                        />
                        {!DocCardFOverallProgress || DocCardFOverallProgress === 100 ? "" : <Icon type="loading" size='lg' className="img-loading" />}
                    </div>
                </div> */}

                <div>
                    <Button type="primary" className='imgButton' onClick={this.saveImgs}>提交</Button>
                </div>
            </div>

        );
    }
}
