<template>
    <a-modal :open="modal.open" :title="modal.title" :width="800" :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-tabs v-model:activeKey="activeKey">
                        <a-tab-pane key="1" tab="基本信息">
                            <a-row :gutter="12">
                                <a-col :span="24">
                                    <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="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="12">
                                    <a-form-item :label="'开始时间'" name="startAt">
                                        <a-date-picker :placeholder="'请选择开始时间'" v-model:value="formData.startAt"
                                            style="width: 100%;"></a-date-picker>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-item :label="'结束时间'" name="endAt">
                                        <a-date-picker :placeholder="'请选择结束时间'" v-model:value="formData.endAt"
                                            style="width: 100%;"></a-date-picker>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-item :label="'消耗积分'" name="price">
                                        <a-input-number :placeholder="'请输入消耗积分'" v-model:value="formData.price"
                                            style="width: 100%;"></a-input-number>
                                    </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="reason">
                                        <x-editor v-model="formData.reason" :uploadHandler="uploadHandler"
                                    :height="300"></x-editor>
                                        <!-- <a-input :placeholder="'请输入备注'" v-model:value="formData.reason"></a-input> -->
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </a-tab-pane>
                        <a-tab-pane key="2" tab="规则设置">
                            <div style="width: 100%;margin-bottom: 10px; display: flex;justify-content: flex-end;">
                                <a-button type="primary" @click="addLayout">
                                    <template #icon>
                                        <PlusOutlined />
                                    </template>
                                    规则
                                </a-button>
                            </div>
                            <div style="display: flex;justify-content: space-around;gap:20px;flex-wrap: wrap;">
                                <a-card hoverable style="flex: 1; min-width: calc(30% - 10px);"
                                    v-for="(child, index) of formData.roles" :key="index">
                                    <a-col :span="24">
                                        <a-form-item :label="'每周几'" name="weekday">
                                            <a-select ref="select" v-model:value="child.weekday">
                                                <a-select-option v-for="item in weekDays" :value="item.value">{{
                                                    item.name }}</a-select-option>
                                            </a-select>
                                        </a-form-item>
                                        <a-form-item :label="'开始时间'" name="startH">
                                            <div style="display: flex;justify-content: space-around;">
                                            <a-select ref="select" v-model:value="child.startH">
                                                <a-select-option v-for="item in hoursArray" :value="item.value">{{
                                                    item.name }}</a-select-option>
                                                     
                                            </a-select>
                                             <a-select ref="select" v-model:value="child.startM">
                                                <a-select-option v-for="item in minutesArray" :value="item.value">{{
                                                    item.name }}</a-select-option>
                                            </a-select>
                                            </div>
                                        </a-form-item>
                                        <a-form-item :label="'结束时间'" name="endTime">
                                            <div style="display: flex;justify-content: space-around;">
                                            <a-select ref="select" v-model:value="child.endH">
                                                <a-select-option v-for="item in hoursArray" :value="item.value">{{
                                                    item.name }}</a-select-option>
                                                     
                                            </a-select>
                                             <a-select ref="select" v-model:value="child.endM">
                                                <a-select-option v-for="item in minutesArray" :value="item.value">{{
                                                    item.name }}</a-select-option>
                                                     
                                            </a-select>
                                            </div>
                                        </a-form-item>
                                        <a-form-item :label="'是否激活'" name="isActive">
                                            <a-radio-group v-model:value="child.isActive" :options="[
                                                { label: '激活', value: true },
                                                { label: '停用', value: false },
                                            ]"></a-radio-group>
                                        </a-form-item>
                                    </a-col>
                                       <template #actions>
                                        <a-button type="text" @click="delLayOut(index)">删 除</a-button>
                                    </template>
                                </a-card>
                            </div>
                        </a-tab-pane>
                    </a-tabs>
                </a-card>
            </a-form>
        </a-spin>
    </a-modal>
</template>

<script setup>
import { ref, h, 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 { PlusOutlined, MinusOutlined, SettingOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs'
import { customersEnum, areaEnum } from "@/enums/useEnum"
import { spliceUrl,decryptString,encryptString } from "@/utils/util.js"
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 layImgList = []
const hoursArray = Array.from({ length: 24 }, (_, i) => ({
  value: i,
  name: i === 0 ? "24点" : `${i}点`
}));
const minutesArray = Array.from({ length: 60 }, (_, i) => ({
  value: i,
  name: `${i.toString().padStart(2, '0')}分`
}));
const activeKey = ref('1')
const weekDays = ref([
    { value: 1, name: '每周一' },
    { value: 2, name: '每周二' },
    { value: 3, name: '每周三' },
    { value: 4, name: '每周四' },
    { value: 5, name: '每周五' },
    { value: 6, name: '每周六' },
    { value: 7, name: '每周日' },
])
formRules.value = {
    areaId: { required: true, message: '请选择区域' },
    title: { required: true, message: '请输入楼盘名称' },
    price: { required: true, message: '请输入消耗积分' },
    startAt: { required: true, message: '请选择开始时间', trigger: 'change' },
    endAt: { required: true, message: '请选择结束时间' , trigger: 'change'},
    status: [{ required: true, message: '请输入状态', trigger: 'change' }],
    reason: [{ required: true, message: '请输入抽奖规则', trigger: 'change' }]
}

/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '新增规则',
    })
    formData.value.areaId = 1
    formData.value.status='enabled'
    formData.value.roles = [{ weekday:1, isActive: true, startH:1, startM:0,endH:0, endM:0 }]
}

/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: '编辑规则',
    })
    try {
        showSpining()
        const { data, success } = await apis.raffles.getItem(record.id).catch()
        if (!success) {
            hideModal()
            return
        }
        hideSpining()
        formData.value = {
            ...data,
            startAt:dayjs(data.startAt),
            endAt:dayjs(data.endAt),
            reason:decryptString(data.reason),
        }
    } catch (error) {
        message.error({ content: error.message })
        hideSpining()
    }

}
/**
 * 确定
 */
function handleOk() {
    formRef.value.validateFields().then(async (values) => {
        try {
            showLoading()
            const params = {
                ...values,
                  roles:formData.value.roles,
                  reason:encryptString(formData.value.reason),
            }
            let result = null
            switch (modal.value.type) {
                case 'create':
                    result = await apis.raffles.createProject(params).catch((error) => {
                        console.log("1111",error.message)
                        // throw new Error(error)
                    })
                    break
                case 'edit':

                    result = await apis.raffles.updateItem(formData.value.id, params).catch(() => {
                              console.log("2222",error.message)
                        // 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()
        })
}

// 在 setup 中添加这些方法
const updateLabel = (index, value) => {
    formData.value.labels[index] = value;
};

const addLabel = () => {
    formData.value.labels.push('');
};

const removeLabel = (index) => {
    formData.value.labels.splice(index, 1);
};
/**
 * 取消
 */
function handleCancel() {

    hideModal()
}

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

defineExpose({
    handleCreate,
    handleEdit,
})
//新增户型
const addLayout = () => {
    const params = { weekday:1, isActive: true, startH:1, startM:0,endH:0, endM:0 }
    formData.value.roles.push(params)
}
//新增顾问
const addAdviser = () => {
    const params = { adviserName: '', adviserPhone: '', adviserImg: [] }
    formData.value.advisers.push(params)
}
//删除户型
const delLayOut = (index) => {
    formData.value.roles.splice(index, 1)
}

const uploadHandler = async (file) => {
    const formData = new FormData();
    formData.append('file', file);
    const { data } = await apis.common.uploadImg(formData);
    return config('http.apiBasic') + data
}
</script>

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