<template>
  <el-dialog
    append-to-body
    title="获取人脸信息"
    :visible.sync="visible"
    width="460px"
    @close="handleClose">
    <div
      class="container"
      v-loading="loading">
      <img
        :id="faceID"
        :style="{opacity:getImgSuccess?1:0,width:'100%'}"
        :src="faceImg">
      <!-- 识别标识 -->
      <div
        ref="mask"
        v-for="(item,index) in masks"
        :key="index"
        class="mask"
        :style="[item,{borderColor:valid?'#1fd83e':'#f8e71c'}]">
      </div>
    </div>

    <div
      class="msg"
      v-if="msg">
      <el-alert
        :type="msg.type"
        effect="dark">
        {{ msg.text }}
      </el-alert>
    </div>

    <span slot="footer">
      <!-- <el-switch
        style="float:left"
        @change="track"
        v-model="isReverse"
        active-text="翻转图像"
        inactive-text="不翻转图像">
      </el-switch> -->

      <!-- <el-button @click="track">重拍</el-button> -->
      <el-upload
        style="display:inline-block"
        action=""
        :show-file-list="false"
        :auto-upload="false"
        :on-change="handleAvatarSuccess">
        <el-button type="primary">重新选择图片</el-button>
      </el-upload>

      <el-button
        style="margin-left:20px"
        v-if="getImgSuccess"
        type="primary"
        @click="handleSubmit">{{ getImgSuccess&&!success?'仍然提交':'确认' }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { faceidentify11 } from '@/api/face'
// import compressImg from '@/assets/compress'

export default {
  props: {
    currentImg: {
      type: String,
      default: ''
    }
  },
  inject: ['skipCheck'],
  data () {
    return {
      masks: [],
      loading: false,
      success: false,
      visible: false,
      isReverse: false,
      faceImg: '',
      valid: false,
      getImgSuccess: false,
      msg: null,
      faceID: 'staticFace' + this._uid
    }
  },
  methods: {
    show () {
      this.loading = true
      this.visible = true
      this.msg = null
      this.masks = []
      this.$nextTick(() => {
        this.faceImg = this.currentImg
        setTimeout(() => {
          this.trackImg()
        }, 1000)
      })
    },
    stopTrack () {
      this.tracker && this.tracker.removeAllListeners()
      this.tracker = null

      this.trackImgTask && this.trackImgTask.stop()

      this.trackImgTask = null
    },
    handleAvatarSuccess (res, list) {
      const isJPG = res.raw.type === 'image/jpeg' || res.raw.type === 'image/png'
      const isLt2M = res.raw.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('图片只能是 JPG或PNG 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return
      }
      let reader = new FileReader()
      reader.readAsDataURL(res.raw)
      reader.onload = (e) => {
        this.faceImg = e.target.result
        this.loading = true
        this.msg = null
        this.masks = []
        setTimeout(() => {
          this.trackImg()
        }, 1000)
        // compressImg(, 400).then(res => {

        // })
      }
    },
    // 人脸比对API
    faceidentify11 (face) {
      if (this.skipCheck) return face
      this.loading = true
      return faceidentify11({ img1: face.split(',')[1], img2: face.split(',')[1] }).then(res => {
        if (res.errInfo === '成功') {
          return face
        } else {
          this.$message({
            showClose: true,
            message: '人脸模糊，请重新拍照',
            type: 'error'
          })
          return false
        }
      }).catch(() => {
        this.$message({
          showClose: true,
          message: '人脸模糊，请重新拍照',
          type: 'error'
        })
        return false
      }).finally(() => {
        this.loading = false
      })
    },
    handleClose () {
      this.visible = false
      this.loading = false
      this.msg = null
      this.masks = []

      this.stopTrack()
    },
    plot (x, y, w, h, color) {
      return {
        width: w + 'px',
        height: h + 'px',
        left: x + 'px',
        // right: x + 'px',
        top: y + 'px',
        borderColor: color || '#ff0'
      }
    },
    trackImg () {
      this.msg = null
      this.masks = []
      this.success = false
      this.getImgSuccess = true
      this.valid = false

      !this.tracker && (this.tracker = new tracking.ObjectTracker(['face']))
      // this.tracker.setStepSize(1.7)
      this.tracker.setEdgesDensity(0.05)
      this.tracker.setInitialScale(1)
      this.tracker.setStepSize(1.5)

      this.trackImgTask = tracking.track(`#${this.faceID}`, this.tracker)

      this.tracker.on('track', (event) => {
        this.masks = []

        event.data.forEach((rect) => {
          this.masks.push(this.plot(rect.x, rect.y, rect.width, rect.height, 'green'))
        })

        if (event.data.length === 0) {
          this.valid = false
          this.msg = {
            type: 'error',
            text: '人脸识别失败，请点击重新截取。'
          }
        }

        if (event.data.length === 1) {
          this.valid = true
          this.success = true
          this.msg = {
            type: 'success',
            text: '人脸识别成功，点击确认按钮提交。'
          }
        }

        if (event.data.length > 1) {
          this.valid = true
          this.msg = {
            type: 'warning',
            text: '人脸识别成功，但人数大于1'
          }
        }

        this.loading = false
      })
    },
    async handleSubmit () {
      let validFace = await this.faceidentify11(this.faceImg)

      if (validFace) {
        this.$emit('change', validFace)
        this.$message.success('人脸校验成功。')
        this.visible = false
      } else {
        this.$message.error('人脸校验失败，请重拍。')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.msg{
  padding: 10px
}
.container{
    width: 100%; position: relative; overflow: hidden;
}
.reverse{
  transform: rotateY(180deg)
}
.canvas,
.video{
    position: absolute;  top: 0;  left: 0;  object-fit: cover; width: 100%; height: 100%;
}
.mask {
  position: absolute; border:5px dashed #f8e71c;box-sizing: border-box;
}
.box {
  position: absolute;  top: 50%;  left: 50%;  width: 60%;  overflow: hidden;  background: rgba(0, 0, 0, .3);  transform: translate(-50%, -50%);
  &:before {
    display: block; padding-bottom: 100%;  content: '';
  }
  &:after {
    position: absolute; top: 0;left: 0; width: 100%;  height: 100%;  content: '';  background: linear-gradient(to left, #f8e71c, #f8e71c) left top no-repeat, linear-gradient(to bottom, #f8e71c, #f8e71c) left top no-repeat, linear-gradient(to left, #f8e71c, #f8e71c) right top no-repeat, linear-gradient(to bottom, #f8e71c, #f8e71c) right top no-repeat, linear-gradient(to left, #f8e71c, #f8e71c) left bottom no-repeat, linear-gradient(to bottom, #f8e71c, #f8e71c) left bottom no-repeat, linear-gradient(to left, #f8e71c, #f8e71c) right bottom no-repeat, linear-gradient(to left, #f8e71c, #f8e71c) right bottom no-repeat;  background-size: 2px 20%, 20% 2px, 2px 20%, 20% 2px;
  }
}
.valid{
  &:after {
    position: absolute; top: 0;left: 0; width: 100%;  height: 100%;  content: '';  background: linear-gradient(to left, #1fd83e, #1fd83e) left top no-repeat, linear-gradient(to bottom, #1fd83e, #1fd83e) left top no-repeat, linear-gradient(to left, #1fd83e, #1fd83e) right top no-repeat, linear-gradient(to bottom, #1fd83e, #1fd83e) right top no-repeat, linear-gradient(to left, #1fd83e, #1fd83e) left bottom no-repeat, linear-gradient(to bottom, #1fd83e, #1fd83e) left bottom no-repeat, linear-gradient(to left, #1fd83e, #1fd83e) right bottom no-repeat, linear-gradient(to left, #1fd83e, #1fd83e) right bottom no-repeat;  background-size: 2px 20%, 20% 2px, 2px 20%, 20% 2px;
  }
}
</style>
