<template>
  <view class="rich-editor">
    <view class="label">标题:</view>
    <u-input v-model="title" type="textarea" :border="true" />
    <view class="label">正文:</view>
    <view class="toolbar" @tap="format">
      <view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
      <view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"></view>
      <view
        :class="formats.underline ? 'ql-active' : ''"
        class="iconfont icon-zitixiahuaxian"
        data-name="underline"
      ></view>
      <view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian" data-name="strike"></view>
      <view
        :class="formats.align === 'left' ? 'ql-active' : ''"
        class="iconfont icon-zuoduiqi"
        data-name="align"
        data-value="left"
      ></view>
      <view
        :class="formats.align === 'center' ? 'ql-active' : ''"
        class="iconfont icon-juzhongduiqi"
        data-name="align"
        data-value="center"
      ></view>
      <view
        :class="formats.align === 'right' ? 'ql-active' : ''"
        class="iconfont icon-youduiqi"
        data-name="align"
        data-value="right"
      ></view>
      <view class="iconfont icon-charutupian" @tap="insertImage"></view>
      <view class="iconfont icon-shanchu" @tap="clear"></view>
    </view>
    <view class="editor-wrapper">
      <editor
        id="editor"
        class="ql-container"
        placeholder="开始输入..."
        showImgSize
        showImgToolbar
        showImgResize
        @statuschange="onStatusChange"
        :read-only="readOnly"
        @ready="onEditorReady"
        @input="getEditorContent"
      >
      </editor>
    </view>
    <u-button type="primary" @click="handleUpdatePost">确定</u-button>
  </view>
</template>

<script>
// 参考 https://github.com/dcloudio/hello-uniapp/tree/master/pages/component/editor
import { queryPostList, updatePost } from '../../cms/api';
import { Setting } from '../../index';
export default {
  data() {
    return {
      readOnly: false,
      formats: {},
      postDetail: null,
      editorContent: null,
      pid: null,
      title: null,
    };
  },
  onLoad(options) {
    this.pid = options.pid;
    uni.loadFontFace({
      family: 'Pacifico',
      source: 'url("https://sungd.github.io/Pacifico.ttf")',
    });
  },
  methods: {
    onEditorReady() {
      uni
        .createSelectorQuery()
        .select('#editor')
        .context(res => {
          this.editorCtx = res.context;
          console.log('%c [onEditorReady]: ', 'color:#1989fa;', res);
          this.getPostDetail();
        })
        .exec();
    },
    format(e) {
      let { name, value } = e.target.dataset;
      if (!name) return;
      console.log('format', name, value);
      this.editorCtx.format(name, value);
    },
    onStatusChange(e) {
      console.log('%c [onStatusChange]: ', 'color:#1989fa;', e);
      const formats = e.detail;
      this.formats = formats;
    },
    // 清空内容
    clear() {
      this.editorCtx.clear({
        success: function (res) {
          console.log('clear success');
        },
      });
    },
    // 插入图片
    insertImage() {
      uni.chooseImage({
        count: 1,
        success: res => {
          console.log('%c [insertImage]: ', 'color:#1989fa;', res);
          uni.uploadFile({
            url: Setting.getImgUploadPath(),
            filePath: res.tempFilePaths[0],
            name: 'file',
            success: uploadFileRes => {
              const url = Setting.getImgPath() + JSON.parse(uploadFileRes.data).data.path;
              this.editorCtx.insertImage({
                src: url,
                alt: url,
                success: function (res) {
                  console.log('insert image success', res);
                },
                fail: function (error) {
                  console.log('insert image fail', error);
                },
              });
            },
          });
        },
      });
    },
    // 获取编辑器内容
    getEditorContent(e) {
      console.log('%c [获取编辑器内容]: ', 'color:#1989fa;', e);
      this.editorContent = e.detail.html;
    },
    // 获取文章详情
    async getPostDetail() {
      if (!this.pid) return;
      const params = {
        query: {
          limit: 10,
          page: 0,
          keyJson: JSON.stringify({ pid: this.pid }),
        },
      };
      const ret = await queryPostList(params);
      const postDetail = ret.data[0];
      this.postDetail = postDetail;
      this.title = postDetail.content.title;
      console.log('%c [postDetail]: ', 'color:#1989fa;', postDetail.content);
      // 设置富文本编辑器的内容
      let EContent = {
        html: postDetail.content.content,
      };
      this.editorCtx.setContents(EContent);
    },
    // 修改文章
    async handleUpdatePost() {
      const params = {
        pid: this.postDetail.pid,
        content: {
          title: this.title,
          content: this.editorContent,
        },
      };
      await updatePost(params);
      uni.showToast({
        title: '修改文章成功',
      });
      uni.navigateBack({ delta: 1 });
    },
  },
};
</script>

<style lang="scss">
@import './editor-icon.css';
.rich-editor {
  height: 100vh;
  background-color: #fff;
  padding-bottom: constant(safe-area-inset-bottom); /*兼容 IOS<11.2*/
  padding-bottom: env(safe-area-inset-bottom); /*兼容 IOS>11.2*/
  .label {
    padding: 20rpx;
  }
}
.editor-wrapper {
  height: calc(100vh - 140px);
  background: #fff;
}
.toolbar {
  box-sizing: border-box;
  border-bottom: 0;
  font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
  display: flex;
  flex-direction: row;
  background-color: #f3f3f3;
  .iconfont {
    cursor: pointer;
    font-size: 20px;
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    margin: 20rpx 10rpx;
  }
}
.ql-container {
  box-sizing: border-box;
  padding: 12px 15px;
  width: 100%;
  min-height: 30vh;
  height: 100%;
  margin-top: 2rpx;
  font-size: 16px;
  line-height: 1.5;
  border-bottom: 1rpx solid #f4f4f4;
}
.ql-active {
  color: #06c;
}
button {
  margin: 20rpx;
}
</style>
