<!-- 身份证上传 -->
<template>
  <div class="g-components-upload-idcard">
    <a-upload list-type="picture-card" class="avatar-uploader" :show-upload-list="false" :before-upload="beforeUpload" @change="handleUpload" :accept="accept">
      <img v-if="image && from == 'idcard'" :src="image" alt="avatar" style="height: 32px;width: auto;" />
      <div v-else class="g_flex_row_center">
        <PlusOutlined class="g_c_8c g_fw_600 g_fs_14 g_mr_2" />
        <div class="ant-upload-text g_fs_14 g_c_8c">上传证件</div>
      </div>
    </a-upload>
  </div>
</template>

<script setup>
/* 身份证上传
 * @params   url 回显的图片
 * @params   from 来源。
 *           default：普通图片上传
 *           idcard：身份证识别上传
 * @function submitEvent 识别成功回调，返回对象格式
 * 						 {
 *							info:身份证携带信息
 * 							image:身份证图片oss地址
 * 						 }
 */
import { ref, onMounted, getCurrentInstance, watch, defineEmits, defineProps } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { uploadImage } from '../../../api/base.js'
import $ from 'jquery'

/* #################### 初始化事件 #################### */
const commonJS = getCurrentInstance().appContext.app.config.globalProperties.G
const emits = defineEmits(['submitEvent'])
const props = defineProps({
  url: {
    type: String,
    default: () => {
      return ''
    },
  },
  from: {
    type: String,
    default: () => {
      return 'default'
    },
  },
  accept: {
    type: String,
    default: () => {
      return 'image/png,image/jpg,image/jpeg'
    },
  },
})

onMounted(() => {
  image.value = props.url
})

const image = ref('')
const beforeUpload = (file) => {
  return false
}

const handleUpload = (info) => {
  uploadImage().then((res) => {
    let dataObj = {}
    dataObj.policy = res.data.data.policy
    dataObj.signature = res.data.data.signature
    dataObj.ossaccessKeyId = res.data.data.accessid
    dataObj.key = res.data.data.dir + commonJS.getUUID() + '_${filename}'
    dataObj.dir = res.data.data.dir
    dataObj.host = res.data.data.host
    let url = 'http://matripe-cms.oss-cn-beijing.aliyuncs.com'
    var formData = new FormData()
    // 创建身份证识别
    var idcardFormData = new FormData()
    idcardFormData.append('uploadFile', info.file)

    //注意formData里append添加的键的大小写
    formData.append('key', dataObj.key) //存储在oss的文件路径
    formData.append('OSSAccessKeyId', dataObj.ossaccessKeyId) //accessKeyId
    formData.append('policy', dataObj.policy) //policy
    formData.append('Signature', dataObj.signature) //签名
    formData.append('success_action_status', '200') // 上传成功返回的状态码，不设置则是204
    formData.append('file', info.file) // 一定在最后
    // 创建请求的选项对象
    $.ajax({
      type: 'post',
      url: 'http://matripe-cms.oss-cn-beijing.aliyuncs.com',
      data: formData,
      contentType: false, // 不设置Content-Type请求头
      processData: false,
      success: function (data) {
        image.value = dataObj.host + '/' + dataObj.key.replace('${filename}', info.file.name)
        if (props.from == 'default') {
          // 普通图片上传
          emits('submitEvent', {
            info: {},
            image: image.value,
          })
        } else if (props.from == 'idcard') {
          $.ajax({
            type: 'post',
            url: 'http://idaotian.com/yishoudan/commons/idCardOcrRecognize',
            data: idcardFormData,
            headers: {
              Authorization: 'Bearer ' + localStorage.getItem('DAOTIAN_token'),
            },
            contentType: false, // 不设置Content-Type请求头
            processData: false,
            success: function (idCardData) {
              if (idCardData.status == 200) {
                emits('submitEvent', {
                  info: idCardData.data,
                  image: image.value,
                })
              } else {
                console.log('识别异常：', err)
              }
            },
            fail: function (err) {
              console.log(err)
            },
          })
        }
      },
      fail: function (err) {
        console.log('上传异常：', err)
      },
    })
  })
}
</script>

<style lang="less">
.g-components-upload-idcard {
}
</style>