<script setup lang="ts">
import { computed, ref } from 'vue';
import type { TextProps } from '../basic/Text.vue';
import Text from '../basic/Text.vue';
import FlexCol from '../layout/FlexCol.vue';
import BackgroundBox from './block/BackgroundBox.vue';

export interface TextEllipsisProps extends TextProps {
  /**
   * 显示的行数
   * @default 1
   */
  lines?: number;
  /**
   * 是否可展开
   * @default true
   */
  expandable?: boolean;
  /**
   * 是否默认展开
   * @default false
   */
  startOpen?: boolean;
  /**
   * 展开按钮文字
   * @default '展开'
   */
  openText?: string;
  /**
   * 收起按钮文字
   * @default '收起'
   */ 
  closeText?: string;
  /**
   * 是否显示遮罩层，当定义了该属性时，折叠时将会显示一个遮罩层。
   * @default false
   */
  showMask?: boolean;
  /**
   * 遮罩层颜色
   * @default white
   */
  maskColor?: string;
  /**
   * 折叠时的高度
   * @default 140
   */
  collapsedHeight?: number;
  /**
   * 是否自定义内容，当定义了该属性时，可以通过slot自定义内容渲染，
   * 折叠时将会设置高度为collapsedHeight。
   * @default false
   */
  customContent?: boolean;
}


const emit = defineEmits(['expand', 'collapse']);
const props = withDefaults(defineProps<TextEllipsisProps>(), {
  lines: 1,
  startOpen: false,
  expandable: true,
  customContent: false,
  showMask: false,
  maskColor: 'white',
  collapsedHeight: 140,
  openText: '展开',
  closeText: '收起',
});

const open = ref(props.startOpen);
const currentLines = computed(() => {
  if (open.value)
    return undefined;
  return props.lines;
});

function handleClick() {
  open.value = !open.value;
  emit(open.value ? 'expand' : 'collapse');
}

defineOptions({
  options: {
    virtualHost: true,
    styleIsolation: "shared",
  },
})
</script>

<template>
  <FlexCol position="relative">
    <FlexCol 
      :height="customContent && !open ? collapsedHeight : undefined"
      overflow="hidden"
    >
      <slot>
        <Text 
          :ellipsis="true" 
          :lines="currentLines"
          v-bind="$attrs"
          :text="text"
        />
      </slot>
      <BackgroundBox 
        v-if="!open && (showMask || customContent)"
        :height="collapsedHeight"
        color1="transparent"
        :color2="maskColor"
        :innerStyle="{ 
          position: 'absolute',
          bottom: '36rpx',
          left: 0,
          right: 0,
        }"
      />
    </FlexCol>
    <slot v-if="expandable" name="button" :onClick="handleClick">
      <Text 
        innerClass="nana-text-ellipsis-expand"
        touchable
        :text="open ? closeText : openText"
        color="primary" 
        @click="handleClick"
      />
    </slot>
  </FlexCol>
</template>

<style>
.nana-text-ellipsis-expand {
  /* #ifndef APP-NVUE */
  display: inline-block;
  /* #endif */
  text-align: right;
}
</style>