<template>
  <div class="edit-image">
    <el-form
      ref="modalFormComp"
      :key="modalForm.id"
      :model="modalForm"
      label-width="100px"
    >
      <el-form-item label="边框颜色：">
        <color-select v-model="modalForm.borderColor" show-empty></color-select>
      </el-form-item>
      <el-form-item label="边框线形：">
        <line-style-select v-model="modalForm.borderStyle"></line-style-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addImage">插入图片</el-button>
        <input
          ref="fileInput"
          type="file"
          style="display: none"
          accept=".jpeg,.jpg,.png"
          @change="imageChange"
        />
      </el-form-item>
      <div style="text-align: center">
        <img v-if="imageSrc" style="width: 150px" :src="imageSrc" alt="图片" />
      </div>
    </el-form>
  </div>
</template>

<script>
import ColorSelect from "../../components/common/ColorSelect";
import LineStyleSelect from "../../components/common/LineStyleSelect";

const initModalForm = {
  id: "",
  borderColor: "",
  borderStyle: "",
  content: [],
};

export default {
  name: "EditImage",
  components: { ColorSelect, LineStyleSelect },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      imageSrc: "",
      modalForm: { ...initModalForm },
    };
  },
  mounted() {
    this.initData(this.instance);
  },
  methods: {
    initData(val) {
      this.modalForm = { ...val };
      const content = val.content && val.content[0] && val.content[0].content;
      this.imageSrc =
        content && content.indexOf("base64") !== -1 ? content : "";
    },
    addImage() {
      this.$refs.fileInput.click();
    },
    imageChange(e) {
      const file = e.target.files[0];
      if (file.size > 100 * 1024) {
        this.$message.error("图片大小不要超过100kb");
        return;
      }
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        this.modalForm.content = [
          {
            type: "text",
            content: e.target.result,
          },
        ];
        this.imageSrc = e.target.result;
        this.$refs.fileInput.value = null;
      };
    },
    submit() {
      this.$emit("modified", this.modalForm);
    },
  },
};
</script>
