// 新增用户信息
import React from 'react';
import { Upload, Icon, message } from 'antd';
import { $http } from '../../../containers/config/https';
import '.././style/index.less';

export default class UploadPage extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            windowHost: '',
            isCode: false,
            loading: false,
            imageUrl: '', // 图片地址
            faceValue: '', // 图片特征值
            errorImg: false, // 图片不通过
            fileList: '', // 图片
            userPicAddress: '', // 图片服务器地址
            typeName: '', // 图片上传名称
            isLt2M: false,
        }
    }

    componentDidMount() {
        let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
        // 判断是否是本地，如果是本地的话取https配置地址，线上则取地址栏地址 （内外网）
        let url = windowHost && (windowHost.indexOf('localhost') !== -1 || windowHost.indexOf('127.0.0.1') !== -1) ? $http.ipDeault : windowHost;
        this.setState({
            windowHost: url,
            imageUrl: this.props.imageUrl ? `${this.props.imageUrl}?v=${new Date().getTime()}` : ''
        }, () => {
            this.addre();
        })
        this.props.onRef && this.props.onRef(this)
    }

    addre = () => {
        const { windowHost } = this.state;
        // 初始值下拉列表值
        let data = {
            "params": [{ "dataAry": [{ "productAppCode": "FileServer", "appPropCode": ["UserPhotoPath", "UserUploadPath"] }, {}] }]
        };
        $http.post('urlADS', this, {
            code: "01040211",
            data: data,
            success: function (res) {
                // if (process.env.NODE_ENV === 'production') {
                //     windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
                //     url = res.result.defaultValue[0].appPropCode[1].defaultValue || '';
                // } else {
                //     windowHost = 'https://172.16.1.6'
                //     url = res.result.defaultValue[0].appPropCode[1].defaultValue || '';
                // }
                if (res.errorCode === '0') {
                    let imgUrl = res.result.defaultValue[0].appPropCode[1].defaultValue || '';
                    this.setState({
                        userPicAddress: imgUrl.indexOf('http') !== -1 ? imgUrl : windowHost + imgUrl
                    })
                }
            }
        });
    }

    //清空地址
    clearn = () => {
        this.setState({
            imageUrl: '', // 图片地址
        })
    }

    // 图片上传
    handleImgChange = file => {
        this.getBase64(file, imageUrl =>
            this.setState({
                imageUrl,
                loading: false,
                fileList: file,
                showLoading: true
            }, () => {
                console.log("imageUrl", imageUrl)
                var { loadMessage } = this.props;
                loadMessage && loadMessage(this.state.showLoading)
                this.VerificationImg() // 验证人脸识别
            }),
        );
    };

    // base64
    getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    // 选中触发
    beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传JPG/PNG文件!');
            if (this.props.handThis.handleLoading) {
                this.props.handThis.handleLoading(false)
            }
        }
        const isLt2M = file.size / 1024 / 1024 < 15;
        this.setState({
            isLt2M
        })
        if (!isLt2M) {
            message.error('图片大小不能超过15MB!');
            if (this.props.handThis.handleLoading) {
                this.props.handThis.handleLoading(false)
            }
        } else {
            this.handleImgChange(file)
        }
        return false;
    }

    // 人脸识别验证
    VerificationImg = () => {
        if (this.props.handThis.handleLoading) {
            this.props.handThis.handleLoading(true)
        }
        this.props.handThis.ImgValue(this.state.faceValue, this.state.imageUrl, this.props.code)
        this.ajaxImg()
        // let { imageUrl } = this.state

        // // 初始值下拉列表值
        // let data = {
        //     "params": [
        //         {
        //             "imageBase64": imageUrl.substring(imageUrl.indexOf(",") + 1),
        //         }
        //     ]
        // };

        // $http.post('urlADS', this, {
        //     code: "88010021",
        //     data: data,
        //     success: function (res) {
        //         let errorCode = res.errorCode;
        //         if (errorCode === '0') {
        //             message.success('图片符合')
        //             this.setState({
        //                 faceValue: res.result.faceValue || '',
        //                 errorImg: false
        //             }, () => {
        //                 this.props.handThis.ImgValue(this.state.faceValue, this.state.imageUrl)
        //                 this.ajaxImg()
        //                 // this.props.handThis.errorImg(this.state.errorImg)
        //             })
        //         } else {
        //             if(this.props.handThis.handleLoading){
        //                 this.props.handThis.handleLoading(false)
        //             }
        //             this.clearn()
        //             this.setState({
        //                 errorImg: true
        //             }, () => {
        //                 this.props.handThis.ImgValue('', '')
        //                 // this.props.handThis.errorImg(this.state.errorImg)
        //             })

        //         }
        //     }
        // });
    }

    ajaxImg = () => {
        let data = new FormData();
        let { fileList, userPicAddress } = this.state
        let that = this
        data.append('file', fileList);

        const option = {
            method: 'post',
            mode: 'cors',
            headers: {
                // "Content-Type": "multipart/form-data"
            },
            body: data
        };
        fetch(userPicAddress, option)
            .then(function (response) {
                if (response.ok) {
                    if (that.props.handThis.handleLoading) {
                        that.props.handThis.handleLoading(false)
                    }
                    return response.text();

                } else {
                    console.log('网络错误，请稍后再试')
                    return;
                }
            }).then(function (data) {
                let dataS = JSON.parse(data)
                if (+dataS.errorCode == 0) {
                    that.props.handThis.ImgValue3(dataS.filePath, that.props?.power || '')
                    if (that.props.handThis.handleLoading) {
                        that.props.handThis.handleLoading(false)
                    }
                } else {
                    message.warning(dataS.errorMessage)
                    that.setState({
                        errorImg: true
                    }, () => {
                        that.clearn()
                        that.props.handThis.ImgValue('', '')
                        if (that.props.handThis.handleLoading) {
                            that.props.handThis.handleLoading(false)
                        }
                        // this.props.handThis.errorImg(this.state.errorImg)
                    })
                }
            })
        // .catch(()=>{
        //     message.warning("上传图片失败,请重试")
        //     this.clearn()
        //     this.setState({
        //         errorImg: true
        //     }, () => {
        //         this.props.handThis.ImgValue('', '')
        //         if(this.props.handThis.handleLoading){
        //             this.props.handThis.handleLoading(false)
        //         }
        //         // this.props.handThis.errorImg(this.state.errorImg)
        //     })

        // })
    }

    render() {
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        const { windowHost, imageUrl } = this.state;
        return (
            <div>
                <Upload
                    accept="image/jpeg,image/png"
                    listType="picture-card"
                    className={this.state.errorImg ? 'errorImg' : ''}
                    showUploadList={false}
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleImgChange}
                >
                    {imageUrl ? <img src={imageUrl.indexOf('http') !== -1 || imageUrl.indexOf('base64') !== -1 ? imageUrl : windowHost + imageUrl} style={{ width: '100%' }} /> : uploadButton}
                </Upload>
            </div>
        )
    }
}
