<template>
    <a-modal :open="modal.open" :title="modal.title" :width="640" :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" :cancel-text="cancelText" :ok-text="okText" @ok="handleOk" @cancel="handleCancel">
        <a-spin :spinning="spining">
            <a-form ref="formRef" :model="formData" :rules="formRules">
                <a-card class="mb-8-2">
                    <a-row :gutter="12">
                        <a-col :span="24">
                            <a-form-item :label="'活动标题'" name="title">
                                <a-input :placeholder="'请输入活动标题'" v-model:value="formData.title"></a-input>
                            </a-form-item>
                        </a-col>

                        <a-col :span="24">
                            <a-form-item :label="'活动内容'" name="content">
                                <x-editor v-model="formData.content"></x-editor>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'报名截止时间'" name="endSignupAt">
                                <a-date-picker 
                                    v-model:value="formData.endSignupAt" 
                                    placeholder="请输入报名截止时间"
                                    style="width: 100%;"
                                    show-time
                                    :format="displayFormat"
                                    :value-format="valueFormat"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="活动开始时间" name="startAt">
                                <a-date-picker 
                                    v-model:value="formData.startAt" 
                                    placeholder="请选择活动开始时间"
                                    style="width: 100%;"
                                    show-time
                                    :format="displayFormat"
                                    :value-format="valueFormat"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="活动结束时间" name="endAt">
                                <a-date-picker 
                                    v-model:value="formData.endAt" 
                                    placeholder="请选择活动结束时间"
                                    style="width: 100%;"
                                    show-time
                                    :format="displayFormat"
                                    :value-format="valueFormat"
                                />
                            </a-form-item>
                        </a-col>
                        <a-form-item :label="'活动报名人数'" name="maxSignupNum">
                            <a-input-number :min="0" :placeholder="'请输入报名人数'" v-model:value="formData.maxSignupNum"
                                style="width: 100%" />
                        </a-form-item>

                        <a-col :span="24">
                            <a-form-item :label="'状态'" name="status">
                                <a-radio-group v-model:value="formData.status" :options="activatyStatus.getAll()"
                                    disabled></a-radio-group>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'活动图片'" name="cover">
                                <gx-upload v-model="formData.cover" accept-types=".jpg,.png,.webp" :fileNumber="1" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'背景图片'" name="images">
                                <gx-upload v-model="formData.images" accept-types=".jpg,.png,.webp" :fileNumber="1" />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-card>
            </a-form>
        </a-spin>
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, onBeforeMount } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal, useSpining } from '@/hooks'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import GxUpload from '@/components/GxUpload/index.vue'
import { spliceUrl } from "@/utils/util"
import { activatyStatus } from '@/enums/index'

// 扩展dayjs的时区功能
dayjs.extend(utc)
dayjs.extend(timezone)

const emit = defineEmits(['ok'])
const { t } = useI18n()
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
const { spining, showSpining, hideSpining } = useSpining()
const cancelText = ref(t('button.cancel'))
const okText = ref(t('button.confirm'))
const fileList = ref([])

// 显示格式 - 用户界面展示的格式
const displayFormat = 'YYYY-MM-DD HH:mm:ss'
// 值格式 - 传给后台的格式，符合2006-01-02T15:04:05Z07:00
const valueFormat = 'YYYY-MM-DDTHH:mm:ssZ'

formRules.value = {
    title: [{ required: true, message: '请输入活动名称' }],
    openAt: [{ required: true, message: '请输入活动时间' }],
    cover: [{ required: false, message: '请上传图片', trigger: 'change' }],
    images: [{ required: false, message: '请上传图片', trigger: 'change' }],
    endSignupAt: [{ required: true, message: '请选择报名截止时间', trigger: 'change' }],
    startAt: [{ required: true, message: '请选择活动开始时间', trigger: 'change' }],
    endAt: [{ required: true, message: '请选择活动结束时间', trigger: 'change' }],
    activityContent: [{ required: true, message: '请输入活动内容' }]
}

onBeforeMount(() => {
    // Initialize if needed
})

/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '新增活动',
    })
    formData.value.status = 1
    formData.value.maxSignupNum = 0
}

/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: '编辑活动',
    })
    try {
        showSpining()
        const { data, success } = await apis.activity.getItem(record.id).catch()
        if (!success) {
            hideModal()
            return
        }
        hideSpining()
        
        // 转换后端时间格式为组件需要的格式
        formData.value = { 
            ...data,
            // 确保时间格式正确解析
            endSignupAt: data.endSignupAt ? dayjs(data.endSignupAt) : null,
            startAt: data.startAt ? dayjs(data.startAt) : null,
            endAt: data.endAt ? dayjs(data.endAt) : null
        }
        
        if (data.images && data.images.length > 0) {
            formData.value.images = data.images.map( item => config('http.apiBasic') + item)
        } else {
            formData.value.images = []
        }
        if (data.cover) {
            formData.value.cover = [config('http.apiBasic') + data.cover]
        } else {
            formData.value.cover = []
        }
    } catch (error) {
        message.error({ content: error.message })
        hideSpining()
    }
}

/**
 * 确定
 */
function handleOk() {
    formRef.value.validateFields().then(async (values) => {
        try {
            showLoading()
            
            // 处理时间格式，确保符合要求
            const formatTime = (timeStr) => {
                if (!timeStr) return null;
                // 确保时间字符串正确转换为所需格式
                return dayjs(timeStr).format(valueFormat);
            };
            
            const params = {
                ...values,
                maxSignupNum: parseInt(values.maxSignupNum) || 0,
                cover: formData.value.cover ? spliceUrl(formData.value.cover[0]) : '',
                images: formData.value.images ? formData.value.images.map(item => spliceUrl(item)) : [],
                signupNum: formData.value.signupNum || 0,
                status: 1,
                // 使用格式化后的时间
                endSignupAt: formatTime(values.endSignupAt),
                startAt: formatTime(values.startAt),
                endAt: formatTime(values.endAt)
            }
            
            let result = null
            switch (modal.value.type) {
                case 'create':
                    result = await apis.activity.createProject(params).catch((error) => {
                        throw new Error(error)
                    })
                    break
                case 'edit':
                    result = await apis.activity.updateItem(formData.value.id, params).catch((error) => {
                        throw new Error(error)
                    })
                    break
            }
            hideLoading()
            if (config('http.code.success') === result?.success) {
                hideModal()
                emit('ok')
            }
        } catch (error) {
            message.error({ content: error.message })
            hideLoading()
        }
    })
    .catch((e) => {
        hideLoading()
    })
}

/**
 * 取消
 */
function handleCancel() {
    formData.value.areaId = 1
    hideModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    resetForm()
    hideLoading()
}

defineExpose({
    handleCreate,
    handleEdit,
})
</script>

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