<template>
  <div class="dsk-photo-input-container" :class="{'upload-is-disabled' : disabled}">
    <div class="dsk-photo-input-inner" @click.stop="uploadFile" v-if="!comFileList.length">
      <i class="el-icon-plus"></i>
      <span>上传图片</span>
    </div>
    <el-badge :value="comFileList.length" class="item" type="primary" v-if="comFileList.length" @click.native="showFileListDialog">
      <div class="dsk-photo-input-inner" @click.stop="uploadFile">
        <i class="el-icon-plus"></i>
        <span>上传图片</span>
      </div>
    </el-badge>
    <el-upload :on-change="handleChange" action="#" :accept="allowTypes.join(',')" :auto-upload="false" :show-file-list="false"
      ref="elUploadDskUploadIns" class="el-upload-dsk-upload-ins"></el-upload>

    <el-dialog title="已上传图片" :visible.sync="fileListDialog" width="800px" @close="fileListDialogClose" :close-on-click-modal="false"
      class="dsk-upload-photo-dialog" append-to-body>
      <el-table :data="comFileList.slice((pageInfo.currentPage -1) * pageInfo.pageSize, pageInfo.pageSize * pageInfo.currentPage)" border stripe>
        <el-table-column prop="fileName" label="图片名称"></el-table-column>
        <el-table-column prop="type" label="图片类型"></el-table-column>
        <el-table-column prop="url" label="图片地址" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span style="color:#0081ff;cursor: pointer;" @click="viewPhoto(scope.row)">{{scope.row.url}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90" v-if="!disabled">
          <template slot-scope="scope">
            <span style="color:#F56C6C;cursor: pointer;" @click="removeImg(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next" :total="comFileList.length" @current-change="currentChange"
        v-if="comFileList.length > 10"></el-pagination>
    </el-dialog>

    <el-dialog title="图片预览" :visible.sync="photoViewDialog" width="800px" @close="photoViewDialogClose" :close-on-click-modal="false"
      class="dsk-upload-view-dialog" append-to-body>
      <el-image :src="viewTemp.url" fit="fill"></el-image>
    </el-dialog>

  </div>
</template>
<script>
import { uploadFileToOssApi, removeFileFromOssApi } from "@/api/consultingOrgManagement";
import { elementMessageSingleton } from "@/utils";
import { generateRandomLowerCaseLetter } from "@/utils/";
export default {
  name: "dskPhotoInput",
  props: {
    limit: {
      type: [String, Number]
    },
    disabled: {
      type: Boolean,
      default: false
    },
    fileList: {
      type: Array,
      default: () => []
    },
    // 是否是演示模式
    presentationModel: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: "fileList",
    event: "update:fileList"
  },
  data() {
    return {
      allowTypes: [".jpg", ".png", ".svg", ".gif", ".jpeg"],
      comFileList: JSON.parse(JSON.stringify(this.fileList)),
      fileListDialog: false,
      photoViewDialog: false,
      viewTemp: {},
      pageInfo: {
        pageSize: 10,
        currentPage: 1
      }
    };
  },
  //可访问data属性
  created() {

  },
  beforeDestroy() {
    if (this.presentationModel) {
      this.comFileList.forEach(item => {
        if (item?.url?.indexOf("localhost") > -1) {
          URL.revokeObjectURL(item.url);
        }
      });
    }
  },
  //计算集
  computed: {
    limitRestrict() {
      return this.limit === -1 ? true : this.comFileList.length >= this.limit ? false : true;
    }
  },
  //方法集
  methods: {
    async handleChange(file, fileList) {
      try {
        /** 
       * @type {string}
      */
        let fileName = file.name;
        let fileType = "";
        const index = fileName.lastIndexOf(".");
        if (index) fileType = fileName.slice(index);

        if (!this.allowTypes.includes(fileType.toLowerCase())) {
          return this.$message.warning(`只支持上传${this.allowTypes.join(" , ")}类型图片`);
        }

        // 是否是演示模式
        if (this.presentationModel) {
          await this.uploadHandleLocal(file, fileType);
        } else {
          // 验证通过进行上传
          await this.uploadHandle(new File([file.raw], encodeURIComponent(fileName)), fileType);
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.$refs["elUploadDskUploadIns"].clearFiles();
      }
    },
    uploadFile() {
      // 禁用状态
      if (this.disabled) return;
      // 超出个数限制
      if (!this.limitRestrict) return elementMessageSingleton("warning", `图片限制上传${this.limit}张,已上传${this.comFileList.length}张图片`);
      this.$refs["elUploadDskUploadIns"].$el.querySelector(".el-upload__input").click();
    },
    async uploadHandle(file, fileType) {
      try {
        const formData = new FormData();
        formData.append("file", file);
        const result = await uploadFileToOssApi(formData);
        if (result.code == 200 && result.data) {
          this.comFileList.push({
            url: result.data.url,
            type: fileType,
            id: result.data.ossId,
            fileName: result.data.fileName
          });
          this.eventChange();
          this.$message.success("上传成功");
        }
      } catch (error) {

      }
    },
    async uploadHandleLocal(file, fileType) {
      try {
        const localUrl = URL.createObjectURL(file.raw);
        this.comFileList.push({
          url: localUrl,
          type: fileType,
          id: `${new Date().getTime()}${generateRandomLowerCaseLetter()}`,
          fileName: file.name
        });
        this.eventChange();
        this.$message.success("上传成功");
      } catch (error) {
        console.log(error);
      }
    },
    showFileListDialog() {
      this.fileListDialog = true;
    },
    fileListDialogClose() {
      this.pageInfo = this.$options.data.call(this).pageInfo;
    },
    viewPhoto(row) {
      this.viewTemp = row;
      this.photoViewDialog = true;
    },
    photoViewDialogClose() {
      this.viewTemp = {};
    },
    currentChange(current) {
      this.pageInfo.currentPage = current;
    },
    removeImg(row) {
      if (row.id) {
        if (this.presentationModel) {
          return this.removeLocalImg(row.id);
        }
        this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const index = this.comFileList.findIndex(item => item.id == row.id);
          if (index > -1) {
            const removeResult = await removeFileFromOssApi(row.id);
            if (removeResult.code == 200) {
              this.comFileList.splice(index, 1);
              this.eventChange(true);
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          }
        }).catch(() => { });
      }
    },
    removeLocalImg(id) {
      const index = this.comFileList.findIndex(item => item.id == id);
      if (index > -1) {
        const url = this.comFileList[index].url;
        URL.revokeObjectURL(url);
        this.comFileList.splice(index, 1);
        this.eventChange(true);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }
    },
    eventChange(isRemove = false) {
      this.$emit("update:fileList", this.comFileList);
      this.$emit("change", isRemove, this.comFileList);
    }
  },
}
</script>
<style lang="scss" scoped>
.dsk-photo-input-container {
  width: 100%;
  height: 32px;

  &.upload-is-disabled {
    .dsk-photo-input-inner {
      cursor: not-allowed;
      &:hover {
        color: rgba(35, 35, 35, 0.8);
        border-color: #dcdfe6;
      }
    }
  }

  .dsk-photo-input-inner {
    width: 106px;
    height: 32px;
    background: #ffffff;
    border: 1px solid #dcdfe6;

    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0px 16px;
    box-sizing: border-box;
    color: rgba(35, 35, 35, 0.8);
    font-size: 14px;
    font-weight: 400;
    cursor: pointer;

    &:hover {
      color: #0081ff;
      border-color: #0081ff;
    }
  }

  ::v-deep .el-upload-dsk-upload-ins {
    width: 0px;
    height: 0px;
    opacity: 0;
    position: relative;
    z-index: -999;
  }

  ::v-deep .el-badge__content {
    background: #0081ff;
    cursor: pointer;
    border-color: #0081ff;
  }
}
</style>
<style lang="scss">
.dsk-upload-photo-dialog,
.dsk-upload-view-dialog {
  @import "@/assets/styles/dsk-upload-dialog.scss";
}
</style>
