<template>
  <div class="uploader">
    <div class="preview-container">
      <div class="preview-list">
        <div
          class="preview-item"
          v-for="(item, index) in tempFileUrl"
          :key="index"
        >
          <div class="preview-item-img" v-if="item.type == 'image'">
            <van-image :src="item.url" fit="cover" />
          </div>
          <div class="preview-item-img" v-if="item.type == 'file'">
            <i
              class="van-icon van-icon-description van-uploader__file-icon"
            ></i>
            <span
              style="
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                width: 64px;
                font-size: 13px;
                padding-top: 5px;
              "
              >{{ item.name }}</span
            >
          </div>
          <div class="preview-item-close">
            <van-icon name="cross" @click="onDelete(item)" />
          </div>
        </div>
      </div>
    </div>

    <div class="upload_section">
      <van-uploader
        :before-read="beforeRead"
        :after-read="afterRead"
        :disabled="false"
      >
        <div class="upload-file">
          <img src="../images/icon_upload_img.png" />
          上传图片
        </div>
      </van-uploader>

      <van-uploader
        style="margin-left: 4%"
        :before-read="beforeReadFile"
        :after-read="afterRead"
        :disabled="false"
        accept="image/*, *.xlsx, *.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, *.txt, *.pdf"
      >
        <div class="upload-file">
          <img src="../images/icon_upload_file.png" />
          上传附件
        </div>
      </van-uploader>
    </div>
  </div>
</template>

<script>
// import setLoading from "@/common/loading";
// import { uploadFile } from "../api";
import { policy } from "@/views/massMessage/api";
import axios from "axios";
export default {
  name: "upload",
  props: ["fileUrl"],
  data() {
    return {
      tempFileUrl: this.fileUrl || [],
      type: "image",
      ossUploadUrl: "https://ks3-cn-beijing.ksyuncs.com/daya",
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        KSSAccessKeyId: "",
        acl: "public-read",
        name: "",
      },
    };
  },
  watch: {
    fileUrl(val) {
      this.tempFileUrl = val;
    },
  },
  methods: {
    onDelete(item) {
      const index = this.tempFileUrl.indexOf(item);
      this.tempFileUrl.splice(index, 1);
      this.$emit("fileUrl", this.tempFileUrl);
    },
    beforeRead(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$toast("上传图片大小不能超过 5MB");
        return false;
      }
      const fileList = this.tempFileUrl.map((item) => {
        if (item.type == "image") {
          return item;
        }
      });
      if (fileList.length >= 5) {
        this.$toast("最多上传5张图片");
        return false;
      }
      this.type = "image";
      return true;
    },
    beforeReadFile(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$toast("上传文件大小不能超过 20MB");
        return false;
      }
      const fileList = this.tempFileUrl.map((item) => {
        if (item.type == "file") {
          return item;
        }
      });
      if (fileList.length >= 3) {
        this.$toast("最多上传3个附件");
        return false;
      }
      this.type = "file";
      return true;
    },
    async afterRead(file) {
      // 上传头像
      // 上传头像
      try {
        file.status = "uploading";
        file.message = "上传中...";
        let tempName = file.file.name || "";
        const fileName = tempName && tempName.replace(/ /gi, "_");
        let key = new Date().getTime() + fileName;
        let objTemp = {
          filename: fileName,
          bucketName: this.bucket_name,
          postData: {
            filename: fileName,
            acl: "public-read",
            key: key,
            unknowValueField: [],
          },
        };

        const res = await policy(objTemp);
        const obj = {
          policy: res.data.policy,
          signature: res.data.signature,
          key: key,
          KSSAccessKeyId: res.data.kssAccessKeyId,
          acl: "public-read",
          name: fileName,
        };

        let formData = new FormData();
        for (let key in obj) {
          formData.append(key, obj[key]);
        }
        formData.append("file", file.file);
        await axios({
          method: "post",
          url: this.ossUploadUrl,
          data: formData,
        });
        const uploadUrl = this.ossUploadUrl + "/" + key;
        file.status = "done";
        this.tempFileUrl.push({
          url: uploadUrl,
          name: file.file.name,
          type: this.type,
          file: {
            // 为了处理pc端显示文件名称
            name: file.file.name,
          },
        });

        this.$emit("update:fileUrl", this.tempFileUrl);
      } catch (e) {
        //
        file.status = "failed";
        file.message = "上传失败";
        return false;
      }
      // try {
      //   setLoading(true);
      //   file.status = "uploading";
      //   file.message = "上传中...";
      //   let formData = new FormData();
      //   formData.append("file", file.file);
      //   let res = await uploadFile(formData);
      //   let result = res.data;
      //   if (result.code == 200) {
      //     file.status = "done";
      //     this.tempFileUrl.push({
      //       url: result.data.url,
      //       name: file.file.name,
      //       type: this.type,
      //       file: {
      //         // 为了处理pc端显示文件名称
      //         name: file.file.name,
      //       },
      //     });

      //     this.$emit("update:fileUrl", this.tempFileUrl);
      //   } else {
      //     file.status = "failed";
      //     file.message = "上传失败";
      //     this.$toast(result.msg);
      //     return false;
      //   }
      //   setLoading(false);
      // } catch (err) {
      //   setLoading(false);
      //   return false;
      // }
    },
  },
};
</script>

<style lang="less" scoped>
.preview-container::-webkit-scrollbar {
  display: none;
}
.preview-container {
  width: 100%;
  overflow: hidden;
  overflow-y: hidden;
  overflow-x: auto;
}
.preview-list {
  display: flex;
}
.preview-item {
  position: relative;
  margin: 0 8px 8px 0;
  border-radius: 4px;
  overflow: hidden;
}
.preview-item,
.preview-item-img {
  background: #f7f8fa;
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  /deep/.van-image {
    width: 100%;
    height: 100%;
  }
}

.preview-item-close {
  position: absolute;
  top: 0;
  right: 0;
  width: 14px;
  height: 14px;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 0 0 0 12px;

  /deep/.van-icon {
    position: absolute;
    top: -2px;
    right: -2px;
    color: #fff;
    font-size: 16px;
    -webkit-transform: scale(0.5);
    transform: scale(0.5);
  }
}

.upload_section {
  display: flex;
  align-content: center;
  /deep/.van-uploader {
    width: 48%;
  }
  /deep/.van-uploader__wrapper,
  /deep/.van-uploader__input-wrapper {
    width: 100%;
  }
}
.upload-file {
  background: #f7f8f9;
  border-radius: 9px;
  padding: 0.12rem 0.14rem;
  display: flex;
  align-content: center;
  justify-content: center;
  font-size: 0.14rem;
  font-weight: 500;
  color: #01c1b5;
  img {
    height: 22px;
    margin-right: 0.19rem;
  }
}
</style>
