<template>
  <view class="upload-file" @click="chooseImage">
    <slot v-if="$slots.default"></slot>
    <view class="icon" v-if="!modelValue"> + </view>
    <image class="img" v-else :src="modelValue"></image>

	<view class="close" @click.stop="()=>{}" v-if="modelValue">
		<up-icon name="close-circle" color="#333" size="14" @click="clearImg" ></up-icon>
	</view>
  </view>
</template>

<script setup>
import { uploadFile } from "@/http/api/index.js";

import { reactive, ref, watch } from "vue";

const modelValue = defineModel({
  type: String,
  default: "",
});

function chooseImage() {
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album", "camera "],
    success: async function (res) {
      uni.showLoading({
        title: "上传中",
      });
      console.log(res);
      const fileRes = await uploadFile(res.tempFiles[0]);
      uni.hideLoading();
      if (fileRes) {
        modelValue.value = fileRes;
      } else {
        uni.showToast({
          title: "上传失败",
          icon: "none",
        });
      }
    },
  });
}

function clearImg(){
	modelValue.value=""
}
</script>

<style lang="scss">
.upload-file {
  $size: 128rpx;
  width: $size;
  height: $size;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8rpx;
  position: relative;
  .close{
	position: absolute;
	right: -10rpx;
	top: -10rpx;
  }
  .img {
    width: $size;
    height: $size;
  }
  .icon {
    width: 36rpx;
    height: 36rpx;
    border: 4rpx solid #999;
    border-radius: 8rpx;
    font-weight: 700;
    color: #999;
    font-size: 32rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    line-height: 1;
    padding: 0;
    margin: 0;
    text-align: center;
  }
}
</style>
