<template>
    <div class="auto-assign-log-page">
        <el-card class="!border-none" shadow="never">
            <el-form :inline="true" class="log-filter-form">
                <el-form-item label="记录时间">
                    <el-date-picker
                        v-model="timeRange"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        clearable
                        @change="doSearch"
                    />
                </el-form-item>
                <el-form-item label="执行日期">
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYY-MM-DD"
                        clearable
                        @change="doSearch"
                    />
                </el-form-item>
                <el-form-item label="结果">
                    <el-select
                        v-model="queryParams.action"
                        clearable
                        placeholder="全部"
                        class="w-[120px]"
                        @change="doSearch"
                    >
                        <el-option label="已分配" value="1" />
                        <el-option label="未分配" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="回退">
                    <el-select
                        v-model="queryParams.is_rollback"
                        clearable
                        placeholder="全部"
                        class="w-[120px]"
                        @change="doSearch"
                    >
                        <el-option label="未回退" value="0" />
                        <el-option label="已回退" value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="关键词">
                    <el-input
                        v-model="queryParams.keyword"
                        placeholder="患者/手机号/医助/诊单ID"
                        clearable
                        class="w-[220px]"
                        @keyup.enter="doSearch"
                        @clear="doSearch"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="doSearch">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
            <div class="log-hint">
                由每日定时任务「待分配诊单自动指派」写入：按上月二诊复诊接诊率分档轮询分配（&gt;70% 每人3条/日，60%~70%
                每人2条/日，50%~60% 每人1条/日，&lt;50% 不分）。「回退」可将已分配医助撤回到自动分配前的原医助（通常为一中心），并写入指派日志。
            </div>
        </el-card>

        <el-card class="!border-none mt-3" shadow="never">
            <div class="toolbar mb-3">
                <el-button
                    v-perms="['stats.autoAssignLog/rollback']"
                    type="warning"
                    :disabled="selectedRows.length === 0"
                    :loading="rollbackLoading"
                    @click="handleBatchRollback"
                >
                    回退选中（{{ selectedRows.length }}）
                </el-button>
                <span v-if="selectedRows.length > 0" class="toolbar-tip">
                    已选 {{ selectedRows.length }} 条可回退记录
                </span>
            </div>
            <el-table
                ref="tableRef"
                :data="pager.lists"
                v-loading="pager.loading"
                size="default"
                stripe
                row-key="id"
                @selection-change="onSelectionChange"
            >
                <el-table-column
                    type="selection"
                    width="48"
                    :selectable="rowSelectable"
                    reserve-selection
                />
                <el-table-column label="记录时间" width="160">
                    <template #default="{ row }">{{ row.create_time_text || '—' }}</template>
                </el-table-column>
                <el-table-column label="诊单" width="90" prop="diagnosis_id" />
                <el-table-column label="患者" min-width="110">
                    <template #default="{ row }">
                        <div>{{ row.patient_name || '—' }}</div>
                        <div class="cell-sub">{{ row.patient_phone || '' }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="结果" width="90" align="center">
                    <template #default="{ row }">
                        <el-tag :type="Number(row.action) === 1 ? 'success' : 'info'" size="small">
                            {{ row.action_text }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="回退状态" width="140">
                    <template #default="{ row }">
                        <template v-if="Number(row.is_rollback) === 1">
                            <el-tag type="warning" size="small">已回退</el-tag>
                            <div class="cell-sub">{{ row.rollback_time_text }}</div>
                            <div v-if="row.rollback_admin_name" class="cell-sub">
                                {{ row.rollback_admin_name }}
                            </div>
                        </template>
                        <el-tag v-else-if="Number(row.can_rollback) === 1" type="success" size="small">
                            可回退
                        </el-tag>
                        <span v-else>—</span>
                    </template>
                </el-table-column>
                <el-table-column label="医助" min-width="110">
                    <template #default="{ row }">
                        <template v-if="Number(row.assistant_id) > 0">
                            <div>{{ row.assistant_name || '#' + row.assistant_id }}</div>
                            <div class="cell-sub">上月二诊接诊率 {{ formatRate(row.visit2_rate) }}</div>
                        </template>
                        <span v-else>—</span>
                    </template>
                </el-table-column>
                <el-table-column label="档位" width="100" align="center">
                    <template #default="{ row }">{{ row.tier_text || '—' }}</template>
                </el-table-column>
                <el-table-column label="轮次" width="70" align="center">
                    <template #default="{ row }">
                        {{ Number(row.round_no) > 0 ? '第' + row.round_no + '轮' : '—' }}
                    </template>
                </el-table-column>
                <el-table-column label="原因" min-width="280" show-overflow-tooltip>
                    <template #default="{ row }">{{ row.reason }}</template>
                </el-table-column>
                <el-table-column label="统计月" width="90" prop="stat_month" align="center" />
                <el-table-column label="批次" width="160">
                    <template #default="{ row }">
                        <span class="cell-sub">{{ row.batch_no }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="90" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button
                            v-if="Number(row.can_rollback) === 1"
                            v-perms="['stats.autoAssignLog/rollback']"
                            link
                            type="warning"
                            :loading="rollbackLoading"
                            @click="handleSingleRollback(row)"
                        >
                            回退
                        </el-button>
                        <span v-else class="cell-sub">—</span>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts" name="statsAutoAssignLog">
import { autoAssignLogLists, autoAssignLogRollback } from '@/api/stats'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import { onMounted, reactive, ref, watch } from 'vue'

const dateRange = ref<[string, string] | null>(null)
const timeRange = ref<[string, string] | null>(null)
const tableRef = ref()
const selectedRows = ref<any[]>([])
const rollbackLoading = ref(false)

const queryParams = reactive({
    start_date: '',
    end_date: '',
    start_time: '',
    end_time: '',
    action: '' as '' | '0' | '1',
    is_rollback: '' as '' | '0' | '1',
    keyword: ''
})

watch(dateRange, (val) => {
    queryParams.start_date = val?.[0] ?? ''
    queryParams.end_date = val?.[1] ?? ''
})

watch(timeRange, (val) => {
    queryParams.start_time = val?.[0] ?? ''
    queryParams.end_time = val?.[1] ?? ''
})

const { pager, getLists, resetPage } = usePaging({
    fetchFun: autoAssignLogLists,
    params: queryParams
})

const doSearch = () => {
    selectedRows.value = []
    tableRef.value?.clearSelection?.()
    resetPage()
}

const handleReset = () => {
    dateRange.value = null
    timeRange.value = null
    queryParams.start_date = ''
    queryParams.end_date = ''
    queryParams.start_time = ''
    queryParams.end_time = ''
    queryParams.action = ''
    queryParams.is_rollback = ''
    queryParams.keyword = ''
    doSearch()
}

const formatRate = (rate: number | null | undefined) =>
    rate === null || rate === undefined ? '—' : `${rate}%`

const rowSelectable = (row: any) => Number(row.can_rollback) === 1

const onSelectionChange = (rows: any[]) => {
    selectedRows.value = rows.filter((r) => Number(r.can_rollback) === 1)
}

const runRollback = async (ids: number[]) => {
    if (ids.length === 0) return
    await feedback.confirm(
        `确认回退选中的 ${ids.length} 条自动分配？将把诊单医助撤回到自动分配前的原医助，并写入指派日志。`
    )
    rollbackLoading.value = true
    try {
        const res: any = await autoAssignLogRollback({ ids })
        const success = Number(res?.success ?? 0)
        const failed = Number(res?.failed ?? 0)
        if (failed > 0 && Array.isArray(res?.messages) && res.messages.length) {
            feedback.msgWarning(
                `回退成功 ${success} 条，跳过/失败 ${failed} 条：${res.messages.slice(0, 3).join('；')}`
            )
        } else {
            feedback.msgSuccess(`回退成功 ${success} 条`)
        }
        selectedRows.value = []
        tableRef.value?.clearSelection?.()
        await getLists()
    } finally {
        rollbackLoading.value = false
    }
}

const handleBatchRollback = () => {
    const ids = selectedRows.value.map((r) => Number(r.id)).filter((id) => id > 0)
    return runRollback(ids)
}

const handleSingleRollback = (row: any) => {
    const id = Number(row?.id ?? 0)
    if (id <= 0) return
    return runRollback([id])
}

onMounted(() => getLists())
</script>

<style lang="scss" scoped>
.auto-assign-log-page {
    .log-filter-form {
        :deep(.el-form-item) {
            margin-bottom: 8px;
        }
    }

    .log-hint {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        line-height: 1.6;
    }

    .toolbar {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .toolbar-tip {
        font-size: 12px;
        color: var(--el-text-color-secondary);
    }

    .cell-sub {
        font-size: 12px;
        color: var(--el-text-color-secondary);
    }
}
</style>
