import request from './request'
import { ocrIdcard } from '@/api/user'

/**
 * base64转文件流
 * @param code 当前base编码
 */
const base64ToBlob = function(code) {
  const parts = code.split(';base64,')
  const contentType = parts[0].split(':')[1]
  const raw = window.atob(parts[1])
  const rawLength = raw.length
  const uInt8Array = new Uint8Array(rawLength)
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i)
  }
  return new Blob([uInt8Array], {
    type: contentType
  })
}

/**
 * 获取加密的图片原件
 * @param uuid 文件id
 * @returns 图片base64
 */
export const imageViewer = async(uuid) => {
  const { base64 } = await request({
    url: `${process.env.VUE_APP_BASIC_API}cuscImage/viewBase64`,
    data: { uuid }
  })
  return URL.createObjectURL(base64ToBlob(`data:${uuid.indexOf('.mp4') ? 'video/mp4' : 'image/png'};base64,${base64}`))
}

/**
 * 通过OCR获取身份证信息
 * @param file 当前文件
 */
export const getIdcardInfoByOcr = file => {
  // 获取FileReader实例
  var reader = new FileReader()
  // 读取文件
  reader.readAsDataURL(file)
  // 返回值
  return new Promise((resolve, reject) => {
    // 文件读取成功转换成base64
    reader.onload = async function() {
      // 转换完成输出该文件base64编码
      const idcardInfo = await ocrIdcard({
        ocrPic: this.result.slice(this.result.indexOf('base64,') + 7)
      })
      // 性别
      idcardInfo.gender = idcardInfo.gender === '男' ? '1' : '2'
      // 数据回填
      resolve(idcardInfo)
    }
  })
}
