<template>
  <view class="uploadImg">
    <view
      class="uploadImg__item"
      v-for="(item, index) in imgArr || []"
      :key="index"
      @click="previewImage(imgArr, index)"
    >
      <image class="uploadImg__img" :src="item" mode="aspectFill"> </image>
      <view
        class="uploadImg__close"
        @click.stop="delImg(index)"
        v-if="type === 'add'"
      >
        <uv-icon
          name="close-circle-fill"
          size="40rpx"
          color="#000000"
        ></uv-icon>
      </view>
    </view>
    <view
      class="uploadImg__item add_img"
      v-if="imgArr.length < imgCount && type === 'add'"
      @click.stop="uploadImg"
    >
      <uv-icon name="plus" size="40rpx" color="#999999"></uv-icon>
    </view>
  </view>
</template>

<script setup name="uploadImg">
import { ref, watch } from "vue";
import { commonUpload_api } from "@/api/index";

// 支持 v-model 的定义
const props = defineProps({
  modelValue: {
    type: [Array, String],
  },
  imgArr: {
    type: Array,
    default: () => [],
  }, // 图片数组
  imgCount: {
    type: Number,
    default: 5,
  }, // 可上传图片总数
  uploadImgCount: {
    type: Number,
    default: 1,
  }, // 一次上传图片数
  type: {
    type: String,
    default: "add",
  }, // add 添加图片，view 查看
  imgSize: {
    //图片大小 单位M
    type: Number,
    default: 4,
  },
  imgType: {
    //如果是小程序，这个值则没用作用
    type: [Array],
    default: function () {
      return ["jpeg", "png", "jpg"];
    },
  },
  closeTip: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue", "result"]);

let list = props.modelValue ? typeof props.modelValue == "object" ? props.modelValue : [props.modelValue] : null;
// console.log("list===>", list);
// 使用 modelValue（v-model）或 imgArr 或 value 作为初始值
const imgArr = ref(list || props.imgArr || []);
const imgCount = ref(props.imgCount);
const uploadImgCount = ref(props.uploadImgCount);
const type = ref(props.type);
const imgSize = ref(props.imgSize);
const imgType = ref(props.imgType);
const closeTip = ref(props.closeTip);

// 监听 imgArr 变化
watch(
  () => props.imgArr,
  (newValue) => {
    if (!props.modelValue) {
      imgArr.value = newValue || [];
    }
  }
);

// 监听 value 变化
watch(
  () => props.modelValue,
  (newValue) => {
    // console.log("newValue===>", newValue);
    let newValueList = JSON.parse(JSON.stringify(newValue));
    let list = [];
    if (newValue) {
      if (typeof newValue == "object") {
        list = [...newValueList];
      } else {
        list = newValueList.split(",");
      }
    }
    imgArr.value = list;
  }
);

watch(
  () => props.imgCount,
  (newValue) => {
    // console.log("newValue===>", newValue);
    imgCount.value = (newValue || 0) * 1;
  }
);
watch(
  () => props.uploadImgCount,
  (newValue) => {
    uploadImgCount.value = (newValue || 0) * 1;
  }
);
watch(
  () => props.type,
  (newValue) => {
    type.value = newValue || "add";
  }
);
watch(
  () => props.imgSize,
  (newValue) => {
    imgSize.value = newValue;
  }
);
watch(
  () => props.imgType,
  (newValue) => {
    imgType.value = newValue;
  }
);
watch(
  () => props.closeTip,
  (newValue) => {
    closeTip.value = newValue;
  }
);

// 图片预览
const previewImage = (urls, index) => {
  uni.previewImage({
    urls: urls,
    current: index,
  });
};

// 删除图片
const delImg = (index) => {
  let list = [...imgArr.value];
  list.splice(index, 1);
  imgArr.value = list;
  emit("result", list);

  // 触发所有可能的事件
  if (props.imgCount > 1) {
    emit("update:modelValue", list);
  } else {
    emit("update:modelValue", "");
  }
};

// 上传图片
const uploadImg = () => {
  // console.log("上传图片");
  uni.chooseImage({
    count: uploadImgCount.value,
    success(res) {
      console.log("上传图片成功", res);
      if (res.tempFiles[0].size > imgSize.value * 1024 * 1024) {
        uni.showToast({
          title: `图片不能大于${imgSize.value}M`,
          icon: "none",
        });
        return false;
      }
      uni.showLoading({ title: "上传中...", mask: true });
      commonUpload_api(res.tempFilePaths[0])
        .then((res) => {
          // console.log(res);
          uni.hideLoading();
          if (res.code == 200) {
            let list = [...imgArr.value];
            list.push(res.data.url);
            emit("result", list);
            // console.log("上传图片成功", props.imgCount > 1);
            // 触发所有可能的事件
            if (props.imgCount > 1) {
              emit("update:modelValue", list);
            } else {
              emit("update:modelValue", res.data.url);
            }
          }
        })
        .catch((err) => {
          console.log("上传图片失败", err);
          // uni.hideLoading();
        });
    },
    fail(err) {
      // console.log("上传图片失败", err);
      // uni.showToast({
      //   title: "请检查格式是否正确" + imgType.value.join(","),
      //   icon: "none",
      //   duration: 3000,
      // });
    },
  });
};
</script>

<style lang="scss" scoped>
.uploadImg {
  display: flex;
  flex-wrap: wrap;
  .add_img {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1rpx dashed #999999;
  }
  .uploadImg__item {
    flex-shrink: 0;
    position: relative;
    width: 200rpx;
    height: 200rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 10rpx;
    .uploadImg__img {
      width: 100%;
      height: 100%;
      border-radius: 10rpx;
    }
    .uploadImg__close {
      position: absolute;
      top: 0;
      right: 0;
      z-index: 1;
      // background-color: #ffffff;
      // border-radius: 50%;
    }
  }
}
</style>
