/* eslint-disable */
import React, { Component } from 'react';
import { VideoCameraOutlined } from '@ant-design/icons';
// import '@ant-design/compatible/assets/index.css';
import { Progress, message } from 'antd-v4';
import * as commonServices from "../../services/services";
import config from '@/utils/config';
import './index.less';
import * as commonFunc from "../Common/commonFunc";

let token = '92d3bf5f3edcb55c731acb11b7f28202'; // 测试的删除token

class FaceDetect extends Component {
  constructor(props) {
    super(props);
    this.video = null;
    this.checkParams = [];
    this.group_id = 'xlyprint';
    this.user_id = '';
    this.user_info = '';
    this.urlpre = `${config.face_host}`;
    this.state = {
      statusContent: '',
      currentPercent: '',
      percentStatus: '',
      thumbImg: ''
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.masterData) {
      console.log('ssss', nextProps.masterData);
      this.user_id = nextProps.masterData.sEmployeeNo;
      this.user_info = JSON.stringify(
        {
          sId: nextProps.masterData.sId,
          sEmployeeName: nextProps.masterData.sEmployeeName,
          sEmployeeNo: nextProps.masterData.sEmployeeNo,
          sDepartName: nextProps.masterData.sDepartName,
        }
      );
    }
  }

  componentDidMount() {
    const { loginAfterInit } = this.props;
    if (loginAfterInit) {
      this.handleEvent(true);
    }
  }

  changeStatusContent = (content) => {
    this.setState({
      statusContent: content
    })
  }
  changeCurrentPercent = (percent) => {
    this.setState({
      currentPercent: percent
    })
  }
  changePercentStatus = (status) => {
    this.setState({
      percentStatus: status
    })
  }


  getFace = () => {
    let canvas = document.getElementById("canvas");
    let context = canvas.getContext("2d");
    context.drawImage(this.video, 0, 0, 268, 214);
    let img = canvas.toDataURL("image/jpeg", 0.9);
    return img;
  }
  //登录认证
  getMedia = () => {
    this.setState({thumbImg: ''});
    this.checkParams=[];
    const _this = this;
    return new Promise((resolve, reject) => {
      _this.video = document.getElementById("video");
      let constraints = {video: true};
      navigator.mediaDevices.getUserMedia(constraints)
        .then((stream) => {
          if ("srcObject" in this.video) {
            _this.video.srcObject = stream;
          } else {
            _this.video.src = window.URL.createObjectURL(stream);
          }
          this.video.onloadedmetadata = (e) => {
            _this.video.play();
          };
          _this.changeStatusContent('人脸检测中');
          _this.changePercentStatus('')
          let timer = setInterval(async () => {
            if (this.checkParams.length < 5) {
              let img = this.getFace();
              let item = {
                "image": img.split(',')[1],
                "image_type": "BASE64",
                "face_field": "age",
                "option": "COMMON"
              }
              _this.checkParams.push(item);
              _this.changeCurrentPercent(_this.checkParams.length / 6 * 100);
            } else {
              clearInterval(timer);
              timer = null;
              const url = this.urlpre + `/face/faceSearch`;
              //console.log(url,this.urlpre);
              _this.changeStatusContent('人脸验证中');
              _this.stopMedia();
              reject();
              const dataReturn = (await commonServices.postValueService(null, _this.checkParams, url));
              //console.log("dataReturn",dataReturn);
              if (dataReturn && dataReturn.data == undefined) {
                _this.changePercentStatus('exception');
                _this.changeStatusContent('接口请求失败');
                // message.error('接口请求失败！');
                _this.stopMedia();
                return;
              }
              if (dataReturn.data.code < 0 ) {
                _this.changePercentStatus('exception');
                _this.changeStatusContent('人脸验证失败,请重新识别:'+dataReturn.data.msg);
                //message.error('人脸验证失败！请重新识别'+dataReturn.data.msg);
                _this.stopMedia();
                reject();
              } else {
                _this.changeStatusContent('人脸验证成功，登录中');
                _this.props.onIdentifySuccess && _this.props.onIdentifySuccess(dataReturn.data);
                _this.changeCurrentPercent(100);
                resolve();
              }
              _this.checkParams= [];
            }
          }, 200);
        })
        .catch(function (err) {
          console.log(err.name + ": " + err.message);
          reject();
        });
    })

  };


  //人脸采集
  getMediaAddFace = () => {
    this.setState({thumbImg: ''});
    this.checkParams=[];
    const _this = this;
    return new Promise((resolve, reject) => {
      _this.video = document.getElementById("video");
      let constraints = {video: true};
      navigator.mediaDevices.getUserMedia(constraints)
        .then((stream) => {
          if ("srcObject" in this.video) {
            _this.video.srcObject = stream;
          } else {
            _this.video.src = window.URL.createObjectURL(stream);
          }
          this.video.onloadedmetadata = (e) => {
            _this.video.play();
          };
          _this.changeStatusContent('人脸采集中,请稍等');
          _this.changePercentStatus('')
          let timer = setInterval(async () => {
            if (this.checkParams.length < 10) {
              let img = this.getFace();
              let item = {
                "image": img.split(',')[1],
                "image_type": "BASE64",
                "face_field": "age",
                "option": "COMMON"
              }
              _this.checkParams.push(item);
              _this.changeCurrentPercent(_this.checkParams.length / 11 * 100);
            } else {
              clearInterval(timer);
              timer = null;
              //验证URL
              const url = this.urlpre + `/face/detectFaces`;
              _this.changeStatusContent('人脸检测中');
              _this.stopMedia();
              reject();
              //console.log("dataReturn",_this.checkParams);
              const dataReturn = (await commonServices.postValueService(null, _this.checkParams, url));
              //console.log("dataReturn",dataReturn);
              if (dataReturn && dataReturn.data == undefined) {
                _this.changePercentStatus('exception');
                _this.changeStatusContent('接口请求失败');
                message.error('接口请求失败！');
                _this.stopMedia();
                return;
              }
              if (dataReturn.data.code < 0 ) {
                _this.changePercentStatus('exception');
                _this.changeStatusContent('人脸采集失败：'+dataReturn.data.msg);
                // message.error('人脸采集失败！请重新采集'+dataReturn.data.msg);
                _this.stopMedia();
                reject();
              } else {
                _this.changeStatusContent('人脸采集成功');
                let img = _this.getFace();
                let userinfo = this.props.app.userinfo;
                const sBrandId = userinfo?.sBrandsId;
                const sSubsidiaryId = userinfo?.sSubsidiaryId;
                if(this.props.bClickSource?.includes('BtnAddFace') ){
                  userinfo = {
                    sUserName: this.props.masterData?.sEmployeeName,
                    sEmployeeNo: this.props.masterData?.sEmployeeNo,
                    sEmployeeId : this.props.masterData?.sEmployeeId,
                    sDepartName:  this.props.masterData?.sDepartName,
                    sId :this.props.masterData?.sId
                  }
                  console.log('userinfo', userinfo);
                }

                let item = {
                  "image": img.split(',')[1],
                  "image_type": "BASE64",
                  "sParentId": userinfo.sId,
                  "sEmployeeId": userinfo.sId,
                  "sEmployeeName": userinfo.sUserName,
                  "sEmployeeNo": userinfo.sEmployeeNo,
                  "sUserName": userinfo.sUserName,
                  "sBrandsId": sBrandId,
                  "sSubsidiaryId": sSubsidiaryId,
                  "quality_control": "NORMAL",
                  "liveness_control": "LOW",
                  "face_field": "feature"
                }
                console.log('item', item);
                //保存URL
                const url = this.urlpre + `/face/faceAdd`;
                _this.changeStatusContent('人脸数据处理中，请稍等');
                const dataReturn = await commonServices.postValueService(null, item, url);
                if (dataReturn.data.code > 0 ) {
                  _this.changeStatusContent('人脸数据处理成功');
                  _this.props.onSaveFaceSuccess && _this.props.onSaveFaceSuccess(dataReturn);
                }else{
                  _this.changeStatusContent('人脸数据处理失败，'+dataReturn.data.msg+'请重新采集');
                }
                _this.changeCurrentPercent(100);
                resolve();
              }
              _this.checkParams= [];
            }
          }, 200);
        })
        .catch(function (err) {
          console.log(err.name + ": " + err.message);
          reject();
        });
    })
  };

  // 注册人脸
  saveFace = () => {
    const _this = this;
    const userinfo = this.props.app.userinfo;
    if(undefined === userinfo.sEmployeeId || userinfo.sEmployeeId === '' ){
      _this.changeStatusContent('您没有采集权限,请联系管理员,将您绑定成员工。');
      message.error('您没有采集权限,请联系管理员,将您绑定成员工。');
      return;
    }
    _this.getMediaAddFace().then(async () => {
      // _this.changeStatusContent('人脸数据处理中，请稍等');
      // async function handleAddFace() {
      //   let img = _this.getFace();
      //   let item = {
      //     "image": img.split(',')[1],
      //     "image_type": "BASE64",
      //     "sParentId": userinfo.sId,
      //     "sEmployeeId": userinfo.sEmployeeId,
      //     "sUserName": userinfo.sUserName,
      //     "sBrandsId": userinfo.sBrandsId,
      //     "sSubsidiaryId": userinfo.sSubsidiaryId,
      //     "quality_control": "NORMAL",
      //     "liveness_control": "LOW",
      //     "face_field": "feature"
      //   }
      //   console.log(userinfo,item);
      //   const url = `http://localhost:8080/xlyEntry/face/faceAdd`;
      //   const dataReturn = await commonServices.postValueService(null, item, url);
      //   _this.changeCurrentPercent(check / 11 * 100);
      //   if (dataReturn.data.code > 0 ) {
      //     _this.setState({thumbImg: _this.getFace()})
      //     _this.changeCurrentPercent(100);
      //     _this.changeStatusContent('人脸采集成功');
      //     _this.props.onSaveFaceSuccess && _this.props.onSaveFaceSuccess(dataReturn);
      //     _this.stopMedia();
      //     return;
      //   }
      // }
      // await handleAddFace();
      // if (check === limit) {
      //   _this.changeCurrentPercent(100);
      //   _this.changePercentStatus('exception');
      //   _this.changeStatusContent('人脸采集失败');
      //   message.error('保存失败！请重新采集');
      //   _this.stopMedia();
      // }
    })
  }

  // 验证人脸
  detectFace = () => {
    const _this = this;
    _this.getMedia().then(async () => {
      let limit = 5;
      let check = 0;
      async function handleDetectFace() {
        for (let i = 0; i < limit; i ++) {
          check ++;
          let img = _this.getFace();
          let item = {
            "image": img.split(',')[1],
            "image_type": "BASE64",
            "face_field": "faceshape,facetype,feature"
          }
          const url = this.urlpre +`/face/faceSearch`;
          const dataReturn = await commonServices.postValueService(null, item, url);
          if (dataReturn.data.code === 1) {
            _this.setState({thumbImg: _this.getFace()})
            _this.changeStatusContent('人脸验证成功');
            _this.stopMedia();
            _this.props.onDetectSuccess && _this.props.onDetectSuccess(dataReturn.data);
            return;
          }
        }
      }
      await handleDetectFace();
    });
  }

  stopMedia = () => {
    if (!this.video) {
      return;
    }
    const stream = this.video.srcObject;
    if (stream) {
      const tracks = stream.getTracks();
      tracks.forEach(function(track) {
        track.stop();
      });
      this.video.srcObject = null;
    }
  }

  // 人脸搜索
  identifyFace = () => {
    // let result = {
    //   result: {
    //     user_list: [{user_id: '200981'}]
    //   }
    // }
    // this.props.onIdentifySuccess(result);
    // return;
    const _this = this;
    _this.getMedia().then(async () => {
      let img = _this.getFace();
      let item = {
        "image": img.split(',')[1],
        "image_type": "BASE64",
        "group_id_list": _this.group_id,
        "quality_control": "NORMAL",
        "liveness_control": "NORMAL"
      }
      const url = this.urlpre +`/face/faceSearch`;
      const dataReturn = await commonServices.postValueService(null, item, url);
      if (dataReturn && dataReturn.data && dataReturn.data.code === 1) {
        _this.setState({thumbImg: _this.getFace()})
        _this.changeStatusContent('人脸验证成功');
        _this.stopMedia();
        _this.props.onIdentifySuccess && _this.props.onIdentifySuccess(dataReturn.data);
        return;
      } else {
        _this.changePercentStatus('exception');
        _this.changeStatusContent('未匹配到用户');
      }
    })
  }

  // 人脸删除
  deleteFace = async () => {
    let item = {
      "user_id": this.user_id,
      "group_id": this.group_id,
      "face_token": token
    }
    const url = `/face/delete/`;
    const dataReturn = await commonServices.postValueService(null, item, url);
    if (dataReturn.data.error_msg === 'SUCCESS') {
      message.success('删除成功');
      console.log('dataReturn', dataReturn);
      return;
    }
  }

  getFaceList = async () => {
    let item = {
      "user_id": this.user_id,
      "group_id": this.group_id,
    }
    const url = `/face/list/`;
    const dataReturn = await commonServices.postValueService(null, item, url);
    if (dataReturn.data.error_msg === 'SUCCESS') {
      message.success('删除成功');
      console.log('dataReturn', dataReturn);
      return;
    }
  }


  handleEvent = async (enable) => {
    let flag = true;
    if (this.props.verify) {
      flag = this.props.verify();
    }
    flag && this[this.props.actionType]();
  }

  render() {
    const enable = ((this.props.enabled && this.user_id !== '' )|| this.props.actionType === 'identifyFace');
    const faceCollection = commonFunc.showLocalMessage(this.props, 'faceCollection', '人脸采集');
    return (
      <>
        <div className="face-recognition-container">
          <div className="face-recognition">
            <div className="face-wrapper">
              <div className="shape">
                <div></div>
                <div></div>
                <div></div>
                <div></div>
              </div>
              <div className="tips">
                <span>{this.state.statusContent}</span>
                {this.state.currentPercent > 0 && (
                  <Progress
                    type="circle"
                    percent={this.state.currentPercent}
                    status={this.state.percentStatus}
                    width={20}
                    strokeWidth={10}
                    format={() => ""}
                  />
                )}
              </div>
              <video id="video" autoPlay="autoplay"></video>
              {this.state.thumbImg !== "" && <img src={this.state.thumbImg} className={"thumb-img"} alt="" />}
              <div className="canvas-wrapper">
                <canvas id="canvas" width="268" height="214"></canvas>
              </div>
              <div className={`action ${enable ? "" : "action_disabled"}`}>
                <div onClick={() => this.handleEvent(enable)} className="action-item">
                  <span className="action-item-icon">
                    <VideoCameraOutlined />
                  </span>
                  <span>{faceCollection}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        {/*<div className="face-actions">*/}
        {/*  <Button onClick={this.deleteFace}>人脸删除(入:token)</Button>*/}
        {/*  <Button onClick={this.identifyFace}>人脸搜索(入:token,回:token)</Button>*/}
        {/*  <Button onClick={this.detectFace}>人脸检测(入:image,回:token)</Button>*/}
        {/*  <Button onClick={this.getFaceList}>用户列表</Button>*/}
        {/*</div>*/}
      </>
    );
  }
}

export default FaceDetect;
