<template>
  <div class="pl-upload-container" :id="divId">
    <el-upload drag v-loading="loading" element-loading-text="正在上传，请稍等..."
               :file-list="fileList"
               :show-file-list="false"
               :action="uploadUrl"
               :on-success="onSuccess"
               :on-exceed="onExceed"
               :on-change="onChange"
               :http-request="uploadFileMethod"
               :accept="acceptFileType"
               :limit="limit"
               :auto-upload="false"
               ref="componentsRef"
               multiple
               style="width:100%;"
               v-if="!isDisabled && !isView">
      <div v-if="!isView">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </div>
    </el-upload>
    <div v-if="isView && fileList.length == 0" class="el-upload__text">
      <el-tag type="info">未上传附件</el-tag>
    </div>

    <div class="pl-flie-list" id="viewer-selection" v-viewer>
      <div class="pl-file-list-item" v-for="file in fileList" :title="file.name">
        <div class="pl-file-list-item-img">
          <img :src="file.url" :onerror="defaultImg"/>
        </div>
        <div class="pl-file-list-item-text">
          {{ file.name }}
        </div>
        <div class="pl-file-list-item-btn pos-abs-full">
          <div class="top-btn" @click.stop="tempRemove(file)" v-if="!isDisabled && !isView">
            <i class="el-icon-close btn-close" title="删除"></i>
          </div>
          <div class="center-btn">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import uploadImg from "./uploadImg";
import uploadMinxins from "./mixin/uploadMixin"

export default {
  name: "pl-components-upload-new",
  mixins:[uploadMinxins],
  props: {

  },
  data() {
    return {

    }
  },

  watch: {

  },

  methods: {
    /*
    ** 初始化上传文件信息列表
    */
    initFiles() {
      let vm = this;
      let fileListDom = window.document.querySelector("#" + this.divId + ".el-upload-list");
      if (fileListDom) {
        fileListDom.innerHTML = "";
      }
      let compId= this.fkId;
      this.axios.post(vm.api.plFormCss.getById,{id:compId}).then(res => {
          let fileName = "";
          let result = res.data || {};
          fileName = result.fileName || "";
          if(fileName){
              let file = {};
              file.url = uploadImg["compress.png"];
              file.name = fileName;
              vm.fileList = [file];
          }else{
              vm.fileList = [];
          }
      })
    },
    /*
        ** 附件上传成功后调用
        */
    onSuccess() {
      this.$refs[this.systemSkinForm].clearValidate('customFile');
      this.$message("附件上传成功");
      this.initFiles();
    },
    /*
    ** 复写原来的上传方法，去除原生的OPTIONS预检请求，
    ** 系统不支持OPTIONS请求
    */
    uploadFileMethod(item) {
      let vm = this;
      if (!vm.beforeUpload(item.file)) {
        return;
      }
      let formData = new FormData();
      formData.append("file", item.file);
      formData.append("fkId", vm.fileFkId);
      formData.append("extraPath", this.extraPath);
      //创建axios实例
      vm.axios.defaults.headers = null;
      const axiosInstance = vm.axios.create({
        baseURL: vm.uploadUrl,
        headers: {
          'Content-Type': 'multipart/form-data',
          // Authorization: (this.USER_GLOBAL.getLoginToken() || "")
        },
        transformRequest: [
          function (data) {
            return data;
          }
        ],
      });

      vm.loading = true;
      //上传文件
      axiosInstance.post(vm.api.plFormCss.uploadCss, formData).then(function (res) {
        vm.axios.defaults.headers = {
          'Content-Type': 'application/x-www-form-urlencoded',
          common: {
            Authorization: (localStorage["Authorization" + (window.projectSuffix || "")] || ""),
            a: 1,
            b: 2,
            abc: 123
          }
        };

        if (res.data && typeof res.data == "object" && !res.data.operateSuccess && !res.data.upload) {
          vm.$message.error(res.data.message);
        } else {
          vm.uploadFileRecord && vm.uploadFileRecord(vm.field, "add", item.file.name);
        }

        vm.loading = false;
        vm.initFiles();
      }).catch(function (thrown) {
        vm.axios.defaults.headers = {
          'Content-Type': 'application/x-www-form-urlencoded',
          common: {
            Authorization: (localStorage["Authorization" + (window.projectSuffix || "")] || ""),
            a: 1,
            b: 2,
            abc: 123
          }
        };
      });
    },

    onChange(file, fileList){
        let fileTmp = {};
        if(fileList.length > 0){
            fileTmp.url = uploadImg["compress.png"];
            fileTmp.name = file.name;
            this.fileList = [fileTmp];
        }else{
            this.fileList = [];
        }
        this.$nextTick(() => {
            this.$refs.componentsRef.fileList.forEach(item => {
                item.status = 'ready';
                item.name = file.name;
                item.percentage = file.percentage;
                item.raw = file.raw;
                item.size = file.size;
                item.uid = file.uid;
            })
        })
    },

    /**
     * 临时删除
     */
    tempRemove(file) {
      if (!this.fileTypeValid) {
        this.fileTypeValid = true;
        return;
      }
      if (!this.ifTempRemove) {
        this.remove(file);
      } else {
        this.$confirm('是否确定删除此附件?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
            this.tempRemoveFile.push(file.id);
            this.fileList = [];
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },

    /*
    ** 文件删除
    */
    remove(file) {
      let vm = this;
      // beforeUpload上传时验证失败不触发这里的删除方法
      if (!vm.fileTypeValid) {
        vm.fileTypeValid = true;
        return;
      }
      vm.$confirm('是否确定删除此附件?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(function () {
        vm.axios.post(vm.api.plFormComponents.url + "/delete", {"ids": file.id}).then(function () {
          vm.$message("附件删除成功！");
          vm.initFiles();
        });
      }).catch(function () {
        vm.$message({
          type: 'info',
          message: '已取消删除'
        });
        vm.initFiles();
      });
    }

  }
}
</script>

<style scoped lang="scss">
.pl-upload-container {

  .pl-flie-list {
    text-align: left;

    .pl-file-list-item {
      vertical-align: top;
      display: inline-block;
      width: 135px;
      height: 135px;
      margin-right: 8px;
      margin-top: 8px;
      border-radius: 2px;
      border: 1px solid #c0ccda;
      cursor: pointer;
      transition: all 0.3s;
      position: relative;

      .pl-file-list-item-btn {
        display: none;
        transition: all 0.3s;
        background: rgba(0, 0, 0, 0.2);

        .top-btn {
          position: absolute;
          top: 0;
          right: 5px;
          text-align: right;

          .btn-close {
            color: black;

            &:hover {
              color: red;
            }
          }
        }

        .center-btn {
          display: inline-block;
          text-align: center;
          width: 100%;
          vertical-align: middle;

          ::v-deep {
            .el-button {
              margin: 5px;
            }
          }
        }

        &:after {
          content: "";
          display: inline-block;
          height: 100%;
          vertical-align: middle;
        }
      }

      &:hover {
        .pl-file-list-item-btn {
          display: block;
        }
      }

      .pl-file-list-item-img {
        /*width: 70px;*/
        height: 70px;
        margin: 14px 31.5px 0 31.5px;

        img {
          width: 70px;
          height: 70px;
        }
      }

      .pl-file-list-item-text {
        margin: 8px 4px;
        text-align: center;
        text-overflow: ellipsis;
        width: 125px;
        white-space: nowrap;
        overflow: hidden;
      }
    }
  }

  .upload-menu {
    position: absolute;
    display: inline-block;

    .menu-li {
      float: left;
      height: 25px;
      line-height: 25px;
      text-align: center;
      font-size: 12px;
      padding-right: 3px;
      cursor: pointer;

      &:hover {
        color: #00AFE4;
      }
    }
  }
}

.upload-info-message {
  color: red;
}

.pl-upload-temp-dialog {
  width: 0;
  height: 0;
}

/* 修改音/视频dialog样式 */
::v-deep .pl-audiovisual-dialog {
  background-color: #000;

  .el-dialog__headerbtn {
    font-size: 25px;
    top: 0;
    right: 0;
    width: 30px;
    height: 30px;
    z-index: 99;
    .el-dialog__close{
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      &:hover{
        color: red;
      }
    }
  }

  .el-dialog__header {
    padding: 0;
    border-bottom:none;
  }

  .el-dialog__body {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0;
    background-color: #000;
  }
}

::v-deep .el-upload-list--picture a.el-upload-list__item-name {
  width: 125px;
  display: inline-block;
  margin: 10px 4px;
  padding: 0px;
  text-align: center;
  vertical-align: middle;
  line-height: 19px;
  cursor: pointer;
}

::v-deep .el-upload-list--picture li.el-upload-list__item {
  height: 135px;
  width: 135px;
  padding: 0px;
  float: left;
  margin-right: 10px;
}

::v-deep .el-upload-list--picture .el-upload-list__item-name i {
  display: none;
}

::v-deep .el-upload-list--picture .el-upload-list__item-thumbnail {
  position: inherit;
  margin: 14px 31.5px 0 31.5px;
  cursor: pointer;
}

::v-deep li.el-list-enter-to, ::v-deep li.el-list-leave-to, ::v-deep li.el-list-enter-active, ::v-deep li.el-list-leave-active {
  transition: none;
}
</style>

<style>
.pl-upload-container .el-upload, .pl-upload-container .el-upload-dragger {
  width: 100%;
}
</style>
