<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 v-if="modelValue" class="richtext-preview-mask" :style="maskStyle" />
    </view>
    <FlexRow :gap="20" justify="flex-end" 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" :text="`${modelValue?.length || 0}/${maxLength} 字`" fontConfig="subText" textAlign="right" />
    </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';
import { propGetThemeVar, useTheme } from '@/components/theme/ThemeDefine';
import { computed } from '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,
  },
  maskColor: {
    type: String,
    default: () => propGetThemeVar('RichTextEditorMaskColor', 'white'),
  }
})
const emit = defineEmits(['update:modelValue'])

const theme = useTheme();

let editorOpened = false;
const maskStyle = computed(() => ({
  height: theme.resolveThemeSize('RichTextEditorMaskHeight', 100),
  background: `linear-gradient(0deg, ${theme.resolveThemeColor(props.maskColor)} 0%, transparent 100%)`,
}));

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 {
  position: relative;
  flex: 1;
  min-height: 400rpx;
  margin-bottom: 15rpx;

  .richtext-preview-mask {
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
  }
}
</style>