<template>
  <view class="d-flex flex-col">
    <view class="richtext-preview-box" @click="edit">
      <Parse v-if="modelValue" :content="modelValue" contentStyle="max-height:400px;overflow:hidden;" />
      <Text v-else color="text.second">{{placeholder}}</Text>
      <div class="richtext-preview-box-fade"></div>
    </view>
    <view class="d-flex flex-row gap-sss align-center mt-2">
      <Button icon="browse" text="预览" size="small" @click="preview" />
      <Button icon="edit" text="编辑" size="small" @click="edit" type="primary" />
      <Text v-if="maxLength > 0">{{ modelValue?.length || 0 }}/{{ maxLength }} 字</Text>
    </view>
  </view>
</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';

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

function preview() {
  uni.setStorage({
    key: 'editorContent',
    data: props.modelValue,
    success: () => navTo('/pages/article/editor/preview'),
  })
}
function edit() {
  editorOpened = true;
  uni.setStorage({
    key: 'editorMaxLength',
    data: props.maxLength,
  })
  uni.setStorage({
    key: 'editorContent',
    data: props.modelValue,
    success: () => navTo('/pages/article/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 {
  position: relative;
  flex: 1;
  min-height: 400rpx;

  .richtext-preview-box-fade {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100rpx;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
  }
}
</style>