<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="address">
                                <a-input :placeholder="'请输入活动地址'" v-model:value="formData.address"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'活动开始时间'" name="startAt">
                                <a-date-picker v-model:value="formData.startAt"
                                    :show-time="{ format: 'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm"
                                    style="width: 100%;" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'活动结束时间'" name="endAt">
                                <a-date-picker v-model:value="formData.endAt"
                                    :show-time="{ format: 'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm"
                                    style="width: 100%;" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'报名截止时间'" name="endSignupAt">
                                <a-date-picker v-model:value="formData.endSignupAt"
                                    :show-time="{ format: 'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm"
                                    style="width: 100%;" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'活动限制人数'" name="maxSignupNum">
                                <a-input-number :placeholder="'请输入活动限制人数'" style="width: 100%;"
                                    v-model:value="formData.maxSignupNum"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'活动所需积分'" name="point">
                                <a-input-number :placeholder="'请输入活动所需积分'" style="width: 100%;"
                                    v-model:value="formData.point"></a-input-number>
                            </a-form-item>
                        </a-col>

                        <a-col :span="24">
                            <a-form-item :label="'活动详情'" name="content">
                                <a-textarea :placeholder="'请输入活动详情'" v-model:value="formData.content"
                                    style="width: 100%;" :rows="4"></a-textarea>
                            </a-form-item>
                        </a-col>

                        <a-col :span="12">
                            <a-form-item :label="'所属区域'" name="areaId">
                                <a-select ref="select" v-model:value="formData.areaId">
                                    <a-select-option v-for="item in areaEnum.getAll()" :value="item.value">{{
                                        item.name }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'状态'" name="status">
                                <a-radio-group v-model:value="formData.status" :options="[
                                    { label: '启用', value: 'enabled' },
                                    { label: '停用', value: 'disabled' },
                                ]"></a-radio-group>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'活动图片'" name="fileList">
                                <gx-upload v-model="formData.fileList" accept-types=".jpg,.png,.webp"
                                    :fileNumber="20" />
                            </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 GxUpload from '@/components/GxUpload/index.vue'
import { customersEnum, areaEnum } from "@/enums/useEnum"
import { spliceUrl } from "@/utils/util"
const emit = defineEmits(['ok'])
const { t } = useI18n() // 解构出t方法
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([])
formRules.value = {
    title: [{ required: true, message: '请输入活动名称' }],
    address: [{ required: true, message: '请输入活动地址' }],
    timeRange: [{
        required: true, message: '请选择活动时间', trigger: 'change', validator: (_, value) => {
            if (!value || !value.length) {
                return Promise.reject(new Error('请选择日期范围'));
            }
            const [start, end] = value;
            if (!start || !end) {
                return Promise.reject(new Error('日期范围必须完整'));
            }
            return Promise.resolve()
        }
    }],
    fileList: [{
        required: true, message: '请上传图片', trigger: 'change', validator: (_, value) => {
            if (!value || !value.length) {
                return Promise.reject(new Error('请上传图片'));
            }
            return Promise.resolve()
        }
    }],
    endAt: [{ required: true, message: '请选择活动结束时间', trigger: 'change' }],
    startAt: [{ required: true, message: '请选择活动开始时间', trigger: 'change' }],
    endSignupAt: [{ required: true, message: '请选择活动报名截止时间', trigger: 'change' }],
    maxSignupNum: [{ required: true, message: '请选择活动报名人数' }],
    points: [{ required: true, message: '请输入参加活动所需积分' }],
    content: [{ required: true, message: '请输入活动详情' }],
    address: [{ required: true, message: '请输入活动地址' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    areaId: [{ required: true, message: '请选择所属区域', trigger: 'change' }]
}

onBeforeMount(() => {
    formData.value.areaId = 1
})

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

/**
 * 编辑
 */
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 }
        formData.value.startAt = dayjs(data.startAt)
        formData.value.endAt = dayjs(data.endAt)
        formData.value.endSignupAt = dayjs(data.endSignupAt)

        if (data.images && data.images.length > 0) {
            formData.value.fileList = data.images.map(item => config('http.apiBasic') + item)
        }
    } catch (error) {
        message.error({ content: error.message })
        hideSpining()
    }

}
const uploadSuccess = (data) => {
    fileList.value.push(data)
}
/**
 * 确定
 */
function handleOk() {
    formRef.value.validateFields().then(async (values) => {
        try {
            showLoading()
            const params = {
                ...values,
                cover: spliceUrl(formData.value.fileList[0]),
                images: formData.value.fileList ? formData.value.fileList.map(item => spliceUrl(item)) : [],
                signupNum: formData.value.signupNum || 0,
            }
            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(() => {
                        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()
}
const onRangeChange = (value, dateString) => {
    console.log('value', value)
    console.log('Formatted Selected Time: ', dateString);
    formData.value.startAt = dayjs(dateString[0])
    formData.value.endAt = dayjs(dateString[1])
    console.log(formData.value)
};

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

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

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