import React from 'react';
import { $http } from '../../containers/config/https';
import './style/index.less';
import { Button, Input,Icon,message } from 'antd';

export default class FaceRecognitionAuto extends React.Component {
    constructor() {
        super();
        this.state = {
            visible: false,
            streaming: false, // 是否开始捕获媒体
            timeSum: 10, // 人脸识别次数
            faceUserData: {}, // 人脸识别对象
            faceTrue: false, // 是否识别成功
            faceValue: "",//人脸特征值
            idCardNo: undefined,
            inputShow: true,
            spining:false
        }
    }

    componentDidMount() {
        setTimeout(()=>{
            this.input.focus()
        },300)
        if ((this.props.businessCode === 'Register') || (this.props.businessCode === '003')) {
            this.setState({
                inputShow: false
            })
        } else {
            this.faceID();
        }
    }

    ///清楚定时器，关闭摄像头
    clearVideo = () => {
        let video = document.querySelector("#video");
        clearInterval(this.timerID); // 移除定时器
        if (video.srcObject) {
            video.srcObject.getTracks()[0].stop(); //关闭摄像头
        }
    }

    inputValue = (e) => {
        this.setState({
            idCardNo: e.target.value
        })
    }
    //检查是否输入了内容
    checkIdCardNo = () => {
        let { idCardNo } = this.state;
        if (idCardNo) {
            this.setState({
                spining:true
            },()=>{
                this.faceID();
            })
        }else{
            this.setState({
                spining:false
            })
        }
    }
    // 人脸识别
    faceID = () => {
        try {
            let video = document.querySelector("#video");
            let canvas = document.querySelector("#canvas"); //
            let width = 500; //视频和canvas的宽度
            let height = 500; //
            let { streaming, timeSum } = this.state; // 是否开始捕获媒体
            let that = this

            // 获取用户媒体,包含视频和音频
            navigator.mediaDevices.getUserMedia({ video: true })
                .then(stream => {
                    video.srcObject = stream; // 将捕获的视频流传递给video  放弃window.URL.createObjectURL(stream)的使用
                    video.play(); //  播放视频
                });

            // 监听视频流就位事件,即视频可以播放了
            video.addEventListener('canplay', function (ev) {
                if (!streaming) {
                    video.setAttribute('width', width);
                    video.setAttribute('height', height);
                    canvas.setAttribute('width', width);
                    canvas.setAttribute('height', height);
                    streaming = true;
                    that.setState({
                        streaming: streaming
                    })
                }
            }, false);
            // 添加定时器
            this.timerID = setInterval(() => {
                let video = document.querySelector("#video");
                if (timeSum == 0) {
                    //message.error(language.LoginLoginErr7 && language.LoginLoginErr7.descripts)
                    this.setState({
                        timeSum: 10,
                        spining:false
                    }, () => {
                        clearInterval(this.timerID); // 移除定时器
                        if (video.srcObject) {
                            video.srcObject.getTracks()[0].stop(); //关闭摄像头
                        }

                    })
                } else {
                    this.tackcapture()
                    timeSum--;
                    this.setState({
                        timeSum: timeSum,
                        spining:false
                    })
                }
            },
                2000
            );
        } catch (error) {
            this.input.focus()
            message.error("当前浏览器没有摄像头权限，请先授权。")
        }
    }
    tackcapture = () => {
        let video = document.querySelector("#video");
        let canvas = document.querySelector("#canvas");
        let context = canvas.getContext('2d');
        let { streaming } = this.state; // 是否开始捕获媒体
        // 需要判断媒体流是否就绪
        if (streaming) {
            context.drawImage(video, 0, 0, 500, 500);// 将视频画面捕捉后绘制到canvas里面
            this.setState({
                imageUrl: canvas.toDataURL('image/png')  // 将canvas的数据传送到img里
            }, () => {
                this.getFaceValue() // 人脸识别验证
            })
        }
    }
    // 人脸识别获取特征值
    getFaceValue = () => {
        let { imageUrl } = this.state
        // 初始值下拉列表值
        let data = {
            "params": [
                {
                    "imageBase64": imageUrl.substring(imageUrl.indexOf(",") + 1)
                }
            ]
        };
        $http.post('urlDeault', this, {
            code: "88010021",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        faceValue: res.result.faceValue
                    }, () => {
                        clearInterval(this.timerID); // 移除定时器
                        video.srcObject.getTracks()[0].stop(); //关闭摄像头
                        this.faceImg()
                    })
                } else {
                    message.errorMessage(res.errorMessage)
                }
            }
        });

    }
    // 人脸识别验证
    faceImg = () => {
        let { idCardNo, faceValue } = this.state
        let data = {
            "params": [
                {
                    "faceType": this.props.faceType ? this.props.faceType : "",
                    "faceValue": faceValue ? faceValue : "",
                    "idCardNo": idCardNo ? idCardNo : "",
                    "businessCode": this.props.businessCode ? this.props.businessCode : "",
                    "hospID": this.props.hospID ? this.props.hospID : "",
                    "locID": this.props.locID ? this.props.locID : "",
                    "doctorID": this.props.doctorID ? this.props.doctorID : ""
                }
            ]
        };
        $http.post('urlDeault', this, {
            code: "88010024",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        faceUserData: res.result || [],
                        faceTrue: true
                    }, () => {
                        var { loadDara } = this.props;
                        loadDara && loadDara(this.state.faceUserData)
                    })
                } else {
                    this.input.focus()
                    var { closeModal } = this.props;
                    closeModal && closeModal()
                }
            },
            error: function () {
                var { closeModal } = this.props;
                closeModal && closeModal()
            }
        });

    }
    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
    }

    handleKeyDown(e){
        if(e.keyCode == '13'){
            this.setState({
                spining:true
            },()=>{
                this.checkIdCardNo()
            })
        }
    }

    render() {
        return (
            <div>
                <div hidden={this.state.inputShow}>
                    <Input type="text" onChange={this.inputValue} value={this.state.idCardNo} style={{ width: '220px' }}onKeyDown={this.handleKeyDown.bind(this)}
                    placeholder="请输入身份证后四位回车键查询" ref={(input) => this.input = input} autoFocus={true} tabIndex='-1'/>
                    <Button onClick={this.checkIdCardNo} type={this.state.spining?'primary':''} style={{marginLeft:10}}>
                        {this.state.spining?<Icon type="sync" spin={this.state.spining} />:null}确定</Button>
                </div>
                <div style={{ textAlign: 'center' }}>
                    <video id="video" width="500" height="500"></video>
                </div>
                <div width="0px" height="0px" style={{ display: 'none' }}>
                    <canvas id="canvas" width="500" height="500"></canvas>
                </div>
            </div>
        )
    }
}
