<template>
    <x-search-bar class="mb-8-2">
        <template #default="{ gutter, colSpan }">
            <!-- 统一设置 label 宽度 -->
            <a-form :model="searchFormData" layout="inline" :label-col="{ style: { width: '80px' } }"
                :wrapper-col="{ style: { flex: 1 } }">
                <a-row :gutter="gutter">
                    <a-col v-bind="colSpan">
                        <a-form-item label="用户姓名" name="customerName">
                            <a-input placeholder="请输入客户姓名" v-model:value="searchFormData.customerName" />
                        </a-form-item>
                    </a-col>
                    <a-col v-bind="colSpan">
                        <a-form-item label="联系方式" name="phone">
                            <a-input placeholder="请输入" v-model:value="searchFormData.phone" />
                        </a-form-item>
                    </a-col>
                    <a-col v-bind="colSpan">
                        <a-form-item label="短信类型" name="smsType">
                            <a-select v-model:value="searchFormData.smsType" allowClear>
                                <a-select-option value="ACTIVITY">活动推广</a-select-option>
                                <a-select-option value="LV_UP">等级通知</a-select-option>
                                <a-select-option value="FIRST_REGISTER">首次注册</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col v-bind="colSpan">
                        <a-form-item label="发送时间" name="sendAtRange">
                            <a-range-picker v-model:value="searchFormData.sendAtRange" style="width: 100%;"
                                :show-time="{ format: 'HH:mm:ss' }" format="YYYY-MM-DD HH:mm:ss"
                                :placeholder="['开始时间', '结束时间']" @change="handleDateRangeChange" />
                        </a-form-item>
                    </a-col>

                    <a-col class="align-right" v-bind="colSpan">
                        <a-space>
                            <a-button @click="handleResetSearch">{{ $t('button.reset') }}</a-button>
                            <a-button ghost type="primary" @click="handleSearch">
                                {{ $t('button.search') }}
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>
            </a-form>
        </template>
    </x-search-bar>
    <a-row :gutter="8" :wrap="false">
        <a-col flex="auto">
            <a-card type="flex">
                <a-table :columns="columns" :data-source="listData" bordered="true" :loading="loading"
                    :pagination="paginationState" :scroll="{ x: 'max-content' }" @change="onTableChange">
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex === 'smsType'">
                            <span v-if="record.smsType == 'ACTIVITY'">{{ '活动推广' }}</span>
                            <span v-else-if="record.smsType == 'LV_UP'">{{ '等级通知' }}</span>
                            <span v-else-if="record.smsType == 'FIRST_REGISTER'">{{ '首次注册' }}</span>
                        </template>
                        <template v-if="column.dataIndex === 'sendAt'">
                            <span>{{ dayjs(record.sendAt).format('YYYY-MM-DD HH:mm:ss') }}</span>
                        </template>
                        <template v-if="column.dataIndex === 'status'">
                            <span>{{ record.status == 'Success' ? '成功' : '失败' }}</span>
                        </template>
                        <template v-if="'action' === column.key">
                            <!-- <x-action-button @click="$refs.editDialogRef.handleEdit(record)">
                                <a-tooltip>
                                    <template #title> {{ $t('pages.system.user.edit') }}</template>
                <edit-outlined /> </a-tooltip></x-action-button> -->
                            <x-action-button @click="handleDelete(record)">
                                <a-tooltip>
                                    <template #title>{{ $t('pages.system.delete') }}</template>
                                    <delete-outlined style="color: #ff4d4f" /> </a-tooltip></x-action-button>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>

    <!-- <edit-dialog ref="editDialogRef" @ok="onOk"></edit-dialog> -->
</template>

<script setup>
import { message, Modal } from 'ant-design-vue'
import { reactive, ref } from 'vue'
import apis from '@/apis'
import { config } from '@/config'
import dayjs from 'dayjs'
import { usePagination } from '@/hooks'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'

defineOptions({
    name: 'owner',
})

const { t } = useI18n()

// 表格列定义
const columns = [
    { title: '用户姓名', dataIndex: 'customerName', width: 120, align: 'center' },
    { title: '用户联系方式', dataIndex: 'phone', width: 120, align: 'center' },
    { title: '信息内容', dataIndex: 'SMSContent', width: 300, align: 'center' },
    { title: '信息类型', dataIndex: 'smsType', width: 120, align: 'center' },
    { title: '发送状态', dataIndex: 'status', width: 120 },
    { title: '发送时间', dataIndex: 'sendAt', width: 120 },
]

// 使用 usePagination 获取分页相关逻辑（但不使用其 searchFormData）
const { listData, loading, showLoading, hideLoading, paginationState, resetPagination } = usePagination()

// ✅ 自己管理搜索表单数据：确保是可扩展的响应式对象
const searchFormData = reactive({
    customerName: '',
    phone: '',
    smsType: undefined,
    sendAtRange: [], // 始终为 [dayjs, dayjs] 或 []
})

/**
 * 获取表格数据
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const params = {
            pageSize,
            current,
            customerName: searchFormData.customerName || undefined,
            phone: searchFormData.phone || undefined,
            smsType: searchFormData.smsType || undefined,
        }

        // ✅ 修改：将时间范围合并为 created_at 数组
        if (searchFormData.sendAtRange?.length === 2) {
            const [start, end] = searchFormData.sendAtRange
            params.send_start = start.format('YYYY-MM-DD HH:mm:ss')
            params.send_at = end.format('YYYY-MM-DD HH:mm:ss') // 注意：这里用 send_at 作为结束时间
        } else {
            params.send_start = undefined
            params.send_at = undefined
        }

        const { success, data, total } = await apis.message.getSmsLogsList(params)
        hideLoading()

        if (config('http.code.success') === success) {
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {
        hideLoading()
        console.error('获取短信日志失败:', error)
    }
}

/**
 * 删除记录
 */
function handleDelete({ id }) {
    Modal.confirm({
        title: t('pages.system.user.delTip'),
        content: t('button.confirm'),
        okText: t('button.confirm'),
        onOk: async () => {
            try {
                const { success } = await apis.customer.delHouseOwner(id)
                if (success === config('http.code.success')) {
                    message.success('删除成功')
                    await getPageList()
                } else {
                    message.error('删除失败')
                }
            } catch (error) {
                message.error('删除失败')
                throw error
            }
        },
    })
}

/**
 * 分页变化
 */
function onTableChange(pagination) {
    paginationState.current = pagination.current
    paginationState.pageSize = pagination.pageSize
    getPageList()
}

/**
 * 搜索
 */
function handleSearch() {
    resetPagination()
    getPageList()
}

/**
 * 重置搜索
 */
function handleResetSearch() {
    // 重置所有字段
    Object.assign(searchFormData, {
        customerName: '',
        phone: '',
        smsType: undefined,
        sendAtRange: [],
    })
    resetPagination()
    getPageList()
}

/**
 * 日期范围变化
 */
const handleDateRangeChange = (dates) => {
    // dates 是 [dayjs, dayjs] 或 null
    searchFormData.sendAtRange = dates || []
}

// 初始加载
getPageList()
</script>