<template>
  <div class="form-item-box" :style="{ width: width }" v-if="props.nopicer">
    <el-upload class="upload-demo" ref="uploadRef" :action="actionUrl" :on-change="filehandleChange" :on-remove="handleRemove" :on-exceed="handleExceed" :limit="limit" :on-success="handlerSuccess">
      <el-button> 选择文件 </el-button>
    </el-upload>
  </div>
  <div class="form-item-box" :style="{ width: width }" v-else>
    <el-upload v-model:file-list="fileList" class="upload-demo" :list-type="isImg ? 'picture-card' : ''" :action="actionUrl" :on-change="handleChange" :before-upload="beforeImgUpload" :on-remove="handleRemove" :on-exceed="handleExceed" :limit="limit" :on-success="handlerSuccess">
      <template #default>
        <el-icon v-if="isImg">
          <Plus />
        </el-icon>
        <el-button v-else type="primary">上传</el-button>
      </template>
      <template #file="{ file }">
        <div v-if="isImg">
          <img class="el-upload-list__item-thumbnail" style="width: 100%" :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="handleDownload(file)">
              <el-icon>
                <Download />
              </el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon>
                <Delete />
              </el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { COMPONENT_WIDTH } from "@/constant";
import {
  ref,
  defineProps,
  defineEmits,
  defineExpose,
  computed,
  watch,
  onMounted
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getApi } from "@/api/tobAcco_api.js";
import type from "element-plus/es/components/upload/src/upload.type";
import { useStore } from "vuex";
const uploadRef = ref(null);
const props = defineProps({
  //获取组件传值
  modelValue: {
    type: Array,
    default: []
  },
  limit: {
    type: Number,
    default: 10
  },
  isImg: {
    type: Boolean,
    default: false
  },
  width: {
    default: COMPONENT_WIDTH,
    type: String
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  nopicer: {
    type: Boolean,
    default: false
  },
  // 是否显示文件列表
  ShowfileList: {
    type: Boolean,
    default: true
  },
  delrow: {
    type: Object,
    default: {}
  }
});
const actionUrl = computed(() => "/mosty-api/mosty-base/minio/image/upload/id");
const emits = defineEmits([
  "update:modelValue",
  "handleChange",
  "filehandleChange"
]);

//获取后缀
const getSuffix = (fileName) => {
  let suffix = "";
  try {
    suffix = fileName.substr(fileName.lastIndexOf(".") + 1, 4); //截取最后一个点号后4个字符
  } catch (err) {
    suffix = "";
    return "OTHER";
  }
  // fileName无后缀返回 false
  if (!suffix) return "";

  // 图片格式
  var imglist = ["png", "jpg", "jpeg", "bmp", "gif"];
  if (imglist.includes(suffix)) return "IMG";

  //txt
  if (suffix === "txt") return "TXT";

  //excel XLS
  const excelist = ["xls", "xlsx"];
  if (excelist.includes(suffix)) return "XLS";

  // 匹配 word
  var wordlist = ["doc", "docx"];
  if (wordlist.includes(suffix)) return "DOC";

  //pdf
  if (suffix === "pdf") return "PDF";

  //视频 音频
  var videolist = [
    "mp4",
    "m2v",
    "mkv",
    "rmvb",
    "wmv",
    "avi",
    "flv",
    "mov",
    "m4v"
  ];
  if (videolist.includes(suffix)) return "VIDEO";

  var musiclist = ["mp3", "wav", "wmv"];
  if (musiclist.includes(suffix)) return "MUSIC";

  var pptlist = ["ppt", "pptx"];
  if (pptlist.includes(suffix)) return "PPT";

  //压缩包
  var yslist = ["7z", "rar", "zip", "apz", "ar", "hpk", "hyp", "hbc2"];
  if (yslist.includes(suffix)) return "YS";

  //否则返回other
  return "OTHER";
};

const imageUrl = ref("");
const store = useStore();
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const headers = ref({
  Authorization: store.getters.token
});

const showpicer = (val) => {
  if (val == true) {
    return "picture - card";
  } else {
    return "";
  }
};
watch(
  () => props.delrow,
  (val) => {
    if (val) {
      let index = fileList.value.findIndex(function (item) {
        return item === val;
      });
      fileList.value.splice(index, 1);
      props.modelValue.splice(index, 1);
      emits("filehandleChange", fileList.value);
    }
  }
);
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      fileList.value = [];
      let ids;
      let val = JSON.parse(JSON.stringify(newVal));
      if (val instanceof Array) {
        ids = newVal;
      } else {
        ids = newVal.split(",");
      }
      ids.forEach((item) => {
        getApi({}, `/mosty-base/minio/file/download/${item}`).then((res) => {
          fileList.value.push({
            name: res.originalName,
            url: `/mosty-api/mosty-base/minio/image/download/` + item
          });
        });
      });
    }
  },
  { deep: true }
);
// 传给子组件的id
const fileListId = ref([]);
onMounted(() => { });
const fileList = ref([]);
const handlerSuccess = (res, file, fileList) => {
  if (props.ShowfileList == false) {
    uploadRef.value.clearFiles(); //去掉文件列表
  }
  fileList.value = fileList;
  if (props.limit == 1) {
    emits("update:modelValue", res.data);
  } else {
    fileListId.value.push(res.data);
    emits("update:modelValue", fileListId.value);
  }
};
const handlePreview = (file) => { };
const handleExceed = (files, fileList) => {
  ElMessage.warning(`限制，只能上传${props.limit}个文件或图片`);
};

const beforeImgUpload = (file) => {
  if (props.isImg) {
    let isIMG = false;
    if (getSuffix(file.name) === "IMG") {
      isIMG = true;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isIMG) {
      ElMessage.error("上传图片只能是jpg/png/jpeg/bmp/gif格式!");
    }
    if (!isLt5M) {
      ElMessage.error("上传图片大小不能超过 5MB!");
    }
    return isIMG && isLt5M;
  } else {
    return true;
  }
};

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};

const handleAvatarSuccess = (res, file) => {
  imageUrl.value = URL.createObjectURL(file.raw);
};
const handleDownload = (file) => {
  if (file.response) {
    window.open(
      `/mosty-api/mosty-base/minio/image/download/${file.response.data}`,
      "_blank"
    );
  } else {
    window.open(file.url, "_blank");
  }
};
const handleRemove = (file) => {
  let index = fileList.value.findIndex(function (item) {
    return item.url === file.url;
  });
  fileList.value.splice(index, 1);
  let list = [];
  if (props.limit != 1) {
    list = JSON.parse(props.modelValue);
    list.splice(index, 1);
  }
  emits("update:modelValue", JSON.stringify(list));
};
</script>

<style lang="scss" scoped>
.list_box {
  display: flex;
  width: 100%;
  justify-content: space-between;
  padding: 10px;
  color: #fff;

  .one_text_detail {
    color: #1983e5;
  }

  .icon_box {
    display: flex;

    & > div {
      margin-left: 10px;
    }
  }
}

::v-deep .el-upload-list__item {
  &:hover {
    background: transparent;
  }
}

.form-item-box {
  width: 100% !important;
}
</style>
