<template>
  <div class="app-container">
    <div class="title">用户协议</div>
    <el-form ref="mainForm" label-width="80px" label-position="top">
      <el-form-item label="" prop="content1">
        <el-upload
          ref="imageListUpload1"
          class="avatar-uploader1"
          :action="baseURL + 'common/upload'"
          :headers="myHeaders"
          multiple
          name="file"
          :show-file-list="false"
          :on-success="uploadSuccess1"
          :on-error="uploadError1"
          :before-upload="beforeUpload1"
        >
        </el-upload>
        <!--富文本编辑器组件-->
        <el-row v-loading="quillImgLoading1">
          <quill-editor
            v-model="mainForm.content1"
            ref="myQuillEditor1"
            :options="editorOption1"
          >
          </quill-editor>
        </el-row>
      </el-form-item>
    </el-form>

    <div class="title">隐私声明</div>
    <el-form ref="mainForm" label-width="80px" label-position="top">
      <el-form-item label="" prop="content2">
        <el-upload
          ref="imageListUpload2"
          class="avatar-uploader2"
          :action="baseURL + 'common/upload'"
          :headers="myHeaders"
          multiple
          name="file"
          :show-file-list="false"
          :on-success="uploadSuccess2"
          :on-error="uploadError2"
          :before-upload="beforeUpload2"
        >
        </el-upload>
        <!--富文本编辑器组件-->
        <el-row v-loading="quillImgLoading2">
          <quill-editor
            v-model="mainForm.content2"
            ref="myQuillEditor2"
            :options="editorOption2"
          >
          </quill-editor>
        </el-row>
      </el-form-item>
    </el-form>

    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button type="primary" @click="submitForm" :loading="formLoading">{{
          formLoading ? "保存中 ..." : "保 存"
        }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getAgreement, editAgreement } from "@/api/setting";
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"],
  ["blockquote", "code-block"],
  [{ header: 1 }, { header: 2 }],
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }],
  [{ indent: "-1" }, { indent: "+1" }],
  [{ direction: "rtl" }],
  [{ size: ["small", false, "large", "huge"] }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }],
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image", "video"],
  // ['clean']
];

export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { "x-token": getToken() },

      mainForm: {
        content1: "",
        content2: "",
      },

      quillImgLoading1: false, // 富文本上传图片loading
      editorOption1: {
        // 富文本配置
        placeholder: "请输入公共内容",
        theme: "snow",
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector(".avatar-uploader1 input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      editorImages1: [],

      quillImgLoading2: false, // 富文本上传图片loading
      editorOption2: {
        // 富文本配置
        placeholder: "请输入公共内容",
        theme: "snow",
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector(".avatar-uploader2 input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      editorImages2: [],

      formLoading: false,
    };
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar;
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened,
      };
    },
  },

  created() {
    this.getAgreement();
  },

  methods: {
    // 获取详情
    getAgreement() {
      getAgreement().then((res) => {
        this.mainForm = {
          content1: res.data.userAgreementContent,
          content2: res.data.privacyStatementContent,
        };
      });
    },

    submitForm() {
      this.formLoading = true;
      editAgreement({
        companyWechatId: JSON.parse(localStorage.getItem("greemall_user"))
          .companyWechatId,
        userAgreementContent: this.mainForm.content1,
        privacyStatementContent: this.mainForm.content2,
      })
        .then((res) => {
          this.formLoading = false;
          this.$successMsg("编辑成功");
          setTimeout(() => {
            this.getAgreement();
          }, 1000);
        })
        .catch((err) => {
          this.formLoading = false;
        });
    },

    // 富文本图片上传前
    beforeUpload1() {
      this.quillImgLoading1 = true;
    },

    // 富文本图片上传成功
    uploadSuccess1(res, file, fileList) {
      console.log(fileList);
      fileList.forEach((item) => {
        if (this.editorImages1.indexOf(item.response.data.url) < 0) {
          this.editorImages1.push(item.response.data.url);
        }
      });
      this.showImage1();
      this.quillImgLoading1 = false;
    },

    showImage1() {
      console.log(this.editorImages1);
      let quill = this.$refs.myQuillEditor1.quill;
      this.editorImages1.forEach((item) => {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        console.log(item);
        quill.insertEmbed(length, "image", item);
        // this.$refs.imageListUpload1.clearFiles()
        // 调整光标到最后
        quill.setSelection(length + 1);
      });
      this.editorImages1 = [];
      this.$refs.imageListUpload1.clearFiles();
    },

    // 富文本图片上传失败
    uploadError1() {
      this.quillImgLoading1 = false;
      this.$errorMsg("图片插入失败");
    },

    // 富文本图片上传前
    beforeUpload2() {
      this.quillImgLoading2 = true;
    },

    // 富文本图片上传成功
    uploadSuccess2(res, file, fileList) {
      console.log(fileList);
      fileList.forEach((item) => {
        if (this.editorImages2.indexOf(item.response.data.url) < 0) {
          this.editorImages2.push(item.response.data.url);
        }
      });
      this.showImage2();
      this.quillImgLoading2 = false;
    },

    showImage2() {
      console.log(this.editorImages2);
      let quill = this.$refs.myQuillEditor2.quill;
      this.editorImages2.forEach((item) => {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        console.log(item);
        quill.insertEmbed(length, "image", item);
        // this.$refs.imageListUpload2.clearFiles()
        // 调整光标到最后
        quill.setSelection(length + 1);
      });
      this.editorImages2 = [];
      this.$refs.imageListUpload2.clearFiles();
    },

    // 富文本图片上传失败
    uploadError2() {
      this.quillImgLoading2 = false;
      this.$errorMsg("图片插入失败");
    },
  },
};
</script>

<style lang="scss" scoped>
.title {
  font-size: 16px;
  color: #333333;
  margin-bottom: 20px;
  font-weight: 600;
}

.avatar-uploader1 {
  height: 0;
}
</style>
