<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-form :model="detailFormData" ref="detailFormRef" :inline="true">
                    <el-form-item label="回执状态" prop="sendStatus">
                        <el-select
                            clearable
                            style="width: 180px"
                            placeholder="请选择回执状态"
                            v-model="detailFormData.sendStatus"
                        >
                            <el-option label="发送成功" value="发送成功" />
                            <el-option label="发送失败" value="发送失败" />
                            <el-option label="未返回" value="未返回" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="onHandleSearch">
                            搜索
                        </el-button>
                        <el-button plain type="warning" icon="Refresh" @click="onHandleReset">
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
                <el-table
                    v-loading="detailLoading"
                    :data="detailList"
                    border
                    style="width: 100%"
                    max-height="500px"
                >
                    <el-table-column type="index" label="序号" align="center" width="80" />
                    <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="submitTime"
                        label="提交时间"
                        align="center"
                        width="180"
                    />
                    <el-table-column
                        width="120"
                        align="center"
                        label="提交状态"
                        prop="submitStatus"
                    />
                    <el-table-column width="180" align="center" prop="sendTime">
                        <template #header>
                            <div
                                style="
                                    display: flex;
                                    align-items: center;
                                    justify-content: center;
                                    gap: 5px;
                                "
                            >
                                <span>回执时间</span>
                                <el-tooltip
                                    effect="dark"
                                    placement="top-start"
                                    content="短信运营商回执时间"
                                >
                                    <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="回执状态" align="center" width="120">
                        <template #default="{ row }">
                            <el-tag :type="row.sendStatus === '发送成功' ? 'success' : 'danger'">
                                {{ row.sendStatus === '发送成功' ? '发送成功' : row.sendStatus }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="120" fixed="right">
                        <template #default="{ row }">
                            <el-button
                                link
                                type="primary"
                                icon="Refresh"
                                @click="handleResend(row)"
                                v-if="row.sendStatus !== '发送成功'"
                            >
                                重新发送
                            </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 detailFormRef = ref(null)
const detailFormData = ref({
    sendStatus: '',
    loopId: '',
    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: 'loopTime',
        label: '时间',
    },
    {
        prop: 'msgType',
        label: '短信类型',
        formatter: (row) => {
            const typeMap = {
                1: '通知',
                2: '计划',
            }
            return typeMap[row.msgType] || '-'
        },
    },
    {
        prop: 'messageContent',
        label: '短信内容',
        showOverflowTooltip: true,
    },
    {
        prop: 'remark',
        label: '备注',
        showOverflowTooltip: true,
    },
]

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

// 第二层详情弹框配置
const detailDialogConfig = reactive({
    outerVisible: false,
    outerTitle: '发送记录详情',
    outerWidth: '80%',
    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
    detailFormData.value.loopId = row.loopId
    detailFormData.value.id = row.id

    try {
        const result = await getLoopSendRecordDetailsAPI(detailFormData.value)
        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(detailFormData.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('重新发送失败')
        }
    }
}

// 搜索
const onHandleSearch = async () => {
    const result = await getLoopSendRecordDetailsAPI(detailFormData.value)
    if (result.code === 200) {
        detailList.value = result.data || result.rows || []
    } else {
        proxy.$modal.msgError(result.msg || '获取详情失败')
    }
}

// 重置
const onHandleReset = () => {
    detailFormRef.value?.resetFields()
    onHandleSearch()
}

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

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