<template>
    <x-search-bar class="mb-24-2">
        <template #default="{ gutter, colSpan }">
            <a-form :model="searchFormData" layout="inline">
                <a-row :gutter="gutter">
                    <a-col v-bind="colSpan">
                        <a-form-item label="用户名" name="name">
                            <a-input placeholder="请输入用户名" v-model:value="searchFormData.name"></a-input>
                        </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-input>
                        </a-form-item>
                    </a-col>
                    <a-col v-bind="colSpan">
                        <a-form-item label="身份证号" name="iDCard">
                            <a-input placeholder="请输入身份证号" v-model:value="searchFormData.iDCard"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col v-bind="colSpan">
                        <a-form-item label="住址" name="address">
                            <a-input placeholder="请输入住址" v-model:value="searchFormData.address"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col class="align-right" v-bind="colSpan">
                        <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">
                <a-table :columns="columns" :data-source="listData" bordered="true" :loading="loading"
                    :pagination="paginationState" @change="onTableChange">
                    <template #bodyCell="{ column, record }">
                        <template v-if="'createdAt' === column.dataIndex">
                            {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
                        </template>
                        <template v-if="'ActivityCover' === column.dataIndex">
                            <a-image :width="60"
                                :src="record.ActivityCover ? config('http.apiBasic') + record.ActivityCover : errImg" />
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>
    <a-modal v-model:open="open" :title="'审核'" @ok="handleClick">
        <a-card class="mb-8-2">

            <a-form-item label="审核" name="">
                <a-radio-group v-model:value="auditStatus">
                    <a-radio :value="2">通过</a-radio>
                    <a-radio :value="99">不通过</a-radio>
                </a-radio-group>
            </a-form-item>

            <a-form-item label="备注" name="">
                <a-textarea :placeholder="'请输入审核备注'" v-model:value="remark"
                    :auto-size="{ minRows: 2, maxRows: 5 }"></a-textarea>
            </a-form-item>

        </a-card>
    </a-modal>
    <a-modal v-model:open="imgOpen" :title="'图片/视频'" @ok="imgOpen = false">
        <a-card class="mb-8-2">
            <a-form-item :label="'图片'" name="images">
                <template v-if="currentInfo.images && currentInfo.images.length > 0">
                    <a-image-preview-group>
                        <a-image v-for="item in currentInfo.images" :width="200"
                            :src="config('http.apiBasic') + item" />
                    </a-image-preview-group>
                </template>
                <template v-else>暂无</template>

            </a-form-item>
            <a-form-item label="视频" name="video">
                <template v-if="currentInfo.videos && currentInfo.videos.length > 0">
                    <video width="320" height="240" controls>
                        <source v-for="item in currentInfo.videos" :src="config('http.apiBasic') + item">
                    </video>
                </template>
                <template>暂无</template>
            </a-form-item>
        </a-card>
    </a-modal>
</template>

<script setup>
import { message, Modal } from 'ant-design-vue'
import { ref } from 'vue'
import apis from '@/apis'
import { config } from '@/config'
import { usePagination } from '@/hooks'
import dayjs from 'dayjs'
import EditDialog from './components/EditDialog.vue'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'
import { orderStatus } from '@/enums/index.js'
import { status } from 'nprogress'
defineOptions({
    name: 'orderList',
})
const { t } = useI18n() // 解构出t方法
const columns = [
    { title: '用户名', dataIndex: 'name' },
    { title: '身份证号', dataIndex: 'iDCard' },
    { title: '联系电话', dataIndex: 'phone' },
    { title: '联系地址', dataIndex: 'address', width: 300 },
    { title: '报名时间', dataIndex: 'createdAt', width: 300 },

]
const { listData, loading, showLoading, hideLoading, paginationState, resetPagination, searchFormData } = usePagination()
const remark = ref('')
const currentInfo = ref({})
const auditStatus = ref(2)
const editDialogRef = ref()
const open = ref(false)
const imgOpen = ref(false)
const activityList = ref([])

getPageList()
getActiveList()
/**
 * 获取活动报名列表
 * @returns {Promise<void>}
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const { success, data, total } = await apis.vote
            .getElectionList({
                pageSize,
                current: current,
                ...searchFormData.value,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === success) {
            listData.value = data.map(item => ({
                ...item,
                key: item.value,
            }))
            paginationState.total = total
        }
    } catch (error) {
        hideLoading()
    }
}
// 获取活动列表
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()
    }
}
/**
 * 下载文件
 */
async function handleExport() {
    try {
        const response = await apis.vote.exportFile()
        console.log(response)
        const url = window.URL.createObjectURL(new Blob([response]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '报名表.xlsx') // 设置下载文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
    } catch (error) {
        message.error('导出失败：' + (error.message || '未知错误'))
        console.error('导出文件出错:', error)
    }
}
const handleClick = async () => {
    try {
        const params = {
            ...currentInfo.value,
            status: auditStatus.value,
            remark: remark.value
        }
        const result = await apis.orderList.updateMenu(currentInfo.value.id, params).catch(() => {
            throw new Error(error)
        })
        if (config('http.code.success') === result?.success) {
            message.success('已审核')
            open.value = false
            getPageList()
        }
    } catch (error) {
        message.error({ content: error.message })
        hideLoading()
    }
}
/**
 * 删除
 */
function handleDelete(value) {
    Modal.confirm({
        title: '确定撤销该工单吗',
        content: t('button.confirm'),
        okText: t('button.confirm'),
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const params = {
                            ...value,
                            status: 98
                        }
                        console.log(params)
                        const { success } = await apis.orderList.updateMenu(value.id, params).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success('撤销成功')
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}

/**
 * 分页
 */
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()
}
</script>

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