<template>
  <FlexCol>
    <view class="richtext-preview-box" @click="() => !disabled && !readonly ? edit() : preview()">
      <Parse v-if="modelValue" :content="modelValue" containerStyle="max-height:400px" />
      <Text v-else color="text.second">{{placeholder}}</Text>
    </view>
    <FlexRow :gap="20" align="center">
      <Button v-if="!disabled" icon="browse" text="预览" size="small" @click="preview" />
      <Button v-if="!disabled && !readonly" icon="edit" text="编辑" size="small" @click="edit" type="primary" />
      <Text v-if="maxLength > 0">{{ modelValue?.length || 0 }}/{{ maxLength }} 字</Text>
    </FlexRow>
  </FlexCol>
</template>

<script setup lang="ts">
import { onPageShow } from '@dcloudio/uni-app';
import { navTo } from '@/components/utils/PageAction';
import Parse from '@/components/display/parse/Parse.vue';
import Button from '@/components/basic/Button.vue';
import Text from '@/components/basic/Text.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';

const props = defineProps({	
  modelValue: { 
    type: String,
    default: null 
  },
  maxLength: {
    type: Number,
    default: -1,
  },
  placeholder: {
    type: String,
    default: '未编写内容，点击编写',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
})
const emit = defineEmits(['update:modelValue'])
let editorOpened = false;

function preview() {
  uni.setStorage({
    key: 'editorContent',
    data: props.modelValue,
    success: () => navTo('/pages/editor/preview'),
  })
}
function edit() {
  editorOpened = true;
  uni.setStorage({
    key: 'editorMaxLength',
    data: props.maxLength,
  })
  uni.setStorage({
    key: 'editorContent',
    data: props.modelValue,
    success: () => navTo('/pages/editor/editor'),
  })
}

onPageShow(() => {
  if (editorOpened) {
    editorOpened = false;
    uni.getStorage({
      key: 'editorContent',
      success: (success) => emit('update:modelValue', success.data),
    })
  }
})
</script>

<style lang="scss" scoped>
.richtext-preview-box {
  flex: 1;
  min-height: 400rpx;
  margin-bottom: 15rpx;
}
</style>