<template>
  <el-form-item
    class="image-item"
    :label="label"
    :rules="requireRule(required, label)"
    :prop="prop"
  >
    <el-upload
      action=""
      :fileList="fileList"
      :httpRequest="httpRequest"
      :onChange="handleChange"
      :onRemove="handleRemove"
      :on-preview="handlePictureCardPreview"
      :class="{ 'is-disabled': fileList.length >= limit || disabled }"
      listType="picture-card"
      :multiple="false"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </el-form-item>
</template>

<script>
import mixin from "./mixin";
// import {uploadImage} from '@/api/system/common'
import { join } from "lodash";

// 通过字符串获取文件列表
const extractFiles = (value) => {
  if (!value || value.trim() === "") {
    return [];
  }
  return value.split(",").map((url) => ({ uid: url, url, status: "success" }));
};
// 将图片路径合并到一个字符串
const extractUrls = (fileList) => {
  return join(
    fileList.map((file) => file.url),
    ","
  );
};

/**
 * 图片选择组件
 */
export default {
  mixins: [mixin],
  props: {
    limit: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      fileList: extractFiles(),
      dialogVisible: false,
      dialogImageUrl: "",
    };
  },
  created() {
    this.$watch(
      () => this.$parent.model[this.prop],
      (value, oldValue) => {
        if (value && !oldValue) {
          this.fileList = extractFiles(value);
        }
      },
      { immediate: true }
    );
  },
  methods: {
    httpRequest({ file }) {
      const prom = new Promise((resolve, reject) => {
        uploadImage(file).then((res) => {
          const { code, url } = res;
          let target = null;
          for (let i = 0; i < this.fileList.length; i++) {
            const element = this.fileList[i];
            if (element.uid === file.uid) {
              target = i;
              break;
            }
          }
          if (target === null) {
            this.$message.error("文件上传异常");
            return;
          }

          if (code === 200) {
            this.fileList[target].url = url;
          } else {
            this.fileList.splice(target, 1);
            this.$message.error("上传失败, 请重新上传");
          }
          this.$parent.model[this.prop] = extractUrls(this.fileList);
          resolve();
        });
      });
      prom.abort = () => {};
      return prom;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.$parent.model[this.prop] = extractUrls(this.fileList);
      setTimeout(() => this.$parent.validateField(this.prop), 500);
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      setTimeout(() => this.$parent.validateField(this.prop), 500);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>

<style>
.image-item .is-disabled .el-upload--picture-card {
  display: none !important;
}
.image-item {
  height: auto;
  min-height: 146px;
}
.image-item .el-upload-list__item {
  transition: none !important;
}
</style>
