<template>
    <div class="send-details-container">
        <!-- 第一层详情列表 -->
        <ComTable
            ref="recordsTableRef"
            :form-columns="formColumns"
            :table-columns="tableColumns"
            :load-data="loadRecordsData"
            :show-toolbar="false"
            :show-action="true"
            :default-query-params="{
                id: props.sendDetailsId,
            }"
            :action-columns="actionColumns"
        />

        <!-- 第二层详情弹框 - 显示每个人的发送记录 -->
        <ComDialog :dialog-config="detailDialogConfig" @closeDialogOuter="onCloseDetailDialog">
            <template #outerContent>
                <el-table
                    v-loading="detailLoading"
                    :data="detailList"
                    border
                    style="width: 100%"
                    max-height="500px"
                >
                    <el-table-column prop="workerName" label="姓名" align="center" width="120" />
                    <el-table-column
                        prop="orgName"
                        label="部门"
                        align="center"
                        show-overflow-tooltip
                    />
                    <el-table-column prop="phone" label="电话" align="center" width="130" />
                    <el-table-column prop="sendTime" label="发送时间" align="center" width="180" />
                    <el-table-column prop="submitStatus" label="提交状态" align="center" />
                    <el-table-column label="发送状态" align="center" width="120">
                        <template #default="{ row }">
                            <el-tag :type="row.sendStatus === '发送成功' ? 'success' : 'danger'">
                                {{ row.sendStatus === '发送成功' ? '发送成功' : '发送失败' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="120" fixed="right">
                        <template #default="{ row }">
                            <el-button
                                v-if="row.sendStatus !== '发送成功'"
                                link
                                type="primary"
                                icon="Refresh"
                                @click="handleResend(row)"
                            >
                                重新发送
                            </el-button>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </ComDialog>
    </div>
</template>

<script setup name="SendDetails">
import { ref, reactive, computed } from 'vue'
import { getCurrentInstance } from 'vue'
import ComTable from '@/components/ComTable/index.vue'
import ComDialog from '@/components/ComDialog/index.vue'
import {
    getLoopSendRecordsAPI,
    getLoopSendRecordDetailsAPI,
    resendOneLoopMsgAPI,
} from '@/api/sMsSendManage/loopSend.js'

const { proxy } = getCurrentInstance()

const recordsTableRef = ref(null)
const detailLoading = ref(false)
const detailList = ref([])
const currentLoopId = ref(null) // 当前查看的 loopId
const currentId = ref(null) // 当前查看的 id

const props = defineProps({
    sendDetailsId: {
        type: [String, Number],
        default: '',
    },
})

// 查询表单配置
const formColumns = computed(() => [
    {
        type: 'input',
        prop: 'taskName',
        placeholder: '请输入任务名称',
    },
    {
        type: 'select',
        prop: 'msgType',
        placeholder: '请选择短信类型',
        options: [
            { label: '通知', value: '1' },
            { label: '计划', value: '2' },
        ],
    },
])

// 表格列配置
const tableColumns = [
    {
        prop: 'taskName',
        label: '任务名称',
    },
    {
        prop: 'msgType',
        label: '短信类型',
        formatter: (row) => {
            const typeMap = {
                1: '通知',
                2: '计划',
            }
            return typeMap[row.msgType] || '-'
        },
    },
    {
        prop: 'remark',
        label: '备注',
        showOverflowTooltip: true,
    },
]

// 操作列配置
const actionColumns = [
    {
        label: '详情',
        type: 'primary',
        link: true,
        handler: (row) => {
            handleViewDetail(row)
        },
    },
]

// 第二层详情弹框配置
const detailDialogConfig = reactive({
    outerVisible: false,
    outerTitle: '发送记录详情',
    outerWidth: '1000px',
    minHeight: '400px',
    maxHeight: '80vh',
})

// 加载第一层列表数据
const loadRecordsData = async (params) => {
    try {
        const result = await getLoopSendRecordsAPI(params)
        if (result.code === 200) {
            return {
                rows: result.rows || result.data || [],
                total: result.total || 0,
            }
        }
        return { rows: [], total: 0 }
    } catch (error) {
        console.error('加载发送记录失败:', error)
        return { rows: [], total: 0 }
    }
}

// 查看详情（打开第二层弹框）
const handleViewDetail = async (row) => {
    detailDialogConfig.outerTitle = `发送记录详情 - ${row.taskName || ''}`
    detailDialogConfig.outerVisible = true
    detailLoading.value = true
    detailList.value = []
    currentLoopId.value = row.loopId // 保存当前 loopId
    currentId.value = row.id // 保存当前 id

    try {
        const result = await getLoopSendRecordDetailsAPI({ loopId: row.loopId, id: row.id })
        if (result.code === 200) {
            detailList.value = result.data || result.rows || []
        } else {
            proxy.$modal.msgError(result.msg || '获取详情失败')
        }
    } catch (error) {
        console.error('获取发送记录详情失败:', error)
        proxy.$modal.msgError('获取详情失败')
    } finally {
        detailLoading.value = false
    }
}

// 关闭第二层弹框
const onCloseDetailDialog = (visible) => {
    detailDialogConfig.outerVisible = visible
}

// 重新发送
const handleResend = async (row) => {
    try {
        await proxy.$modal.confirm('确认要重新发送给该人员吗？')
        const result = await resendOneLoopMsgAPI({
            id: row.id,
            phone: row.phone,
            taskId: row.taskId,
        })
        if (result.code === 200) {
            proxy.$modal.msgSuccess('重新发送成功')
            // 重新获取详情数据以刷新列表
            if (currentLoopId.value) {
                const detailResult = await getLoopSendRecordDetailsAPI({
                    loopId: currentLoopId.value,
                    id: currentId.value,
                })
                if (detailResult.code === 200) {
                    detailList.value = detailResult.data || detailResult.rows || []
                }
            }
        } else {
            proxy.$modal.msgError(result.msg || '重新发送失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('重新发送失败:', error)
            proxy.$modal.msgError('重新发送失败')
        }
    }
}

// 暴露刷新方法
defineExpose({
    refresh: () => {
        recordsTableRef.value?.refresh()
    },
})
</script>

<style lang="scss" scoped>
.send-details-container {
    padding: 0;
}
</style>
