<template>
  <view>
    <uni-file-picker :fileMediatype="'image'" :disable-preview="disablePreview" :auto-upload="autoUpload" :limit="limit"
      :mode="mode" :title="title" v-model="fileList" @progress="progress" @select="select" :listStyles="listStyles"
      :imageStyles="imageStyles" ref="img" @click="upload">
    </uni-file-picker>
    <self-upload :action="uploadImgUrl" :fileMediatype="'image'" :disable-preview="disablePreview"
      :auto-upload="autoUpload" :limit="limit" :mode="mode" :title="title" :on-self-progress="progress"
      :on-self-success="success" :listStyles="listStyles" :imageStyles="imageStyles" ref="selfUpload"
      @selfUploadClick="upload" :headers="headers" :baseUrl="baseUrl" name="file"></self-upload>
  </view>
</template>

<script>
import config from "@/config";
import { getToken } from "@/utils/auth";
import SelfUpload from "./upload";

export default {
  name: "ImageUpload",
  components: { SelfUpload },
  props: {
    // #ifdef VUE3
    modelValue: {
      type: [Array, Object, String],
      default() {
        return [];
      },
    },
    // #endif

    // #ifndef VUE3
    value: {
      type: [Array, Object, String],
      default() {
        return [];
      },
    },
    // #endif

    disabled: {
      type: Boolean,
      default: false,
    },
    disablePreview: {
      type: Boolean,
      default: false,
    },
    delIcon: {
      type: Boolean,
      default: true,
    },
    // 自动上传
    autoUpload: {
      type: Boolean,
      default: true,
    },
    // 最大选择个数 ，h5只能限制单选或是多选
    limit: {
      type: [Number, String],
      default: 9,
    },
    // 列表样式 grid | list | list-card
    mode: {
      type: String,
      default: "grid",
    },
    title: {
      type: String,
      default: "",
    },
    listStyles: {
      type: Object,
      default() {
        return {
          // 是否显示边框
          border: true,
          // 是否显示分隔线
          dividline: true,
          // 线条样式
          borderStyle: {},
        };
      },
    },
    imageStyles: {
      type: Object,
      default() {
        return {
          width: "auto",
          height: "auto",
        };
      },
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    returnType: {
      type: String,
      default: "array",
    },
    sizeType: {
      type: Array,
      default() {
        return ["original", "compressed"];
      },
    },
    onStart: Function,
    onProgress: Function,
    onSuccess: Function,
    onError: Function,
    withCredentials: Boolean,
    data: Object,
  },
  data() {
    return {
      form: {},
      businessLicenseUrl: [],
      imgListModel: [],
      baseUrl: config.baseUrl,
      uploadImgUrl: config.baseUrl + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: getToken(),
      },
      reqs: {},
      mouseover: false,
      fileList: [],
      uploadList: [],
      number: 0,
      vModelList: [],
      uploadStringList: [],
    };
  },
  computed: {},
  methods: {
    select(tempFiles) {
      let businessLicenseUrl = [];
      businessLicenseUrl.push(tempFiles.tempFilePaths);
      this.form.businessLicenseUrl = businessLicenseUrl;
      this.businessLicenseUrl = {
        name: businessLicenseUrl,
        extname: businessLicenseUrl,
        url: businessLicenseUrl,
      };
      this.$refs.selfUpload.$emit("selfUploadFiles", tempFiles.tempFiles[0]);
      this.number++;
    },
    progress(progress, tempFiles) { },
    setValue(newVal, oldVal) {
      console.log(config.appInfo.site_url);
      console.log(process.env.MY_TEST)
      console.log(process.env)
      return {
        name: newVal,
        extname: newVal.split(".")[newVal.split(".").length - 1],
        // url: config.appInfo.site_url + config.baseUrl + newVal,
        url: process.env.NODE_ENV === "development" ? config.baseUrl + newVal : config.appInfo.site_url + config.baseUrl + newVal,
      };
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url.replace(this.baseUrl, "") + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
    success(res) {
      console.log(res);
      // this.uploadList.push({ name: res.fileName, url: res.fileName });
      this.uploadList.push(this.setValue(res.fileName));
      console.log(this.setValue(res.fileName))
      this.uploadStringList.push(res.fileName);
      if (this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.vModelList = this.vModelList.concat(this.uploadStringList);
        this.uploadList = [];
        this.uploadStringList = [];
        this.number = 0;
        this.$emit("input", this.vModelList);
      }
    },
  },
  watch: {
    // #ifndef VUE3
    value: {
      handler(newVal, oldVal) {
        const _this = this;
        _this.fileList = [];
        if (!(newVal === oldVal)) {
          if (Array.isArray(newVal)) {
            newVal.forEach((element) => {
              _this.fileList.push(_this.setValue(element, oldVal));
            });
          } else {
            try {
              let value = JSON.parse(newVal);
              if (Array.isArray(newVal)) {
                value.forEach((element) => {
                  _this.fileList.push(_this.setValue(element, oldVal));
                });
              } else {
                _this.fileList.push(_this.setValue(newVal, oldVal));
              }
            } catch (err) {
              if (Array.isArray(newVal)) {
                value.forEach((element) => {
                  _this.fileList.push(_this.setValue(element, oldVal));
                });
              } else {
                _this.fileList.push(_this.setValue(newVal, oldVal));
              }
            }
          }
        }
      },
      immediate: true,
    },
    // #endif
    // #ifndef VUE3
    modelValue: {
      handler(newVal, oldVal) {
        const _this = this;
        _this.fileList = [];
        if (!(newVal === oldVal)) {
          if (Array.isArray(newVal)) {
            newVal.forEach((element) => {
              _this.fileList.push(_this.setValue(element, oldVal));
            });
          } else {
            try {
              let value = JSON.parse(newVal);
              if (Array.isArray(newVal)) {
                value.forEach((element) => {
                  _this.fileList.push(_this.setValue(element, oldVal));
                });
              } else {
                _this.fileList.push(_this.setValue(newVal, oldVal));
              }
            } catch (err) {
              if (Array.isArray(newVal)) {
                value.forEach((element) => {
                  _this.fileList.push(_this.setValue(element, oldVal));
                });
              } else {
                _this.fileList.push(_this.setValue(newVal, oldVal));
              }
            }
          }
        }
      },
      immediate: true,
    },
    // #endif
  },

  created() { },

  // 组件周期函数--监听组件挂载完毕
  mounted() { },
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() { },
  // 组件周期函数--监听组件数据更新之后
  updated() { },
  // 组件周期函数--监听组件激活(显示)
  activated() { },
  // 组件周期函数--监听组件停用(隐藏)
  deactivated() { },
  // 组件周期函数--监听组件销毁之前
  beforeDestroy() { },
};
</script>

<style lang="sass" scoped></style>