<template>
    <PagingTable url="/ocrRecord" :query="query" ref="table">
        <template #filter>
            <ElSelect
                class="!w-52 ml-2"
                v-model="query.channel"
                placeholder="请选择渠道"
                clearable
                @change="table.refresh(true)"
            >
                <ElOption label="全部渠道" value="" />
                <ElOption v-for="item in channelStore.channelOptions" :key="item" :label="item" :value="item" />
            </ElSelect>
            <ElInput
                class="!w-52"
                placeholder="请输入设备号"
                clearable
                v-model="query.deviceId"
                @keyup.enter="table.refresh(true)"
            >
                <template #append>
                    <ElButton :icon="Search" @click="table.refresh(true)" />
                </template>
            </ElInput>
            <ElButton :icon="ClearAll" @click="exportDialog" v-if="onlyAdmin">清理图片</ElButton>
            <ElButton :icon="Refresh" @click="table.refresh(true)" circle />
        </template>
        <ElTableColumn prop="id" label="#" width="80" />
        <ElTableColumn prop="channel" label="渠道" width="150" />
        <ElTableColumn prop="deviceId" label="设备" width="150" align="center">
            <template #default="{ row }">
                <span
                    @click="copyText(row.deviceId)"
                    class="cursor-pointer hover:text-blue-500"
                    :title="'点击复制: ' + row.deviceId"
                >
                    {{ row.deviceId }}
                </span>
            </template>
        </ElTableColumn>
        <ElTableColumn v-if="isAdmin" prop="img" label="图片" width="120" align="center">
            <template #default="{ row }">
                <RImage
                    style="width: 30px; height: 35px; vertical-align: middle"
                    :src="row.img"
                    :thumbnail="row.thumbnail"
                    fit="cover"
                    lazy
                />
            </template>
        </ElTableColumn>
        <ElTableColumn v-if="isAdmin" label="内容" align="center" width="260">
            <template #default="{ row }">
                <div style="display: flex; align-items: center; justify-content: center; width: 100%">
                    <div
                        v-html="formatContent(row.content)"
                        style="text-align: center; display: flex; justify-content: center; align-items: center"
                        @click="copyText(row.content)"
                        class="cursor-pointer hover:text-blue-500"
                        :title="'点击复制: ' + row.content"
                    ></div>
                    <ElButton :icon="Edit" circle size="small" @click="onContentEdit(row)" style="margin-left: 10px">
                    </ElButton>
                </div>
            </template>
        </ElTableColumn>

        <ElTableColumn label="详细" align="center">
            <template #default="{ row }">
                <div class="detail-container">
                    <div v-if="row.detail" class="detail-content">
                        <div class="detail-item">
                            <div class="detail-left">
                                <template v-if="isValidJson(row.detail)">
                                    <div v-for="(value, key) in JSON.parse(row.detail)" :key="key" class="detail-row">
                                        <strong class="detail-key">{{ key.toUpperCase() }}</strong>
                                        <span
                                            class="detail-address"
                                            @click="copyText(value.address)"
                                            :title="'点击复制地址: ' + value.address"
                                            >{{ value.address }}</span
                                        >
                                        <span class="detail-balance">{{ value.balance }}</span>
                                    </div>
                                </template>
                                <template v-else>
                                    <div class="detail-row">
                                        <span class="text-red-500">数据格式错误</span>
                                    </div>
                                </template>
                            </div>
                            <div class="detail-right">
                                <ElButton
                                    :icon="Refresh"
                                    :loading="row._loading"
                                    circle
                                    size="small"
                                    @click="updateDetail(row)"
                                ></ElButton>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </ElTableColumn>
        <ElTableColumn v-if="isAdmin" label="原始记录" align="center" width="80">
            <template #default="{ row }">
                <ElButton link size="small" @click="showRecord(row.record)">查看</ElButton>
                <!--                <div v-html="formatRecord(row.record)"></div>-->
            </template>
        </ElTableColumn>
        <ElTableColumn prop="favorite" label="收藏" width="60">
            <template #default="{ row }">
                <ElButton
                    circle
                    :icon="row.favorite ? Star : StarOff"
                    @click="handleFavoriteClick(row)"
                    :type="row.favorite ? 'warning' : 'info'"
                />
            </template>
        </ElTableColumn>
        <ElTableColumn prop="createdAt" label="创建时间" :formatter="timeFormatter" width="130" />
    </PagingTable>

    <EditDialog
        v-model="showEditDialog"
        :model="model"
        :on-submit="submit"
        @success="table.refresh()"
        style="width: 90%"
    >
        <ElForm label-width="100px" label-position="right">
            <div class="dialog-content">
                <!-- 左侧输入和展示区域 -->
                <div class="left-section">
                    <ElFormItem prop="content" label="助记词内容: " class="input-section">
                        <div class="input-wrapper">
                            <ElInput
                                v-model="inputWord"
                                placeholder="输入助记词"
                                @input="handleWordInput"
                                @keydown="handleKeyDown"
                                clearable
                                class="word-input"
                            />
                            <div class="suggestions" v-if="suggestions.length > 0">
                                <div
                                    v-for="(word, index) in suggestions"
                                    :key="word"
                                    class="suggestion-item"
                                    :class="{ 'suggestion-item-active': index === selectedIndex }"
                                    @click="selectWord(word)"
                                >
                                    {{ word }}
                                </div>
                            </div>
                        </div>
                    </ElFormItem>
                    <div class="selected-words-container">
                        <div v-for="(word, index) in selectedWords" :key="index" class="selected-word-item">
                            <span>{{ word }}</span>
                            <ElButton type="danger" :icon="X" circle size="small" @click="removeWord(index)" />
                        </div>
                    </div>
                </div>

                <ElDivider direction="vertical" class="divider" />

                <!-- 右侧图片区域 -->
                <div class="right-section">
                    <div class="image-container">
                        <RImage :src="model.img" :thumbnail="model.thumbnail" fit="contain" class="preview-image" />
                    </div>
                </div>
            </div>
        </ElForm>
    </EditDialog>

    <ElDialog v-model="showExportDialog" title="日期选择" width="400px">
        <div class="block">
            <el-date-picker
                v-model="dateValue"
                type="daterange"
                unlink-panels
                range-separator="-"
                start-placeholder="起始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
            />
        </div>
        <template #footer>
            <span class="dialog-footer">
                <ElButton @click="exportDialog()">取 消</ElButton>
                <ElButton type="primary" @click="confirmExport()">确 定</ElButton>
            </span>
        </template>
    </ElDialog>
</template>
<script setup>
import { inject, ref, onMounted, watch } from 'vue'
import PagingTable from '@/components/PagingTable.vue'
import { useTimeFormatter } from '@/utils/formatter'
import { Check, Edit, Plus, Search, Refresh, Star, StarOff, ClearAll, X } from '@vicons/tabler'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import EditDialog from '@/components/EditDialog.vue'
import { setupEditDialog } from '@/utils/editDialog'
import { http } from '@/plugins/http'
import { useClipboard } from '@vueuse/core'
import { format } from 'date-fns'
import { wordlists } from 'bip39'
import { useChannelStore } from '@/stores/channel'

const query = ref({
    width: 50,
    height: 50,
    quality: 50
})
const timeFormatter = useTimeFormatter()
const table = ref(null)
const model = ref({})
const { showEditDialog } = setupEditDialog(model)
const { copy } = useClipboard({ legacy: true })
const isAdmin = inject('isAdminAndOperator')
const onlyAdmin = inject('isAdmin')
const channelStore = useChannelStore()

const showExportDialog = ref(false)
const dateValue = ref('')
const shortcuts = [
    {
        text: '当前周',
        value: () => {
            const now = new Date()
            const startOfWeek = new Date(now)
            startOfWeek.setDate(startOfWeek.getDate() - ((now.getDay() + 6) % 7))
            return [startOfWeek, now]
        }
    },
    {
        text: '当前月',
        value: () => {
            const now = new Date()
            const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
            return [startOfMonth, now]
        }
    },
    {
        text: '上一周',
        value: () => {
            const now = new Date()
            const startOfWeek = new Date(now)
            startOfWeek.setDate(startOfWeek.getDate() - ((now.getDay() + 6) % 7) - 7)
            const endOfWeek = new Date(startOfWeek.getTime() + 6 * 24 * 3600 * 1000)
            return [startOfWeek, endOfWeek]
        }
    },
    {
        text: '上一月',
        value: () => {
            const now = new Date()
            const startOfMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1)
            const endOfMonth = new Date(now.getFullYear(), now.getMonth(), 0)
            return [startOfMonth, endOfMonth]
        }
    }
]

// 添加新的响应式变量
const inputWord = ref('')
const suggestions = ref([])
const selectedWords = ref([])
const selectedIndex = ref(-1)

// 监听model变化，初始化selectedWords
watch(
    () => model.value.content,
    (newVal) => {
        if (newVal) {
            selectedWords.value = newVal.split(' ').filter(Boolean)
        }
    },
    { immediate: true }
)

// 使用BIP39的英文单词列表
const bip39Words = wordlists.english

// 处理单词输入
function handleWordInput() {
    if (!inputWord.value) {
        suggestions.value = []
        selectedIndex.value = -1
        return
    }
    const input = inputWord.value.toLowerCase()
    suggestions.value = bip39Words.filter((word) => word.startsWith(input)).slice(0, 10)
    selectedIndex.value = -1
}

// 处理键盘事件
function handleKeyDown(e) {
    if (suggestions.value.length === 0) return

    switch (e.key) {
        case 'ArrowDown':
            e.preventDefault()
            selectedIndex.value = (selectedIndex.value + 1) % suggestions.value.length
            scrollToSelected()
            break
        case 'ArrowUp':
            e.preventDefault()
            selectedIndex.value = (selectedIndex.value - 1 + suggestions.value.length) % suggestions.value.length
            scrollToSelected()
            break
        case 'Enter':
            e.preventDefault()
            if (selectedIndex.value >= 0) {
                selectWord(suggestions.value[selectedIndex.value])
            }
            break
    }
}

// 选择单词
function selectWord(word) {
    if (!selectedWords.value.includes(word)) {
        selectedWords.value.push(word)
        updateContent()
    }
    inputWord.value = ''
    suggestions.value = []
    selectedIndex.value = -1
}

// 移除单词
function removeWord(index) {
    selectedWords.value.splice(index, 1)
    updateContent()
}

// 更新内容
function updateContent() {
    model.value.content = selectedWords.value.join(' ')
}

onMounted(async () => {
    await channelStore.fetchChannelOptions()
})

function formatRecord(record) {
    return record
        .split('\n')
        .map((line) => {
            if (line.includes('Det:')) return ''
            if (line.includes('Rec:')) {
                const [_, recPart] = line.split('Rec:')
                const [first, ...rest] = recPart.split(',').map((str) => str.trim())
                return first
                // return Rec: <span style="color:red;">${first}</span>, ${rest.join(', ')}
                // if (/^[A-Za-z]+$/.test(first)) {
                //     return <span style="color:red;">${first}</span>
                // }
            }
            return line
        })
        .filter(Boolean)
        .join('<br>')
}

function showRecord(record) {
    ElMessageBox.alert(`<div class="whitespace-pre">${formatRecord(record)}</div>`, '原始记录', {
        dangerouslyUseHTMLString: true,
        customStyle: 'overflow-x: auto;'
    })
}

function formatContent(content) {
    return content
        .split(' ')
        .reduce((acc, cur, index) => {
            if (index % 3 === 0) {
                acc.push([cur])
            } else {
                acc[acc.length - 1].push(cur)
            }
            return acc
        }, [])
        .map((arr) => arr.join('&nbsp;&nbsp;&nbsp;'))
        .join('<br>')
}

async function onContentEdit(row) {
    model.value = row
    showEditDialog.value = true
}

async function submit() {
    try {
        await http.put('/ocrRecord/updateContent', model.value)
        ElMessage.success('修改助记词成功')
    } catch (e) {
        console.error('保存失败', e)
        ElMessage.error('修改助记词失败')
    }
}

async function updateDetail(row) {
    if (row._loading) return
    row._loading = true
    ElMessage.info('正在更新中，请稍等...')
    try {
        const data = await http.get(`/ocrRecord/updateDetail/${row.id}`)
        // table.value.refresh()
        row.detail = data.detail
        ElMessage.success('更新成功')
    } catch (error) {
        console.error('更新详情失败', error)
        ElMessage.error('更新详情失败')
    } finally {
        row._loading = false
    }
}

function copyText(text) {
    copy(text)
    ElMessage.success('复制成功')
}

async function handleFavoriteClick(row) {
    try {
        const data = await http.get(`/ocrRecord/updateFavorite/${row.id}`)
        row.favorite = data.favorite
        if (row.favorite) {
            ElMessage.success('收藏成功')
        } else {
            ElMessage.info('取消收藏')
        }
    } catch (error) {
        console.error('收藏失败失败', error)
        ElMessage.error('收藏失败')
    }
}

function exportDialog() {
    showExportDialog.value = !showExportDialog.value
}

async function confirmExport() {
    if (!dateValue.value) {
        ElMessage.error('请选择日期')
        return
    }
    const data = {
        startDate: format(dateValue.value[0], 'yyyy-MM-dd 00:00:00'),
        endDate: format(dateValue.value[1], 'yyyy-MM-dd 23:59:59')
    }

    const loading = ElLoading.service({
        lock: true,
        text: '正在清理数据...',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
        const res = await http.post('/ocrRecord/imgCleaning', data)
        loading.close()
        if (res.success) {
            ElMessage.success(res.message)
        } else {
            ElMessage.error(res.message)
        }
    } catch (error) {
        loading.close()
        console.error('Error receipt:', error)
        ElMessage.error('清理数据错误,请稍后再试.', error)
    }
    exportDialog()
}

// 滚动到选中项
function scrollToSelected() {
    const suggestionsEl = document.querySelector('.suggestions')
    const selectedEl = suggestionsEl?.querySelector('.suggestion-item-active')
    if (selectedEl) {
        const containerRect = suggestionsEl.getBoundingClientRect()
        const selectedRect = selectedEl.getBoundingClientRect()
        const itemHeight = selectedRect.height
        const visibleHeight = containerRect.height
        const scrollTop = suggestionsEl.scrollTop
        const selectedTop = selectedRect.top - containerRect.top + scrollTop

        // 计算选中项在可视区域中的位置
        const positionInViewport = selectedTop - scrollTop

        // 如果选中项在中间位置以下，向下滚动
        if (positionInViewport > visibleHeight / 2) {
            suggestionsEl.scrollTop = selectedTop - visibleHeight / 2 + itemHeight / 2
        }
        // 如果选中项在中间位置以上，向上滚动
        else if (positionInViewport < visibleHeight / 2 - itemHeight) {
            suggestionsEl.scrollTop = selectedTop - visibleHeight / 2 + itemHeight / 2
        }
    }
}

function isValidJson(str) {
    if (!str) return false
    try {
        const obj = JSON.parse(str)
        return typeof obj === 'object' && obj !== null
    } catch (e) {
        console.error('JSON解析错误:', e)
        return false
    }
}
</script>

<style scoped>
.detail-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
}

.detail-content {
    width: 100%;
    text-align: center;
}

.detail-item {
    display: flex;
    align-items: flex-start;
    width: 100%;
}

.detail-left {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding-right: 8px;
}

.detail-row {
    display: flex;
    align-items: center;
    gap: 4px;
    width: 100%;
}

.detail-right {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    margin-top: 25px;
}

.detail-key {
    background-color: #f56c6c;
    padding: 2px 4px;
    border-radius: 5px;
    color: white;
    font-size: 12px;
    white-space: nowrap;
    width: 55px;
    text-align: center;
    display: inline-block;
}

.detail-address {
    background-color: #e0f7fa;
    color: #00796b;
    padding: 2px 4px;
    border-radius: 5px;
    font-size: 12px;
    cursor: pointer;
    word-break: break-all;
    flex: 1;
    min-width: 0;
}

.detail-balance {
    background-color: #f1f8e9;
    color: #388e3c;
    padding: 2px 4px;
    border-radius: 5px;
    font-size: 12px;
    white-space: nowrap;
}

@media (max-width: 768px) {
    .detail-item {
        flex-direction: column;
        align-items: center;
    }

    .detail-left {
        padding-right: 0;
        margin-bottom: 8px;
    }

    .detail-row {
        flex-direction: column;
        gap: 4px;
    }

    .detail-key,
    .detail-address,
    .detail-balance {
        width: 100%;
        text-align: center;
    }

    .detail-right {
        margin-top: 8px;
    }
}

.suggestions {
    margin-top: 8px;
    max-height: 200px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}

.suggestion-item {
    padding: 8px 12px;
    cursor: pointer;
    transition: all 0.3s;
}

.suggestion-item:hover,
.suggestion-item-active {
    background-color: #f5f7fa;
    color: #409eff;
    font-weight: 500;
}

.selected-words-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    padding: 10px;
    min-height: 200px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}

.selected-word-item {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    background-color: #f0f9eb;
    border-radius: 4px;
    border: 1px solid #e1f3d8;
}

.selected-word-item span {
    color: #67c23a;
    font-weight: 500;
}

.image-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
    border-radius: 4px;
    overflow: hidden;
}

.preview-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.dialog-content {
    display: flex;
    align-items: stretch;
    gap: 20px;
    height: 500px;
    padding: 10px;
}

.left-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.input-section {
    margin-bottom: 0;
}

.input-wrapper {
    position: relative;
    width: 100%;
}

.word-input {
    width: 100%;
    margin-bottom: 8px;
}

.suggestions {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin-top: 4px;
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: white;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.suggestion-item {
    padding: 8px 12px;
    cursor: pointer;
    transition: all 0.2s;
}

.suggestion-item:hover,
.suggestion-item-active {
    background-color: #f5f7fa;
    color: #409eff;
    font-weight: 500;
}

.suggestion-item-active {
    background-color: #ecf5ff;
}

.selected-words-container {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    padding: 10px;
    min-height: 300px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: white;
    overflow-y: auto;
}

.selected-word-item {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 6px 12px;
    background-color: #f0f9eb;
    border-radius: 4px;
    border: 1px solid #e1f3d8;
    transition: all 0.3s;
}

.selected-word-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.selected-word-item span {
    color: #67c23a;
    font-weight: 500;
}

.divider {
    margin: 0;
    height: 100%;
}

.right-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.image-container {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: white;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    overflow: hidden;
}

.preview-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}
</style>
