<template>
  <u-upload
    v-if="cusImg"
    :fileList = "fileList"
    @afterRead="afterRead"
    @delete="deletePic"
    :multiple="false"
    :uploadText="uploadText"
    :previewFullImage="previewFullImage"
    :maxSize="maxSize"
    :maxCount="1"
    :deletable="deletable"
    :uploadIcon="uploadIcon"
    :uploadIconColor="uploadIconColor"
    :height="height"
    :width="width"
    accept="image"
    @oversize="oversize"
  ><slot></slot>
  </u-upload>
  <u-upload
    v-else
    :fileList = "fileList"
    @afterRead="afterRead"
    @delete="deletePic"
    :multiple="false"
    :uploadText="uploadText"
    :previewFullImage="previewFullImage"
    :maxSize="maxSize"
    :maxCount="1"
    :deletable="deletable"
    :uploadIcon="uploadIcon"
    :uploadIconColor="uploadIconColor"
    :height="height"
    :width="width"
    accept="image"
    @oversize="oversize"
  >
  </u-upload>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, watch, watchEffect } from "vue";
interface Props {
  serverProxyApiUrl?: string; //后台服务器请求地址
  type?: string //上传证件类型：101-身份证；102：银行卡；103-户口本；104-社保卡；201-营业执照；301-增值税发票
  outputFigure?: string //类型是身份证时，是否需要图案检测功能，1表示需要
  isResidentPage?: string | number // 类型是户口本时，是否是户口本常住人口页，1表示是

  result?: object; // 识别结果对象, 初始为null
  maxSize?: string | number; //上传文件的大小限制,单位Byte
  deletable?: boolean; //是否显示删除图片的按钮, 默认true
  uploadText?: string; //上传区域的提示文字
  previewFullImage?: boolean; //是否允许展示预览图, 默认true
  uploadIcon?: string; //上传区域的图标，只能内置图标, 默认camera-fill
  uploadIconColor?: string; //上传区域的图标的颜色, 默认#D3D4D6
  height?: string; //内部预览图片区域和选择图片按钮的区域高度，单位rpx，不能是百分比，或者auto
  width?: string; //内部预览图片区域和选择图片按钮的区域宽度，单位rpx，不能是百分比，或者auto
  cusImg?: boolean; //添加image以自定义上传样式，达到身份证，银行卡等不同场景需求
}

const props = withDefaults(defineProps<Props>(), {
  serverProxyApiUrl: Global.serverProxyApiUrl,
  fileServerType: Global.fileServerType,
  previewFullImage: true,
  uploadText: 'OCR识别',
  uploadIcon: 'scan',
  type: '101',
  deletable: true,
  cusImg: false
});

// 文件Url数组(实际就一张图片)
const fileList = reactive([]);

// OCR识别结果对象
const fileResult = ref({});

const emit = defineEmits(["doUpload"]);

// 新增图片
const afterRead = async (event) => {
  let eventFile = null;
  if (Object.prototype.toString.call(event.file) === "[object Array]") {
    eventFile = event.file[0];
  } else if (Object.prototype.toString.call(event.file) === "[object Object]") {
    eventFile = event.file;
  }
  fileList[0] = {url: eventFile.url}
  const upload = {
    url: eventFile.url,
    size: eventFile.size,
    name: eventFile.name,
  };
  await doUpload(upload);
};

//上传操作
const doUpload = (upload: any) => {
  let extName = "";
  if (upload.name) {
    extName = upload.name.substring(upload.name.lastIndexOf(".") + 1);
  } else if (upload.url.includes(".")) {
    extName = upload.url.substring(upload.url.lastIndexOf(".") + 1);
  }
  if (
    ![
      "jpg",
      "png",
      "jpeg",
      "JPG",
      "JPEG",
      "PNG"
    ].includes(extName)
  ) {
    uni.showToast({
      title: "请上传图片",
      duration: 2000,
    });
    return;
  }
 
  // url：后台接口地址
  //filePath: 文件资源路径
  //formData.type: 上传证件类型：101-身份证；102：银行卡；103-户口本；104-社保卡；201-营业执照；301-增值税发票
  uni.showLoading({
    title: "识别中",
    mask: true
  })
  uni.uploadFile({
    url: props.serverProxyApiUrl + "rest/wbl/ocr/identify",
    filePath: upload.url,
    name: "file",
    formData: {
      type: props.type,
      outputFigure: '1'
    },
    success: (res) => {
      if(res.errMsg == 'uploadFile:ok'){
        uni.showToast({
          title:'识别成功'
        })
      }
      if(res.data) {
        let data = JSON.parse(res.data);
        if(data.code=='200' && Object.prototype.toString.call(data.data)=="[object Object]") {
          fileResult.value = data.data;
          emit("doUpload", fileResult.value);
        }else{
          uni.showToast({
            title:'识别失败, 请确认类型'
        })
        }
      }
    },
    complete: () => {
      uni.hideLoading()
    }
  });
};

// 删除图片
const deletePic = async (event) => {
  let index = event.index;
  fileList.splice(index, 1);
};
//超出大小提示
const oversize = () => {
  uni.showToast({
    title: `大小不能超过 ${Math.floor(Number(props.maxSize) / 1024).toFixed(
      2
    )}KB!`,
    duration: 2000,
  });
};
</script>
<style lang="scss" scoped>
  .u-upload__wrap :deep(.u-upload__button) {
    margin:0
  }
</style>


