<template>
    <div class="translation-content" ref="translationContentRef">
            <!-- :class="{ active: store.highlightClauseId === item.payload?.clause_number }"
        :data-clause-number="item.payload?.clause_number" -->
<!-- 查找 -->
        <div class="searchFor" v-if="store.isSsearchFor">
            <el-input v-model="keyword" style="width: 260px;" placeholder="查找原文内容" />
            <div class="searchTextNum">
                <span v-if="total==0">0</span>
                <span v-else> {{ current + 1 }}</span>/{{ total }} 
            </div>
            <div class="prev" @click="prev"><el-icon><ArrowUp /></el-icon></div>
            <div class="next" @click="next"><el-icon><ArrowDown /></el-icon></div>
            <div class="close" @click="closeClick"><el-icon><CloseBold /></el-icon></div>
        </div>
        <div class="content-box" ref="contentBox">
            <div class="translation-item" v-for="(item, index) in renderList" :key="index">
                <div class="item-body">
                    <div class="original-text" v-if="store.isShowOriginal">
                        <template v-for="(t, i) in item.fragments" :key="i">
                            <span :class="{ high: t.hit, current: t.hit && currentGlobalIndex === t.globalIndex}">
                                {{ t.text }}
                            </span>
                        </template>
                    </div>
                    <div class="translated-text">
                        <span class="clause-title">第{{ getChineseNumber(item.payload?.clause_number) }}节</span>{{ item.payload?.clause_content_zh }}
                    </div>
                </div>
            </div>
        </div>
    </div>

</template>

<script setup>
import { onMounted, onUnmounted, ref, nextTick ,watch,computed} from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { useWrittingAsstaintStore } from "@/stores/writtingAsstaintStore";
import { useStream } from "@/hooks/useStream";
// 子组件直接获取Pinia Store（核心优化）
const store = useWrittingAsstaintStore();
const translationContentRef = ref(null);

// 数字转中文序号
const getChineseNumber = (num) => {
	const zh = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
	const n = parseInt(num);
	if (n <= 10) return zh[n];
	if (n < 20) return '十' + zh[n % 10];
	if (n < 100) {
		return zh[Math.floor(n / 10)] + '十' + (n % 10 === 0 ? '' : zh[n % 10]);
	}
	return num;
};

const closeClick=()=>{
    store.handleIsSsearchFor()
    current.value=0
    total.value=0
    keyword.value=''
}
const keyword = ref('')
const contentBox = ref(null)
const current = ref(0)
const total = ref(0)

// 渲染列表（不修改原数据，自动更新）
const renderList = computed(() => {
  const key = keyword.value.trim()
  return (store.clauseTranslationMessages || []).map(item => {
    const section = item.payload?.clause_section || ''
    const content = item.payload?.clause_content || ''
    const fullText = section + ' ' + content

    if (!key) {
      return {
        ...item,
        fragments: [{ text: fullText, hit: false, globalIndex: -1 }]
      }
    }

    const parts = fullText.split(new RegExp(`(${key})`, 'g'))
    const fragments = []
    parts.forEach(t => {
      fragments.push({
        text: t,
        hit: t === key,
        globalIndex: -1
      })
    })
    return { ...item, fragments }
  })
})

// 全局匹配列表（只计算一次，修复蓝色全部选中BUG）
const globalMatchList = computed(() => {
  const arr = []
  renderList.value.forEach(item => {
    item.fragments.forEach(f => {
      if (f.hit) arr.push(f)
    })
  })
  return arr
})

// 当前高亮的全局索引
const currentGlobalIndex = computed(() => {
  if (!globalMatchList.value.length) return -1
  return globalMatchList.value[current.value]?.globalIndex ?? -2
})

// 总数
watch(globalMatchList, (val) => {
  total.value = val.length
  current.value = 0
}, { immediate: true })

// 给每个命中项分配唯一 index
watch([renderList, globalMatchList], () => {
  let idx = 0
  const map = new Map()
  globalMatchList.value.forEach(item => {
    map.set(item, idx++)
  })

  renderList.value.forEach(item => {
    item.fragments.forEach(f => {
      if (f.hit) f.globalIndex = map.get(f)
    })
  })
})

function doSearch() {
  current.value = 0
  scrollTo(0)
}

function prev() {
  if (!total.value) return
  current.value = (current.value - 1 + total.value) % total.value
  console.log(current.value )
  scrollTo(current.value)
}

function next() {
  if (!total.value) return
  current.value = (current.value + 1) % total.value
  scrollTo(current.value)
}

function scrollTo(idx) {
  setTimeout(() => {
    const all = contentBox.value?.querySelectorAll('.high')
    if (all?.[idx]) {
      contentBox.value.scrollTo({
        top: all[idx].offsetTop - 100,
        behavior: 'smooth'
      })
    }
  }, 0)
}


</script>
<style lang="scss" scoped>

.content-box{
    overflow-y: auto;
    margin-top: 30px;
    height: calc(100vh - 250px);
    .translation-item{
        margin-bottom: 24px;
        .item-body{
            display: flex;
            justify-content: space-between;
            width: 85%;
            margin: 0 auto;
            .original-text{
                min-width: 48%;
                line-height: 30px;
                margin-right: 62px;
                flex: 2;
            }
            .translated-text{
                width: 100%;
                line-height: 30px;
            }
        }
    }

}


.searchFor{
    display: flex;
    align-items: center;
    width: 430px;
    height: 60px;
    padding: 12px 0;
    border-radius: 10px;
    background-color: #fff;
    border: 1px solid rgb(234, 236, 238);
    position: fixed;
    top: 120px;
    right: 20px;
    :deep(.el-input__wrapper){
        background-color: #fff;
    }
    .searchTextNum{
        width: 70px;
        height: 100%;
        border-right: 1px solid rgb(234, 236, 238);
        line-height: 40px;
        margin-right: 16px;
        text-align: center;
    }
    .prev{
        margin-right: 12px;
    }
    .next{
        margin-right: 12px;
    }
    // position: absolute;
}

.high {
  background: #ffeb3b;
}
.current {
  background: #409eff !important;
  color: #fff !important;
}
</style>