<template>
  <div class="component-upload-image">
    <el-upload
      multiple
      :action="uploadImgUrl"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="imageUpload"
      :before-remove="handleDelete"
      :show-file-list="false"
      :headers="headers"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
    >
      <template #trigger>
        <el-button v-show="!fileList.length" class="upd-btn" icon="Upload" type="primary" plain >{{ t('common.upload') }}</el-button>
      </template>
      <div v-if="fileList.length" v-for="(file, index) in fileList" :key="index" class="pic-list" >
        <div class="el-upload-list el-upload-list--picture-card picture-card">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)" >
              <el-icon><zoom-in /></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDelete(file)" >
              <el-icon><Delete /></el-icon>
            </span>
          </span>
        </div>
        <div class="pic-status">
          <div v-if="file.status == 'success'" style="display: flex;align-items: center;font-size: 16px;font-weight: 400;" >
            <svg-icon icon-class="uploadOK" style="margin-right: 9px;width: 20px;height: 20px;flex-shrink: 0;" />
            <span style="color: rgba(67, 207, 124, 1);flex-shrink: 0;">{{ t('common.uploaded') }}</span>
          </div>
          <div style="display: flex;align-items: center;font-size: 16px;font-weight: 400;cursor: pointer;" @click="handleDelete(file)">
            <svg-icon icon-class="uploadRetry" style="margin-right: 9px;width: 20px;height: 20px;flex-shrink: 0;" />
            <span style="color: rgba(41, 187, 228, 1);flex-shrink: 0;">{{ t('common.reupload') }}</span>
          </div>
        </div>
      </div>
    </el-upload>

    <el-dialog
      v-model="dialogVisible"
      :title="t('common.preview')"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { getToken } from "@/utils/auth";
import { useLocale } from 'element-plus'

const { t } = useLocale()
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 10,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg", "bmp"],
  },
  baseUrl: String
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/ossUpload/imgUpload"); // 上传的图片服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);

watch(() => props.modelValue, val => {
  if (val) {
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : props.modelValue.split(",");
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        if (item.indexOf(props.baseUrl) === -1) {
          item = { name: item, url: props.baseUrl + item };
        } else {
          item = { name: item, url: item };
        }
      }
      return item;
    });
  } else {
    fileList.value = [];
    return [];
  }
},{ deep: true, immediate: true });

// 上传前loading加载
function handleBeforeUpload(file) {
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }
  if (!isImg) {
    window.showTip({
      title: t('common.fileTypeLt'),
      status: 'error'
    })
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      window.showTip({
        title: t('common.fileSizeLt', {n: props.fileSize}),
        status: 'error'
      })
      return false;
    }
  }
  proxy.loading.show(t('common.uploading'));
  number.value++;
}

// 文件个数超出
function handleExceed() {
  window.showTip({
    title: t('common.fileNumLt', {n: props.limit}),
    status: 'error'
  })
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200 || res.code === 0) {
    uploadList.value.push({ name: res.data.imgNameList[0], url: res.data.prefix + res.data.imgNameList[0] });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy.loading.hide();
    proxy.$modal.msgError(t('common.uploadError'));
    proxy.$refs.imageUpload.handleRemove(file);
    uploadedSuccessfully();
  }
}

// 删除图片
function handleDelete(file) {
  const findex = fileList.value.map(f => f.name).indexOf(file.name);
  if (findex > -1 && uploadList.value.length === number.value) {
    fileList.value.splice(findex, 1);
    emit("update:modelValue", listToString(fileList.value));
    return false;
  }
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit("update:modelValue", listToString(fileList.value));
    proxy.loading.hide();
  }
}

// 上传失败
function handleUploadError() {
  window.showTip({
      titleCode: 'common.error.uploadError',
      status: 'error'
  })
  proxy.loading.hide();
}

// 预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
      strs += list[i].url.replace(props.baseUrl, "") + separator;
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}
</script>

<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
    display: none;
}

.upd-btn {
  // min-width: 213px;
  height: 40px;
}

.pic-list {
  margin-top: -40px;
  display: flex;
}

.picture-card {
  width: 150px;
  height: 74px;
}

.pic-status {
  margin-left: auto;
  height: 74px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>