<template>
  <view class="upload-wrapper">
    <view class="upload-wrapper-text ismust" v-if="formItemTitle">
      {{ formItemTitle }}
    </view>
    <view class="upload-wrapper-upload">
      <view class="upload-files-content">
        <template v-if="fileListData.length > 0">
          <view
            class="upload-files"
            v-for="(item, index) in fileListData"
            :key="index + item.path"
          >
            <view class="image-box">
              <image :src="item.path" class="show-image-box"></image>
              <image
                src="/static/images/new_ui/guanbi.png"
                class="close-box"
                v-if="!disabledDetele"
                @click="onHandleDelete(item, index)"
              ></image>
            </view>
          </view>
        </template>
        <view
          class="upload-no-files"
          :style="getUploadClass"
          v-if="isHidden"
          @click="uploadDataFiles"
        >
          <image src="/static/images/new_ui/xiangji.png"></image>
          <view class="upload-no-files__text"> {{ setImageTitle }} </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { uploadFile } from "@/commit/product.js";
import { baseURL, phpToken } from "@/commit/requestPhp.js";
export default {
  props: {
    maxLimit: {
      type: Number,
      default: 5,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    disabledDetele: {
      type: Boolean,
      default: false,
    },
    formItemTitle: {
      type: String,
      default: "",
    },
    isMust: {
      type: Boolean,
      default: false,
    },
    imageTitle: {
      type: String,
      default: "",
    },
    index: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      fileListData: [],
      paths: "",
    };
  },
  methods: {
    emitChangeFiles(data) {
      this.$emit("changeFiles", {
        fileList: data || [],
        index: this.index,
      });
      // console.log(data,"emitChangeFiles")
    },
    uploadDataFiles() {
      if (this.disabled || this.maxLimit == 0) {
        return;
      }
      let that = this;
      uni.chooseImage({
        count: 1, // 最多可以选择的图片张数，默认9
        // sizeType: ["compressed"], // original 原图，compressed 压缩图，默认二者都有
        sourceType: ["album", "camera"], // album 从相册选图，camera 使用相机，默认二者都有
        success: async function (res) {
            const tempFiles = res.tempFiles;
            const tempFilePaths = res.tempFilePaths;
          if (that.fileListData.length === 0) {
          
            const data = await that.uploadFileData(tempFiles[0]);
            if (!data) {
              that.fileListData = [];
            } else {
              that.fileListData.push({
                path: data,
                Files: tempFiles,
              });
            }
          } else if (that.fileListData.length < that.maxLimit) {
            const dataPath = await that.uploadFileData(tempFiles[0]);
            that.fileListData = that.fileListData.concat({
              path: dataPath,
              Files: tempFiles,
            }); //concat追加到数组
          }
          that.emitChangeFiles(that.fileListData);
          //   console.log(that.fileListData,"that.fileListData")
        },
        fail() {
          that.emitChangeFiles([]);
        },
      });

      // let that = this;
      // that.$time.uploadPictures((res) => {
      //   console.log(res);
      //   // that.merchantsIn.business_license = res;
      // });
    },
    onHandleDelete(item, index) {
      if (!this.disabledDetele) {
        this.fileListData.splice(index, 1);
        console.log(this.fileListData, "this.fileListData");
        this.emitChangeFiles(this.fileListData);
      }
    },
    async uploadFileData(files) {
      uni.showLoading({
        title: "上传中",
        mask: true,
      });
      const uploadUrl = `${baseURL}/mer/upload/image/0/file`;
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: uploadUrl,
          file: files,
          name: "file",
          header: {
            "X-Token": phpToken,
            // 'Content-Type': "application/json;charset=UTF-8",
          },
          success: (res) => {
            const data = JSON.parse(res.data);
            if (data.status === 200) {
              uni.showToast({
                title: "上传成功",
                icon: "success",
              });
              this.paths = data.data.src || "";
            } else {
              uni.showToast({
                title: "上传失败",
                icon: "error",
              });
              this.paths = "";
            }
            resolve(this.paths);
            console.log("上传成功", JSON.parse(res.data));
             uni.hideLoading();
            uni.hideToast();
          },
          fail: (err) => {
            console.error("上传失败", err);
            this.paths = "";
            resolve(this.paths);
             uni.hideLoading();
            uni.hideToast();
          },
          complete: () => {
            uni.hideLoading();
            uni.hideToast();
          },
        });
      });
    },
  },
  computed: {
    isHidden() {
      return this.fileListData.length < this.maxLimit;
    },
    setImageTitle() {
      if (this.disabled || this.maxLimit == 0) {
        return "禁止上传图片";
      } else if (
        this.fileListData.length < this.maxLimit &&
        this.fileListData.length > 0 &&
        this.imageTitle
      ) {
        return `${this.fileListData.length} / ${this.maxLimit}`;
      } else {
        return "添加图片";
      }
    },
    getUploadClass() {
      let isZeo = this.fileListData.length > 0;
      let styles = {};
      if (isZeo) {
        styles = {
          width: "208rpx",
        };
      } else {
        styles = {
          width: "100%",
        };
      }
      return styles;
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-wrapper {
  width: calc(100% - 0rpx);
  // border: 2rpx solid #f00;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
  padding: 32rpx;
  box-sizing: border-box;
  background-color: #ffffff;
  .upload-wrapper-text {
    width: 100%;
    font-weight: 600;
    font-size: 30rpx;
    color: #333333;
    margin-bottom: 20rpx;
    &.ismust {
      &::after {
        content: "*";
        color: #f00;
        padding-left: 10rpx;
      }
    }
  }
  .upload-wrapper-upload {
    width: 100%;
    user-select: none;
    border-radius: 8rpx;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .upload-files-content {
      // border: 2rpx solid #f00;

      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
      width: 100%;
    }
    .upload-no-files {
      height: 208rpx;
      width: 100%;
      // background: #f00;
      background: #f8f8f8;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      flex-shrink: 0;
      border-radius: 16rpx;
      .upload-no-files__text {
        font-weight: 400;
        font-size: 26rpx;
        color: #333333;
      }
      image {
        width: 72rpx;
        height: 72rpx;
      }
    }

    .upload-files {
      display: flex;
      // border: 2rpx solid #ff0;
      gap: 26rpx;
      flex-wrap: wrap;
      border-radius: 16rpx;
      .image-box {
        position: relative;
        border-radius: 16rpx;
        .show-image-box {
          width: 208rpx;
          height: 210rpx;
        }
        .close-box {
          position: absolute;
          right: 0rpx;
          top: 0;
          width: 42rpx;
          height: 42rpx;
        }
      }
    }
  }
}
</style>
