<template>
      <x-search-bar class="mb-8-2">
        <template #default="{ gutter, colSpan }">
            <a-form :model="searchFormData" layout="inline">
                <a-row :gutter="gutter">
                    <a-col >
                        <a-form-item label="所属区域" name="areaId" style="width: 500px;">
                            <a-select v-model:value="searchFormData.areaId" allowClear>
                                <a-select-option :value="1">南通</a-select-option>
                                <a-select-option :value="2">盐城</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                     <a-col >
                        <a-form-item label="手机号" name="customerPhone" style="width: 500px;">
                            <a-input v-model:value="searchFormData.customerPhone"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col  >
                        <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">
                <div class="exportExcel"><a-button type="primary">
                        <a :href='config("http.apiBasic") + `/api/v1/apps/common/raffle/Atbrw2334D_FVadfyb435zr55q3?area_id=${searchFormData.areaId==undefined? -1 : searchFormData.areaId}`'>导出Excel</a></a-button>
                </div>
                <a-table :columns="columns" :data-source="listData" bordered="true" :loading="loading"
                    :pagination="paginationState" :scroll="{ x: 1000 }" @change="onTableChange">
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex === 'createdAt'">
                            <span>{{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm') }}</span>
                        </template>
                        <template v-if="column.dataIndex === 'status'">
                            <a-tag :color="getStatusColor(record.status)">
                                {{ getStatusText(record.status) }}
                            </a-tag>
                        </template>
                        <template v-if="'action' === column.key">
                            <x-action-button v-if="record.status === 'checking'" @click="handleEdit(record)">
                                <a-tooltip>
                                    <template #title> {{ '核销' }}</template>
                                    <FormOutlined />
                                </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>
</template>

<script setup>
import * as XLSX from "xlsx"; // 推荐用 xlsx 库导出 Excel
import { message, Modal } from 'ant-design-vue'
import { ref } from 'vue'
import apis from '@/apis'
import { config } from '@/config'
import { usePagination } from '@/hooks'
import { FormOutlined } from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'
import dayjs from 'dayjs'

defineOptions({
    name: 'lotteryOrders',
})
const { t } = useI18n() // 解构出t方法
const columns = [
    { title: '奖品名称', dataIndex: 'productName' },
    { title: '所属规则', dataIndex: 'raffleName', align: 'center' },
    { title: '中奖人', dataIndex: 'customerName', align: 'center' },
    { title: '客户手机号', dataIndex: 'customerPhone', align: 'center' },
    { title: '状态', dataIndex: 'status', align: 'center' },
    { title: '中奖时间', dataIndex: 'createdAt', width: 180, align: 'center' },
    { title: '操作', key: 'action', fixed: 'right', width: 100, align: 'center' },

]
const { listData, loading, showLoading, hideLoading, paginationState, resetPagination, searchFormData } = usePagination()
const editDialogRef = ref()
getPageList()

// 状态映射
const statusMap = {
    'success': '未中奖',
    'checked': '已核销',
    'checking': '待核销'
}

// 状态颜色映射
const statusColorMap = {
    'success': 'default',
    'checked': 'green',
    'checking': 'orange'
}

/**
 * 获取状态显示文本
 */
function getStatusText(status) {
    return statusMap[status] || status
}

/**
 * 获取状态颜色
 */
function getStatusColor(status) {
    return statusColorMap[status] || 'default'
}

/**
 * 获取表格数据
 * @returns {Promise<void>}
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const { success, data, total } = await apis.raffleProduct
            .getRaffleOrders({
                pageSize,
                current: current,
                ...searchFormData.value,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === success) {
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {
        hideLoading()
    }
}

/**
 * 删除
 */
function handleDelete({ id }) {
    Modal.confirm({
        title: t('pages.system.user.delTip'),
        content: t('button.confirm'),
        okText: t('button.confirm'),
        onOk: () => {
            return new Promise((resolve, reject) => {
                (async () => {
                    try {
                        const { success } = await apis.house.delItem(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success(t('component.message.success.delete'))
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}

/**
 * 核销
 */
async function handleEdit(record = {}) {
    try {
        const params = {
            ...record,
            status: 'checked',
        }

        const { success } = await apis.raffleProduct.updateProject(record.id, params)
        
        if (success) {
            message.success('核销成功')
            await getPageList()
        } else {
            message.error('核销失败')
        }
    } catch (error) {
        console.error('核销出错:', error)
        message.error('核销失败')
    }
}

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

/**
 * 搜索
 */
function handleSearch() {
    resetPagination()
    getPageList()
}
/**
 * 重置
 */
function handleResetSearch() {
    searchFormData.value = {}
    resetPagination()
    getPageList()
}
/**
 * 编辑完成
 */
async function onOk() {
    await getPageList()
}

async function exportExcel() {
    try {
        const response = await apis.raffleProduct.exportFile()

        // const url = window.URL.createObjectURL(new Blob([response]))
        // const link = document.createElement('a')
        // link.href = url
        // link.setAttribute('download', 'raffle_orders.xlsx') // 设置下载文件名
        // document.body.appendChild(link)
        // link.click()
        // document.body.removeChild(link)
        // window.URL.revokeObjectURL(url)
    } catch (error) {
        message.error('导出失败：' + (error.message || '未知错误'))
        console.error('导出文件出错:', error)
    }
}
</script>

<style lang="less" scoped>
.exportExcel {
    display: flex;
    flex-direction: row;
    justify-content: right;
    margin: 10px;
}
</style>