<template>
      <view class='wrapper'>
        <view class="editor-wrapper">
          <sv-editor 
						eid="editor" 
						class="ql-container" 
						placeholder="开始输入..." 
						show-img-size show-img-toolbar show-img-resize
            :read-only="readOnly" 
						@statuschange="onStatusChange" 
						pasteMode="origin" @ready="onEditorReady" @input="onInput"
					/>
        </view>
				<view class="page-editor-toolbar-container" v-if="toolbar">
				  <sv-editor-toolbar
				    ref="toolbarRef"
				    :style-tools="[
				      'header',
				      'divider',
				      'bold',
				      'italic',
				      'underline',
				      'strike',
				      'align',
				      'color',
				      'backgroundColor',
				      'removeformat'
				    ]"
				    @changeTool="changeTool"
				    @toolMoreItem="onToolMoreItem"
				  >
				    <template #at>
				      <view class="panel-at">
				        <view v-for="item in atList" :key="item.id" class="panel-at-item" @click="onAt(item)">
				          {{ item.name }}
				        </view>
				      </view>
				    </template>
				    <template #topic>
				      <view class="panel-topic">
				        <view v-for="item in topicList" :key="item.id" class="panel-topic-item" @click="onTopic(item)">
				          {{ item.name }}
				        </view>
				      </view>
				    </template>
				    <template #setting>
				      <button size="mini" @click="onExport">导出</button>
				    </template>
				  </sv-editor-toolbar>
				</view>
      </view>
</template>

<script>
import SvEditorToolbar from '@/uni_modules/sv-editor/components/sv-editor/sv-editor-toolbar.vue'
import {
  addAt,
  addTopic,
  addAttachment,
  addImage,
  addLink,
  addVideo
} from '@/uni_modules/sv-editor/components/common/utils.js'	

export default {
  name: 'QuillEditor',
	components: {
		SvEditorToolbar
	},
  props: {
    value: {
      type: String,
      default: ''
    },
    readOnly: {
      type: Boolean,
      default: false
    },
		toolbar: {
			type: Boolean,
			default: true
		}
  },
  data() {
    return {
      formats: {},
      editorCtx: null,
      activeColor: '#2979ff'
    }
  },
  mounted() {
    // #ifndef MP-BAIDU
    uni.loadFontFace({
      family: 'Pacifico',
      source: 'url("https://sungd.github.io/Pacifico.ttf")'
    })
    // #endif
  },
  methods: {
    onEditorReady() {
      // #ifdef MP-BAIDU
      this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editor');
      // #endif
      // #ifdef APP-PLUS || MP-WEIXIN || H5
      uni.createSelectorQuery().select('#editor').context((res) => {
        this.editorCtx = res.context;
        // 初始化内容
        if (this.value) {
          this.editorCtx.setContents({ html: this.value });
        }
      }).exec();
      // #endif
    },
		changeTool(e) {
		  console.log('changeTool ==>', e)
		},
		onToolMoreItem(e) {
		  console.log('onToolMoreItem ==>', e)
		
		  if (e.name == 'clear') {
		    uni.showModal({
		      title: '提示',
		      content: '确定要清空内容吗？',
		      success: ({ confirm }) => {
		        if (confirm) {
		          this.editorCtx.clear()
		        }
		      }
		    })
		  }
		},
    onInput(e) {
      // 触发v-model
			console.log(e)
      this.$emit('input', e.html);
      this.$emit('update:value', e.html);
    },
		onAt(e) {
		  addAt({ username: e.name, userid: e.id }, () => {
		    uni.showToast({ title: '艾特成功' })
		  })
		  // 关闭弹窗
		  this.$refs.toolbarRef.closeMorePop()
		},
		onTopic(e) {
		  addTopic({ topic: e.name, link: e.id }, () => {
		    uni.showToast({ title: '添加话题成功' })
		  })
		  // 关闭弹窗
		  this.$refs.toolbarRef.closeMorePop()
		},
    undo() {
      this.editorCtx && this.editorCtx.undo();
    },
    redo() {
      this.editorCtx && this.editorCtx.redo();
    },
    // uni-icons点击格式化
    formatIcon(name) {
      if (!name) return;
      this.editorCtx && this.editorCtx.format(name);
    },
    onStatusChange(e) {
      this.formats = e.detail;
    },
    insertDivider() {
      this.editorCtx && this.editorCtx.insertDivider({
        success: function() {
          // divider inserted
        }
      });
    },
    clear() {
      uni.showModal({
        title: '清空编辑器',
        content: '确定清空编辑器全部内容？',
        success: res => {
          if (res.confirm) {
            this.editorCtx && this.editorCtx.clear();
          }
        }
      });
    },
    removeFormat() {
      this.editorCtx && this.editorCtx.removeFormat();
    },
    insertDate() {
      const date = new Date();
      const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
      this.editorCtx && this.editorCtx.insertText({ text: formatDate });
    },
    insertImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.editorCtx && this.editorCtx.insertImage({
            src: res.tempFilePaths[0],
            alt: '图像'
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.container {
  width: 100%;
}
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background: #f7f7f7;
  border-radius: 8rpx 8rpx 0 0;
  padding: 8rpx 0;
  font-size: 40rpx;
}
.ql-active {
  color: #2979ff;
}
.editor-wrapper {
  background: #fff;
  border-radius: 0 0 8rpx 8rpx;
  border: 1rpx solid #eee;
  padding: 12rpx;
}

.page-editor-container {
    flex: 1;
    overflow-y: auto;
    border: 10px solid #66ccff;
    box-sizing: border-box;
  }
</style>
