<template>
  <el-form class="login-form"
           status-icon
           :rules="loginRules"
           ref="loginForm"
           :model="loginForm"
           label-width="0">
    <el-form-item prop="username" style="padding-left: 44px">
      <div class="video" style="z-index: 1">
        <video  id="video"  width="274"  height="265"  preload autoplay loop muted style="z-index: 1;"></video>
      </div>
      <div class="renlian" style="z-index: 999">
        <div class="box">
          <div class="line"></div>
          <div class="bottom"></div>
        </div>
      </div>
      <canvas id="canvas" width="500" height="500" style="position: fixed;top: -10000px"></canvas>
    </el-form-item>
    <el-form-item>
    </el-form-item>
  </el-form>
</template>

<script>
    import {mapGetters} from "vuex";
    import {info} from "@/api/system/tenant";
    import * as user from "@/api/user";
    import {getTopUrl} from "@/util/util";
    import website from "@/config/website";

    export default {
        name: "renlian",
        data() {
            return {
                tenantMode: website.tenantMode,
                loginForm: {
                    //租户ID
                    tenantId: "000000",
                    //用户名
                    username: "",
                    //密码
                    password: "",
                    //账号类型
                    type: "account",
                    //验证码的值
                    code: "",
                    //验证码的索引
                    key: "",
                    //预加载白色背景
                    image: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
                },
                loginRules: {
                    tenantId: [
                        {required: false, message: "请输入租户ID", trigger: "blur"}
                    ],
                    username: [
                        {required: true, message: "请输入用户名", trigger: "blur"}
                    ],
                    password: [
                        {required: true, message: "请输入密码", trigger: "blur"},
                        {min: 1, message: "密码长度最少为6位", trigger: "blur"}
                    ]
                },
                passwordType: "password"
            };
        },
        created() {

        },
        mounted() {
          let that = this
          setTimeout(function () {
            that.openCamera()
            that.getTenant();
            that.refreshCode();
          },1000)
        },
        destroyed() {
            // console.log(1111111111)
            // // 停止侦测
            this.trackerTask.stop()
            // // 关闭摄像头
            // window.tracking.closeCamera()
        },
        computed: {
            ...mapGetters(["tagWel"])
        },
        props: [],
        methods: {
            closeshexiangtou(){
                this.trackerTask.stop()
            },
            refreshCode() {
                user.getCaptcha().then(res => {
                    const data = res.data;
                    this.loginForm.key = data.key;
                    this.loginForm.image = data.image;
                })
            },
            showPassword() {
                this.passwordType === ""
                    ? (this.passwordType = "password")
                    : (this.passwordType = "");
            },
            handleLogin() {
                this.$refs.loginForm.validate(valid => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: '登录中,请稍后。。。',
                            spinner: "el-icon-loading"
                        });
                        this.$store.dispatch("LoginByUsername", this.loginForm).then(() => {
                            this.$router.push({path: this.tagWel.value});
                            loading.close();
                        }).catch(() => {
                            loading.close();
                            this.refreshCode();
                        });
                    }
                });
            },
            getTenant() {
                let domain = getTopUrl();
                info(domain).then(res => {
                    const data = res.data;
                    if (data.success && data.data.tenantId) {
                        this.tenantMode = false;
                        this.loginForm.tenantId = data.data.tenantId;
                        this.$parent.$refs.login.style.backgroundImage = `url(${data.data.backgroundUrl})`;
                    }
                })
            },


            openCamera() {

                var video = document.getElementById('video');
                var canvas = document.getElementById('canvas');
                var context = canvas.getContext('2d');

                var tracker = new tracking.ObjectTracker('face');  // 引入第三方 库
                tracker.setInitialScale(1);
                tracker.setStepSize(2);
                tracker.setEdgesDensity(0.1);

                this.trackerTask = tracking.track('#video', tracker, {camera: true});
                //-------  指定 canvas 的宽高 ，auto 自动播放
                let constraints = {
                    video: {width: 300, height: 300},
                    audio: true
                };

                let promise = navigator.mediaDevices.getUserMedia(constraints);   // h5 新的API

                promise.then(function (MediaStream) {
                    video.srcObject = MediaStream;
                    video.play();
                }).catch(function (PermissionDeniedError) {
                    console.log(PermissionDeniedError);
                })
                //--------------
                let that = this;
                that.tracker_fun(tracker, video, context, canvas); //open 摄像头，执行tracker_fun( 传入参数 )

            },
            tracker_fun(tracker, video, context, canvas) {
                let that = this;
                let set_clear;
                set_clear = setInterval(function () { // 每秒 检测人脸 结果
                    tracker.on('track', function (event) {     // 视频流
                        if (!that.first) {     // if  --- > else  检测到人脸 success() =>{}
                            event.data.forEach(function (rect) {
                                if (rect.x) {
                                    that.first = rect.x;
                                    // video.pause();    // success  将暂停 video
                                    context.drawImage(video, 0, 0, 500, 500);   // 绘制到 canvas
                                    context.font = '11px Helvetica';
                                    context.fillText("", 100, 40);
                                    context.strokeStyle = '#a64ceb';
                                    context.strokeRect(rect.x, rect.y, rect.width, rect.height);
                                    var data_url = canvas.toDataURL('image/png'); //base64 request
                                    that.$store.dispatch("LoginByrenlian",data_url).then((res) => {
                                        if (res.error_code == 400) {
                                            setTimeout(function () {
                                                that.first = null;
                                            },3000)
                                            this.$message.error(res.error_msg);
                                        } else {
                                            const loading = that.$loading({
                                                lock: true,
                                                text: '登录中,请稍后。。。',
                                                spinner: "el-icon-loading"
                                            });
                                            clearInterval(set_clear)
                                            setTimeout(function () {
                                                loading.close();
                                                location.reload();
                                                // that.$router.resolve({path: that.tagWel.value});
                                            },3000)
                                        }


                                    }).catch(() => {
                                        setTimeout(function () {
                                            that.first = null;
                                        },3000)
                                    });
                                    // return;
                                }
                            });
                        }
                    });
                    // clearTimeout(set_clear)
                    // console.log('-------')
                }, 3000)

            }
        }
    };
</script>

<style>
  .renlian {
    position: relative;
    height: 90px;
    width: 274px;
    background-size: 100% 100%;
  }
  .video {
    position: relative;
    height: 90px;
    width: 274px;
    background-size: 100% 100%;
  }

  .renlian .box {
    width: 30vw;
    height: 30vw;
    max-height: 30vh;
    max-width: 30vh;
    position: relative;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    overflow: hidden;
    border: 0.1rem solid rgba(3, 169, 244, 0.2);
  }

  .renlian .line {
    height: calc(100% - 2px);
    width: 100%;
    background: linear-gradient(180deg, rgba(0, 255, 51, 0) 43%, #03a9f4 211%);
    border-bottom: 2px solid #03a9f4;
    transform: translateY(-100%);
    animation: radar-beam 2s infinite;
    animation-timing-function: cubic-bezier(0.3, 0, 0.43, 0.7);
    animation-delay: 1.4s;
    z-index: 999;
  }

  .renlian .box:after,
  .renlian .box:before,
  .renlian .bottom:after,
  .renlian .bottom:before {
    content: '';
    display: block;
    position: absolute;
    width: 3vw;
    height: 3vw;
    z-index: 999;
    border: 0.2rem solid transparent;
  }

  .renlian .box:after,
  .renlian .box:before {
    top: 0;
    border-top-color: #03a9f4;
    z-index: 999;
  }

  .renlian .bottom:after,
  .renlian .bottom:before {
    bottom: 0;
    border-bottom-color: #03a9f4;
  }

  .renlian .box:before,
  .renlian .bottom:before {
    left: 0;
    border-left-color: #03a9f4;
  }

  .renlian .box:after,
  .renlian .bottom:after {
    right: 0;
    border-right-color: #03a9f4;
  }

  @keyframes radar-beam {
    0% {
      transform: translateY(-100%);
    }

    100% {
      transform: translateY(0);
    }
  }
</style>
