<template>
    <div class="mall-order-fail-reason-table-cell">
        <template v-if="fullText !== ''">
            <el-tooltip placement="top" effect="dark" popper-class="mall-order-reason-tooltip" :enterable="true">
                <template #content>
                    <div class="mall-order-fail-reason-tooltip-body">{{ fullText }}</div>
                </template>
                <span class="mall-order-fail-reason-ellipsis">{{ displayText }}</span>
            </el-tooltip>
        </template>
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { TableColumnCtx } from 'element-plus'
import { getCellValue } from '/@/components/table/index'

interface Props {
    row: TableRow
    field: TableColumn
    column: TableColumnCtx<TableRow>
    index: number
}

const props = defineProps<Props>()

/** 与后台换行一致；无换行时在 attempt N: 前补行首，便于阅读 */
function normalizeFailReasonText(raw: unknown): string {
    if (raw === null || raw === undefined) {
        return ''
    }
    let t = String(raw)
        .replace(/\r\n/g, '\n')
        .replace(/\r/g, '\n')
    t = t.replace(/([^\n])(attempt\s+\d+:)/gi, '$1\n$2')
    return t
}

const rawCell = computed(() => getCellValue(props.row, props.field, props.column, props.index))

const fullText = computed(() => normalizeFailReasonText(rawCell.value))

const displayText = computed(() => fullText.value)
</script>

<style scoped lang="scss">
.mall-order-fail-reason-table-cell {
    width: 100%;
    min-width: 0;
}

.mall-order-fail-reason-ellipsis {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
}
</style>

<style lang="scss">
.el-popper.mall-order-reason-tooltip {
    max-width: min(560px, 90vw);
    box-sizing: border-box;
}

.mall-order-reason-tooltip .mall-order-fail-reason-tooltip-body {
    white-space: pre-wrap;
    word-break: break-word;
    line-height: 1.5;
    text-align: left;
}
</style>
