<template>
  <div class="comModule-main" v-loading="loading">
    <div class="comModule-title" style="margin: 20px 0 0 0">
      <b>在线回复</b>
      <el-button
        class="fr"
        style="margin: 9px 0 0 16px"
        type="primary"
        :size="'mini'"
        @click="submitForm"
        >提交</el-button
      >
      <el-button
        class="fr"
        style="margin: 9px 0 0 0px"
        plain
        :size="'mini'"
        @click="$refs.txt1.innerHTML = ''"
        >重置</el-button
      >
    </div>
    <div class="comModule">
      <div
        class="comment"
        ref="txt1"
        id="txt1"
        v-html="input"
        :contenteditable="true"
        @paste="handlePaste"
        contenteditable
        placeholder="请输入回复： Ctrl+V可粘贴截图 "
      ></div>
    </div>
  </div>
</template>
<script>
import resToken from "@/mixins/resToken";
import urlConfig from "@/apis/url-config";
import { getToken } from "@/utils/auth";
import asyncRequest from "@/apis/service/purchaseAndSale/adjust";
export default {
  name: "comModule",
  mixins: [resToken],
  props: ["id", "value", "bugNo"],
  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;height:40px;' name='${name}' src='${url}'/>${right}`;
      }
    },

    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() {
      if (!this.loading) {
        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;
          }
          await this.plunsubmit({
            id: this.id,
            input: str,
          });
        } else {
          this.$message.warning("评论内容不能为空");
          this.loading = false;
        }
      }
    },
    async plunsubmit({ id, input }) {
      let model = {
        id,
        talk_note: input,
        bugNo: this.bugNo,
      };
      let res = {};
      if (id === "add") {
        delete model["id"];
        res = await asyncRequest.comAdd(model);
      } else {
        res = await asyncRequest.comUpdate(model);
      }
      this.loading = false;
      const { code, message } = res;
      if (code === 0) {
        this.$notify.success({
          title: id === "add" ? "回复添加成功！" : "回复修改成功！",
          message: "",
        });
        this.$refs.txt1.innerHTML = "";
        this.$emit("submit");
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.comModule-title {
  width: 100%;
  padding: 0 20px;
  height: 40px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  line-height: 40px;
  font-weight: bold;
  display: inline-block;
  list-style: none;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  position: relative;

  margin: 0 0 20px 0;
}
.comModule {
  .comment {
    width: 100%;
    border: 1px solid #eee;
    min-height: 300px;
    max-height: 300px;
    padding: 12px 16px;
    line-height: 28px;
    font-size: 13px;
    overflow-y: scroll;
    overflow-x: hidden;
    &:empty::before {
      content: attr(placeholder);
      color: #aaa;
      font-size: 13px;
    }
    /deep/ img {
      display: inline-block;
      max-width: 100%;
      height: 50px;
    }
  }
}
</style>
