<template>
  <div>
    <Modal
      ref="dialog"
      v-model="isShow"
      title="图集"
      :footer-hide="true"
    >
      <el-upload
        style="width: 400px"
        ref="upload"
        multiple
        :headers="{
             Authorization: `Bearer ${getToken()}`,
        }"
        :on-success="successHandle"
        :before-upload="uploadBefore"
        :before-remove="beforeRemove"
        accept=".jpg,.png,.gif"
        :action="action"
        :file-list="fileList"
        :on-remove="removeHande"
        :limit="100"
        list-type="picture"
      >
        <el-button slot="trigger" size="small" type="primary"
        >选取文件</el-button
        >
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png/gif文件，
          <br />单个文件不能超过50M
        </div>
      </el-upload>

    </Modal>
  </div>
</template>

<script>
import { save, index, destroy } from "@/api/system/baseForm";
import { getToken } from '@/utils/auth'
export default {
  props: {},
  data() {
    return {
      isShow: false,
      id: "",
      type: "",
      action: process.env.VUE_APP_UPLOAD_API,
      fileList: [],

      form: {
        file: []
      },
      rules: {
        name: [
          {
            required: true,
            message: "请填写名称",
          },
        ],
        upload_id: [
          {
            validator: (rule, value, callback) => {
              if (this.fileList.length > 0) {
                callback();
              } else {
                callback(new Error("请上传文件"));
              }
            },
            message: "请上传文件",
          },
        ],
      },
    };
  },
  methods: {
    getToken,
    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    init() {
      this.form = {
        name: "",
        upload_id: "",
        model_id: "",
        model_type: "customer",
      };
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },
    getId() {
      return this.id;
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this.form[key] = value;
      }
      if (!key) {
        this.init();
      }
    },

    //上传
    successHandle(response, file, fileList) {
      this.fileList = fileList;

      this.submit(response);
    },
    removeHande(file, fileList) {
      this.fileList = fileList;
    },
    uploadBefore(file) {
      console.log(file);
      if (file.size / 1000 > 50 * 1024) {
        this.$message({
          type: "warning",
          message: "上传图片大小超过50M！",
        });
        return false;
      }
    },
    beforeRemove(file,fileList){
      return this.$confirm('确认要删除吗？').then(res => {
        destroy({
          table_name: 'assets_atlas_files',
          id: file.response.id
        }).then(_ => true).catch(_ => false)
      })
    },

    async getDetail() {
      const res = await index({
        table_name: 'assets_atlas_files',
        page: 1,
        page_size: 999,
        filter: [
          {
            key: /\/land/g.test(this.$route.path) ? 'land_id' : 'house_id',
            op: 'eq',
            value: this.id
          }
        ]
      });
      this.fileList = res.data.map((item) => {
        return {
          name: item.original_name,
          url: item.url,
          response: item,
        };
      });
      this.$integrateData(this.form, res);
    },

    submit(response) {
      save({
        table_name: 'assets_atlas_files',
        file_id: response.id,
        [/\/land/g.test(this.$route.path) ? 'land_id' : 'house_id']: this.id,
        name: response.name,
        original_name: response.original_name,
        //TODO: 待修改
        url: response.url.replace(/:\/\/:\/\//g,'://')
      }).then(res => {
        this.$message({
          type: 'success',
          message: '图集上传成功'
        })
      })
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        this.getDetail();
      } else {
        this.id = "";
        this.type = "";
        this.fileList = [];
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}

.img__delete {
  transform: scale(0.8, 0.8);

  position: absolute;
  top: 4px;
  right: 4px;
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: $primaryColor;
}

::v-deep .el-upload--picture-card {
  font-size: 28px;
  color: #8c939d;
  width: 80px !important;
  height: 80px !important;
  line-height: 80px !important;
  text-align: center;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px !important;
  height: 80px !important;
  line-height: 80px !important;
  text-align: center;
}

::v-deep .avatar {
  width: 80px !important;
  display: block;
  border-radius: 6px;
}

::v-deep .el-input__inner {
  text-align: left;
}
</style>
