<template>
  <div class="comModule" v-loading="loading">
    <div
      class="comment"
      ref="txt1"
      id="txt1"
      v-html="input"
      :contenteditable="true"
      @paste="handlePaste"
    ></div>
    <div style="padding: 10px 0 0 0">
      <el-button type="primary" :size="'mini'" @click="submitForm"
        >提交</el-button
      >
      <el-button plain :size="'mini'" @click="$emit('cancel')">取消</el-button>
    </div>
  </div>
</template>
<script>
import resToken from "@/mixins/resToken";
import urlConfig from "@/apis/url-config";
import { getToken } from "@/utils/auth";
export default {
  name: "comModule",

  mixins: [resToken],
  props: ["id", "value"],
  data() {
    return {
      imgAPI: urlConfig.baseURL,
      inputEdit: false,
      input: "",
      isChange: true,
      loading: false,
    };
  },
  created() {
    this.input = this.value;
  },
  methods: {
    // 获取出纳粘贴图片
    async handlePaste(event) {
      event.preventDefault();
      event.stopPropagation();
      let focusOffset = 0;
      let anchorOffset = 0;
      let einput = this.$refs.txt1.innerHTML || "";
      const typeList = ["image/jpg", "image/png", "image/jpeg"];
      let len = einput.length;
      if (
        window.getSelection().focusOffset <= window.getSelection().anchorOffset
      ) {
        focusOffset = window.getSelection().focusOffset;
        anchorOffset = window.getSelection().anchorOffset;
      } else {
        focusOffset = window.getSelection().anchorOffset;
        anchorOffset = window.getSelection().focusOffset;
      }
      console.log(focusOffset, anchorOffset, len);
      let left = "",
        right = "";
      if (focusOffset !== 0) {
        left = einput.slice(0, focusOffset);
      }
      if (anchorOffset !== len) {
        right = einput.slice(anchorOffset);
      }
      const items = (event.clipboardData || window.clipboardData).items;
      let file = null;
      let findex = -1;
      if (!items || items.length === 0) {
        this.$message.error("当前浏览器不支持本地或请打开图片再复制");
        return;
      }
      for (let i = 0; i < items.length; i++) {
        if (items[i].type === "text/plain") {
          let clipboardData = event.clipboardData || window.clipboardData;
          let pastedData = clipboardData.getData("Text");
          this.input = `${left}${pastedData}${right}`;
        } else {
          findex = typeList.findIndex((v) => v == items[i].type);
          if (findex !== -1) {
            file = items[i].getAsFile();
            break;
          }
        }
      }
      if (!file) {
        return;
      }
      if (file.size / 1024 / 1024 > 3) {
        this.$message.error("图片大小不能超过 3MB!");
        return;
      }
      let res = await this.httpupLoad(file);
      if (res === "error") {
        this.$message.error("图片上传失败，请稍后重试！");
      } else if (res === "token") {
        await this.logout();
      } else {
        const { name, url } = res;
        this.input = `${left}<img style='display: inline-block;max-width: 50%;' src='${url}'/>${right}`;
      }
      // console.log(left);
      // console.log(right);
      // console.log(this.input);
    },

    async httpupLoad(file) {
      return new Promise((resolve, reject) => {
        let that = this;

        let form = new FormData();
        form.append("image", file);
        form.append("token", getToken());
        axios
          .post(`${that.imgAPI}admin/uploadimg`, form)
          .then((res) => {
            if (res && res.data && res.status === 200) {
              const { code, data } = res.data;
              if (code === 0) {
                const { url, name } = data[0];
                resolve({
                  url: `${that.imgAPI}storage/${url}`,
                  name: name,
                });
              } else if (code >= 100 && code <= 104) {
                resolve("token");
              } else {
                resolve("error");
              }
            } else {
              reject();
            }
          })
          .catch((error) => {
            reject();
          });
      });
    },
    async submitForm() {
      this.loading = true;
      let str = this.$refs.txt1.innerHTML;
      let length = 2000;
      if (str) {
        if (str.length > length) {
          this.$message.warning("评论文字及图片总长度不能超过2000！");
          this.loading = false;
          return;
        }
        this.loading = false;
        this.$emit("submit", {
          id: this.id,
          input: str,
        });
      } else {
        this.$message.warning("评论内容不能为空");
        this.loading = false;
      }
    },
  },
};
</script>

   <style lang="scss" scoped>
.comModule {
  .comment {
    width: 100%;
    border: 1px solid #eee;
    min-height: 250px;
    max-height: 250px;
    padding: 12px 16px;
    line-height: 40px;
    overflow-y: scroll;
    overflow-x: hidden;
    /deep/ img {
      display: inline-block;
      max-width: 100%;
      height: auto;
    }
  }
}
</style>
