<template>
  <div>
    <div class="demo-upload-list" :key="'d'+index" v-for="(item,index) in ups">
      <template v-if="item.status === 'finished'">
        <img :src="item.url">
        <div class="demo-upload-list-cover">
          <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
          <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
        </div>
      </template>
      <template v-else>
        <Progress v-if="item.showProgress" :percent="50" hide-info></Progress>
      </template>
    </div>
    <Upload
      ref="upload"
      :data="d"
      :show-upload-list="false"
      :on-success="handleSuccess"
      :format="['jpg','jpeg','png']"
      :max-size="2048"
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
      :before-upload="handleBeforeUpload"
      multiple
      type="drag"
      :action="action"
      style="display: inline-block;width:58px;"
    >
      <div style="width: 58px;height:58px;line-height: 58px;">
        <Icon type="ios-camera" size="20"></Icon>
      </div>
    </Upload>
    <Modal title="View Image" v-model="visible">
      <img :src="imgName" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>

<script>
import { ossConfig } from "@/api/meta";
export default {
  name: "uploads",
  components: {},
  props: ["value"],
  model: {
    prop: "value",
    event: "change"
  },
  data() {
    return {
      imgName: "",
      visible: false,
      uploadList: [],
      result: this.value,
      d: {},
      action: ""
    };
  },
  methods: {
    loadXML(xmlString) {
      var xmlDoc = null;
      if (!window.DOMParser && window.ActiveXObject) {
        var xmlDomVersions = [
          "MSXML.2.DOMDocument.6.0",
          "MSXML.2.DOMDocument.3.0",
          "Microsoft.XMLDOM"
        ];
        for (var i = 0; i < xmlDomVersions.length; i++) {
          try {
            xmlDoc = new ActiveXObject(xmlDomVersions[i]);
            xmlDoc.async = false;
            xmlDoc.loadXML(xmlString);
            break;
          } catch (e) {}
        }
      } else if (
        window.DOMParser &&
        document.implementation &&
        document.implementation.createDocument
      ) {
        try {
          var domParser = new DOMParser();
          xmlDoc = domParser.parseFromString(xmlString, "text/xml");
        } catch (e) {
          console.log(e);
        }
      } else {
        return null;
      }
      return xmlDoc;
    },
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      //to do --添加修改时已经有逻辑，fileList中没有
      const fileList = this.uploadList;
      this.uploadList.splice(fileList.indexOf(file), 1);
      let cresults= this.result.split(",")
      let cs =cresults.filter(r=>{
        return r!=file.url
      })
     this.result=cs.join(",")
     this.$emit('change',this.result)
    },
    handleSuccess(res, file, fileList) {
      // var xml= this.loadXML(res);
      //  this.result=xml.documentElement.getElementsByTagName("Location")[0].textContent;
      //解析filelist,构造逗号分隔的文件列表
      console.log("/////////////////////////////////////////",fileList);
      let mps = fileList.map(item => {
        if (item.status == "finished") {
          if (item.response) {
            let xml = this.loadXML(item.response);
            let tmp = xml.documentElement.getElementsByTagName("Location")[0]
              .textContent;
            return tmp;
          }
        }
      });
      mps.push(this.result);
      this.result = mps.join(",");
      this.$emit("change", this.result);
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "The file format is incorrect",
        desc:
          "File format of " +
          file.name +
          " is incorrect, please select jpg or png."
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "Exceeding file size limit",
        desc: "File  " + file.name + " is too large, no more than 2M."
      });
    },
    handleBeforeUpload(file) {
      const check = this.uploadList.length < 5;
      if (!check) {
        this.$Notice.warning({
          title: "Up to five pictures can be uploaded."
        });
      }
      // this.result = "";
      var myDate = new Date();
      var key =
        "zc_" +
        Math.round(Math.random() * 500) +
        myDate.getMonth() +
        myDate.getTime() +
        myDate.getFullYear() +
        myDate.getDate() +
        myDate.getHours() +
        myDate.getMinutes() +
        myDate.getSeconds() +
        myDate.getMilliseconds() +
        file.name.replace(" ", "");
      this.d.key = key;
      return check;
    }
  },
  created() {},
  computed: {
    ups() {
      let tmpary = [];
      let ti = this.uploadList.map(item => {
        console.log(item);
        if (item.status == "finished" && item.response) {
          var xml = this.loadXML(item.response);
          let tmplink = xml.documentElement.getElementsByTagName("Location")[0]
            .textContent;
          return { name: item.name, url: tmplink, status: item.status };
        } else {
          return item;
        }
      });
      let t = tmpary.concat(ti);
      return t;
    }
  },
  mounted() {
    let url = "/api/meta/oss/getOssConfig";
    ossConfig(url, null).then(res => {
      let rtn = res.data;
      if (rtn.status == 0) {
        let data = rtn.data;
        this.d["key"] = "key";
        this.d["Bucket"] = data.Bucket;
        this.d["OSSAccessKeyId"] = data.OSSAccessKeyId;
        this.d["Signature"] = data.Signature;
        this.d["policy"] = data.policy;
        this.d["success_action_status"] = data.success_action_status;
        this.action = data.url;
      } else {
        console.log("cofig fetch failuer");
      }
    });
    this.$refs.upload.fileList = [];
    this.uploadList = this.$refs.upload.fileList;
  },
  watch: {
    value: function(v) {
      this.result = v;
      //打开窗口，给vaue属性赋予值
      this.$refs.upload.fileList = [];
      if (this.result && this.result!="") {
        console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.");
        let i = 10;
        this.result.split(",").forEach(item => {
          let sb = this.uploadList.some(s => {
            if (s.url) {
              return s.url == item;
            }
          });
          if (!sb) {
            this.uploadList.push({ name: i++, url: item, status: "finished" });
          }
        });
      }else{
           this.uploadList=[]
      }
   
    }
  }
};
</script>
<style>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
