<template>
    <x-search-bar class="mb-8-2">
        <template #default="{ gutter, colSpan }">
            <a-form :model="searchFormData" layout="inline">
                <a-row :gutter="12">
                    <a-col :span="12">
                        <a-form-item label="活动名称" name="name">
                            <a-select v-model:value="searchFormData.activityId">
                                <a-select-option v-for="item of activityList" :value="item.id">{{ item.title
                                    }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col class="align-right" :span="12">
                        <a-space>
                            <a-button @click="handleExport">导出文件</a-button>
                            <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">
                <!-- <x-action-bar class="mb-8-2">
                    <a-button type="primary" @click="$refs.editDialogRef.handleCreate()">
                        <template #icon>
                            <plus-outlined></plus-outlined>
                        </template>
                        新增活动
                    </a-button>
                </x-action-bar> -->
                <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>{{ record.createdAt && dayjs(record.createdAt).format('YYYY-MM-DD HH:mm') }}</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>
    <a-modal v-model:open="open" :title="type === 1 ? '活动图片' : '活动详情'" @ok="open = false">
        <template v-if="type === 1">
            <a-image v-if="imgList.length > 0" :width="200" v-for="item of imgList"
                :src="config('http.apiBasic') + item" />
            <span v-else>
                暂无图片
            </span>
        </template>
        <template v-else>
            <span>{{ content }}</span>
        </template>

    </a-modal>
</template>

<script setup>
import { message, Modal } from 'ant-design-vue'
import { ref } from 'vue'
import apis from '@/apis'
import { formatUtcDateTime } from '@/utils/util'
import { config } from '@/config'
import dayjs from 'dayjs'
import { usePagination } from '@/hooks'
import { customersEnum, areaEnum } from "@/enums/useEnum"
import { PlusOutlined, EditOutlined, DeleteOutlined, QrcodeOutlined } from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'
import axios from 'axios'
defineOptions({
    name: 'activityOrder',
})
const { t } = useI18n() // 解构出t方法
const open = ref(false)
const imgList = ref([])
const type = ref(1)

const columns = [
    { title: '活动名称', dataIndex: 'activityName' },
    { title: '客户姓名', dataIndex: 'customerName' },
    { title: '联系方式', dataIndex: 'customerPhone' },
    { title: '报名时间', dataIndex: 'createdAt', width: 150, align: 'center' },

    // { title: t('button.action'), key: 'action', fixed: 'right', width: 150, align: 'center' },
]
const activityList = ref([])
const { listData, loading, showLoading, hideLoading, paginationState, resetPagination, searchFormData } =
    usePagination()

const editDialogRef = ref()
getPageList()
getActiveList()
async function getActiveList() {
    try {
        showLoading()
        const { success, data } = await apis.activity
            .getProjectList({
                pageSize: 99,
                current: 1,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === success) {
            activityList.value = data.map(item => ({ id: item.id, title: item.title }))
        }
    } catch (error) {
        hideLoading()
    }
}
/**
 * 获取表格数据
 * @returns {Promise<void>}
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const { success, data, total } = await apis.activity
            .getActivityList({
                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.activity.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()
                    }
                })()
            })
        },
    })
}

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

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

/**
 * 下载文件
 */
async function handleExport() {
    try {
        const activityId = searchFormData.value.activityId
        if (!activityId) {
            message.warning('请选择活动')
            return
        }

        // 注意添加 { responseType: 'blob' }
        const response = await apis.activity.exportFile({ activityId })
        console.log(response)
        const url = window.URL.createObjectURL(new Blob([response]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'filename.xlsx') // 设置下载文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
    } catch (error) {
        // message.error('导出失败：' + (error.message || '未知错误'))
        // console.error('导出文件出错:', error)
    }
}
/**
 * 重置
 */
function handleResetSearch() {
    searchFormData.value = {}
    resetPagination()
    getPageList()
}
/**
 * 编辑完成
 */
async function onOk() {
    await getPageList()
}
</script>

<style lang="less" scoped></style>
