<template>
  <div class="photo-of-responsible-person">
    <!--  活体检测规则  -->
    <div class="face-recognition-requirement">
      <div class="face-recognition-requirement-words">
        <p class="tips">
          请确保脸部清晰完整，光线充足
        </p>
        <p class="important-tips">
          {{ take ? '拍摄时' : '请使用手机录制，录制时' }}{{ type === LIVENESS_TYPE.ACTION ? '完成以下所要求的动作' : '用普通话大声读如下数字' }}
        </p>
        <p v-if="type === LIVENESS_TYPE.ACTION" class="action">{{ action }}</p>
        <p v-else class="random-num">
          <b>{{ number.substr(0,1) }}</b>
          <b>{{ number.substr(1,1) }}</b>
          <b>{{ number.substr(2,1) }}</b>
          <b>{{ number.substr(3,1) }}</b>
        </p>
        <el-button v-if="take || isTablet" class="btn-take" type="primary" icon="el-icon-video-play" @click="handleTakeVideo">开始验证</el-button>
        <p v-else class="tips">
          请正对手机屏幕录制2～3秒
        </p>
      </div>
      <div class="face-recognition-requirement-img" :class="take ? 'pc' : ''" />
    </div>
    <!--  活体视频上传  -->
    <div class="face-recognition-ipload">
      <comp-file-info
        ref="file"
        :limit="1"
        :data="data.fileData"
        :size="4"
        :liveness-type="type"
        :random-num="number"
        accept=".mp4"
        btn-name="上传视频"
        label-name="人脸识别视频"
        desc="文件类型为视频文件，扩展名要求使用小写字母，允许支持的视频格式包括mp4，小于4MB"
      />
    </div>
    <DeviceVideo :liveness-type="type" :random-num="number" :show.sync="showDeviceVideo" title="人脸识别验证" @upload-success="handleUploadSuccess" />
  </div>
</template>

<script>
import request from '@/utils/request'
import bridge from '@/utils/bridge'
import { getToken } from '@/utils/auth'
import CompFileInfo from '@/components/CompFileInfo'
import DeviceVideo from '@/components/Device/video'

const LIVENESS_TYPE = {
  NUMBER: 'LIP',
  ACTION: 'ACTION'
}

export default {
  name: 'CompFaceRecognition',
  components: {
    CompFileInfo,
    DeviceVideo
  },
  props: {
    // 验证方式：number：读数字 action：动作
    type: {
      type: String,
      default: LIVENESS_TYPE.NUMBER
    },
    // 是否是摄像
    take: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 是否展示录屏弹框
      showDeviceVideo: false,
      LIVENESS_TYPE,
      number: '',
      videoUrl: '',
      isTablet: window.OS.isTablet
    }
  },
  computed: {
    /**
     * 当前是否是动作
     */
    action() {
      // 动作编号
      return '请先' + this.number.split(',').map(actionCode => {
        try {
          return this.$store.getters.dict.livenessActionSeq.find(seq => `${seq.value}` === `${actionCode}`).label
        } catch (error) {
          console.error(error)
          return ''
        }
      }).join('，再')
    }
  },
  watch: {
    data() {
      this.updateInternalData()
    }
  },
  created() {
    this.init()
  },
  methods: {
    /**
     * 开始拍摄视频
     */
    handleTakeVideo() {
      // 上传文件
      const uploadFile = async video => {
        // 表单数据
        const form = new FormData()
        // 遍历数据
        form.append('file', video)
        // 开始请求数据
        const uploadResult = await request({
          url: `${process.env.VUE_APP_BASIC_API}file/upload`,
          headers: {
            'Content-Type': 'multipart/form-data;',
            'Authorization': `bearer ${getToken()}`
          },
          data: form
        })
        // 上传结果
        this.handleUploadSuccess(uploadResult)
      }
      // 如果当前是平板
      if (this.isTablet) {
        // 如果当前是一体机
        if (this.$store.getters.deviceType === 'aio') {
          const callback = (video, type) => {
            // 如果当前选择了图片
            if (type === 'image') {
              this.$message.error('请上传视频文件')
              return
            }
            uploadFile(video)
          }
          // 获取一体机
          bridge.getUvcCameraList((deviceList = []) => {
            // 是否有master相机
            const slaveCamera = deviceList.find(device => device.productName.toLowerCase().indexOf('slave') >= 0)
            // 如果当前有高拍仪的主相机
            if (slaveCamera) {
              bridge.openTargetUvcCamera(slaveCamera, callback)
            } else {
              bridge.getUvcCamera(callback)
            }
          })
        } else {
          bridge.takeVideo(uploadFile)
        }
        return
      }
      // 如果当前是pc，则打开高拍仪
      this.showDeviceVideo = true
    },

    init() {
      this.updateInternalData()
    },
    updateInternalData() {
      if (typeof this.data === 'object' && this.data !== null) {
        this.number = this.data.number || ''
      } else {
        this.number = ''
      }
    },

    async validate() {
      try {
        await this.$refs.file.validate()
        return true
      } catch (e) {
        throw e
      }
    },
    getFormData() {
      return this.$refs.file.getFormData()
    },
    getPendingCacheData() {
      return this.$refs.file.getPendingCacheData()
    },

    /**
     * 视频上传成功方法
     */
    handleUploadSuccess(data) {
      // 当前可访问的路径
      data.url = data.accessUrl
      // 设置文件名
      data.name = '录制的视频.mp4'
      // 追加一条数据
      this.$refs.file.appendFile(data)
    }
  }
}
</script>

<style scoped lang="scss">
.photo-of-responsible-person {
  overflow: hidden;
  .face-recognition-requirement{
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 10px;
    .face-recognition-requirement-img {
      width: 490px;
      height: 290px;
      flex: none;
      background: url(../../assets/image/living_body_drawing@2x.png) no-repeat 0 0 / 490px 290px;

      &.pc {
        background: url(../../assets/image/living_body_drawing_pc.png) no-repeat 0 0 / 490px 290px;
      }
    }
    &-words{
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      text-align: center;
      color: #666;
      font-size: 16px;
      .random-num {
        display: flex;
        justify-content: space-between;
      }
      .action {
        background: #F7F8FA;
        border-radius: 8px;
        color: #212026;
        font-weight: 500;
        font-size: 30px;
        margin-bottom: 14px;
        width: fit-content;
        height: 86px;
        line-height: 86px;
        padding: 0 16px;
        white-space: nowrap;
      }
      b {
        width: 56px;
        height: 86px;
        background: #F7F8FA;
        border-radius: 8px;
        font-size: 48px;
        display: inline-block;
        font-weight: bold;
        color: #212026;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
    &-img{
      display: flex;
      align-items: center;
      img{
        width: 100%;
      }
    }
  }
  .face-recognition-ipload {
    margin-top: 20px;
    .face-recognition-video-box{
      background: #F7F8FA;
      border-radius: 4px;
      padding:0 0 20px 20px;
      height: 116px;
      line-height: 116px;
      .el-upload__tip{
        display: inline-block;
        margin-left: 14px;
        font-family: PingFangSC-Regular;
        font-size: 12px;
        color: rgba(132,133,138,0.70);
        line-height: 18px;
        font-weight: 400;
      }
    }
  }
  .face-recognition-requirement-words{
    text-align: left;
    margin-left: 78px;
    p {
      padding: 0;
      margin: 0;
    }
    .btn-take {
      width: 108px;
      height: 32px;
      padding: 0 16px;
      margin-top: 36px;
    }
    .tips{
      font-family: PingFangSC-Regular;
      font-size: 14px;
      color: rgba(132,133,138,0.70);
      line-height: 18px;
      font-weight: 400;
      padding-bottom: 10px;
      margin-top: 14px;
    }
    .important-tips{
      margin-bottom: 20px;
      font-family: PingFangSC-Medium;
      font-size: 18px;
      font-weight: 600;
      color: #212026;
      line-height: 25px;
      width: 270px;
    }
  }
}
</style>
