<template>
  <view class="form-richtext">
    <view class="richtext-toolbar">
      <text class="toolbar-btn" @click="insertTag('b')">加粗</text>
      <text class="toolbar-btn" @click="insertTag('i')">斜体</text>
      <text class="toolbar-btn" @click="insertImage">图片</text>
    </view>
    <textarea class="richtext-editor" :value="value" placeholder="请输入图文内容" placeholder-class="placeholder"
      @input="$emit('input', $event.detail.value)" />
    <view v-if="value" class="richtext-preview">
      <rich-text :nodes="value" />
    </view>
  </view>
</template>

<script>
export default {
  name: "FormItemRichtext",
  props: {
    value: { type: String, default: "" },
  },
  methods: {
    insertTag(tag) {
      const text = `<${tag}></${tag}>`;
      this.$emit("input", (this.value || "") + text);
    },
    insertImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          const imgTag = `<img src="${res.tempFilePaths[0]}" />`;
          this.$emit("input", (this.value || "") + imgTag);
        },
      });
    },
  },
};
</script>

<style scoped>
.form-richtext {
  width: 100%;
}

.richtext-toolbar {
  display: flex;
  gap: 16rpx;
  padding: 16rpx;
  background-color: #f0f0f0;
  border-radius: 8rpx 8rpx 0 0;
}

.toolbar-btn {
  padding: 8rpx 16rpx;
  background-color: #ffffff;
  border-radius: 4rpx;
  font-size: 24rpx;
  color: #333333;
}

.richtext-editor {
  width: 100%;
  height: 300rpx;
  background-color: #ffffff;
  border: 2rpx solid #e0e0e0;
  border-top: none;
  border-radius: 0 0 8rpx 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333333;
}

.placeholder {
  color: #999999;
}

.richtext-preview {
  margin-top: 16rpx;
  padding: 16rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
}
</style>
