<script setup>
import { ref, onMounted, reactive, computed } from "vue";
import ElementPlus from "element-plus";
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';
import moment from 'moment';
//变量
// 用户对象假的
const admin = ref({
    adminId: 1,
    name: '赵刚',
    area: '中国'
})
//活动表格数据
const tableData = ref([]);
//分页总条目
const total = ref(100);
// 搜索对象时间
const getTime = ref([]);
// 搜索对象活动
const activity = ref({});
//搜索对象
const getObj = ref({
    pageNum: 1,
    pageSize: 5,
})
// 添加对象
const addObj = ref({
    add: '',
})
// 删除
// 删除对象
const delObj = ref({});
//表格高度
const tableHeight = computed(function () {
    return (getObj.value.pageSize + 1) * 50 + 'px';
});

// 表单验证ref
const Ref = ref(null);

//方法
//搜索方法
const get = async function (val) {
    try {
        // 搜索参数页码赋值
        if (typeof val === 'number') {
            getObj.value.pageNum = val;
        }
        // 搜索参数时间赋值
        if (getTime.value != null) {
            if (getTime.value.startDate != '' && getTime.value.endDate != '') {
                activity.value.startDate = getTime.value[0];
                activity.value.endDate = getTime.value[1];
            }
        } else {
            activity.value.startDate = '';
            activity.value.endDate = '';
        }

        console.log('搜索参数', getObj.value);
        // 发送POST请求
        const result = await axios.post('http://192.168.8.93:10010/recharge/activity/select', { ...getObj.value, activity: { ...activity.value } });

        // 将响应结果存储到响应式数据中
        console.log('请求成功', result);
        // 存储表格数据
        tableData.value = result.data.data.list;
        console.log('tableData', tableData.value);
        // 存储分页总条目
        total.value = result.data.data.total;
        console.log('total', total.value);
    } catch (error) {
        console.log('请求失败', error);
        // 在这里可以处理错误逻辑，比如显示错误提示等
    }
}

// 重置
const reset = function () {
    getObj.value = {};
    getObj.value.pageNum = 1;
    getObj.value.pageSize = 5;
    getTime.value = {};
    activity.value = {};
}
//新增活动弹出框
const addActivityVisible = ref(false)
//打开新增活动弹出框
const openAddActivityVisible = function () {
    addActivityVisible.value = true
}
//关闭新增窗口弹出框
const closeAddActivityVisible = function () {
    addActivityVisible.value = false
}
//添加活动按钮
const addActicity = function () {
    //添加对象初始化操作
    addObj.value = {};
    addObj.value.adminId = admin.value.adminId;
    addObj.value.adminName = admin.value.name;
    addObj.value.dept = admin.value.area;
    addObj.value.freeGold = '0';
    addObj.value.rechargeRatio = 0;
    addObj.value.startTime = null;
    addObj.value.endTime = null;
    openAddActivityVisible();
}

// 添加确认
const add = async function () {
    Ref.value.validate(async (valid) => {
        if (valid) {
            try {
                console.log('添加对象', addObj.value);
                // 发送POST请求
                const result = await axios.post('http://192.168.8.93:10010/recharge/activity/add', addObj.value);

                // 将响应结果存储到响应式数据中
                console.log('请求成功', result);
                // 刷新表格数据
                get();
                // 关闭弹出框
                closeAddActivityVisible();
                //提示
                ElMessage({
                    type: 'success',
                    message: '活动添加成功！',
                })
            } catch (error) {
                console.log('请求失败', error);
                // 在这里可以处理错误逻辑，比如显示错误提示等
            }
        } else {
            //提示
            ElMessage({
                type: 'error',
                message: '请检查输入内容',
            })
        }

    })

}
// 删除=========================================================
// 删除按钮
const del = function (row) {
    delObj.value.activityId = row.activityId;
    console.log('delObj', delObj.value);
}
// 删除按钮的气泡弹出框确认按钮
const delConfirm = async function () {
    try {
        console.log('delObj', delObj.value);
        // 发送POST请求
        const result = await axios.post('http://192.168.8.93:10010/recharge/activity/edit', delObj.value);
        // 将响应结果存储到响应式数据中
        console.log('请求成功', result);
        // 刷新表格数据
        get();
    } catch (error) {
        console.log('请求失败', error);
        // 在这里可以处理错误逻辑，比如显示错误提示等
    }
}

// 表单验证
// 开始时间改变时，重新验证结束时间
const handleStartTimeChange = () => {
    Ref.value.validateField('endTime');
};
const checkFreeGoldRadio = function (rule, value, callback) {
    if (addObj.value.freeGold == 1) {
        if (value == '0' || value == null || value == '') {
            callback(new Error('请输入免费金币兑换比'))
        }else if(value<0||typeof value!='number') {
            callback(new Error('请输入正确的格式'));
        }
    } else {
        callback()
    }
}

const checkStartTime = function (rule, value, callback) {
    if (value <= new Date()) {
        callback(new Error('开始时间不能小于当前时间'))
    } else {
        callback()
    }
}

const checkEndTime = function (rule, value, callback) {
    if (value <= new Date()) {
        callback(new Error('结束时间不能小于当前时间'))
    } else if (value <= addObj.value.startTime) {
        callback(new Error('结束时间不能小于开始时间'))
    } else {
        callback()
    }
}
const rules = reactive({
    activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' },],
    freeGold: [{ required: true, message: '请选择是否赠送免费金币', trigger: 'blur' },],
    rechargeRatio: [{ validator: checkFreeGoldRadio, trigger: 'blur' },],
    startTime: [
        { required: true, message: '请选择开始时间', trigger: 'blur' },
        { validator: checkStartTime, trigger: 'blur' },
    ],
    endTime: [
        { required: true, message: '请选择结束时间', trigger: 'blur' },
        { validator: checkEndTime, trigger: 'blur' },
    ],
})

// 验证跳转输入框的数字是否合法
const checkNumber = function () {
    if (typeof parseInt(getObj.value.pageNum) === 'number') {
        console.log('总共有多少页' + Math.ceil(total.value / getObj.value.pageSize));
        if ((getObj.value.pageNum > 0) && (getObj.value.pageNum <= Math.ceil(total.value / getObj.value.pageSize))) {
            console.log('输入的数字合法');
            get();
        } else {
            //提示
            ElMessage({
                type: 'error',
                message: '请检查输入内容',
            })
        }
    } else {
        //提示
        ElMessage({
            type: 'error',
            message: '请检查输入内容',
        })
    }
}

// 挂载
onMounted(async function () {
    get();
})

</script>

<template>
    <el-row>
        <el-col>
            <el-card style="margin-bottom: 20px">
                <div class="head-card">
                    <div class="head-card-element">
                        <el-text class="mx-1" size="large">活动名称：</el-text>
                        <el-input v-model="activity.activityName" style="width: 240px" placeholder="请输入活动名称"
                            clearable />
                    </div>
                    <div class="head-card-element">
                        <el-text class="mx-1" size="large">添加时间：</el-text>
                        <el-date-picker v-model="getTime" type="daterange" range-separator="至" start-placeholder="起始时间"
                            end-placeholder="结束时间" />
                    </div>
                    <div class="head-card-btn">
                        <el-button @click="reset()">重置</el-button>
                        <el-button type="primary" @click="get()">查询</el-button>
                    </div>
                </div>
            </el-card>
        </el-col>
    </el-row>
    <el-row>
        <el-col>
            <el-card>
                <div>
                    <el-button plain @click="addActicity()"
                        style="color: #048EFB; border:1px solid #048EFB">新增活动</el-button>
                </div>
                <div>
                    <el-table :data="tableData" :height="tableHeight" style="width: 100%">
                        <el-table-column prop="activityName" label="活动名称" />
                        <el-table-column prop="startTime" label="开始时间" />
                        <el-table-column prop="endTime" label="结束时间" />
                        <el-table-column prop="rechargeRatio" label="免费兑换比">
                            <template #default="scope">
                                <span>{{ scope.row.rechargeRatio }}:1</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态">
                            <template #default="scope">
                                <span v-if="scope.row.status === 1">
                                    <div class="status">
                                        <span class="green-dot"></span>
                                        <span>进行中</span>
                                    </div>
                                </span>
                                <span v-if="scope.row.status === 0">
                                    <div class="status">
                                        <span class="red-dot"></span>
                                        <span>未开始</span>
                                    </div>
                                </span>
                                <span v-if="scope.row.status === 2">
                                    <div class="status">
                                        <span class="grey-dot"></span>
                                        <span>已结束</span>
                                    </div>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="添加人" />
                        <el-table-column prop="createTime" label="添加时间">
                            <template #default="scope">
                                {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="operation" label="操作">
                            <template #default="scope">
                                <el-popconfirm title="确定将此条活动删除吗？" @confirm="delConfirm">
                                    <template #reference>
                                        <el-button type="primary" text @click="del(scope.row)">
                                            删除
                                        </el-button>
                                    </template>
                                    <template #actions="{ confirm, cancel }">
                                        <el-button size="small" @click="cancel">取消</el-button>
                                        <el-button type="primary" size="small" @click="confirm">
                                            确定
                                        </el-button>
                                    </template>
                                </el-popconfirm>
                            </template>

                        </el-table-column>
                    </el-table>
                </div>

                <!-- 分页 -->
                <div class="pagination">
                    <el-pagination background :page-size="getObj.pageSize" layout="slot" :total="total">
                        <div>共{{ total }}条,每页 </div>
                        <el-select v-model="getObj.pageSize" class="page-size" @change="get()" style="width: 80px">
                            <el-option v-for="item in [5, 6, 7, 8, 9, 10]" :key="item" :label="item"
                                :value="item"></el-option>
                        </el-select>
                        <div> 条</div>
                    </el-pagination>
                    <el-pagination background layout="prev, pager, next, slot" :page-size="getObj.pageSize"
                        :total="total" :current-page="getObj.pageNum" @current-change="get">
                        <div>跳至</div>
                        <el-input v-model="getObj.pageNum" style="width: 40px;" @change="checkNumber" />
                        <div>页</div>
                    </el-pagination>
                </div>
            </el-card>
        </el-col>
    </el-row>

    <el-dialog v-model="addActivityVisible" title="新增活动" width="500" :before-close="closeAddActivityVisible">
        <template #footer>

            <el-form :model="addObj" ref="Ref" :rules="rules" label-width="auto" style="max-width: 600px">

                <el-form-item prop="activityName" label="活动名称:">
                    <el-input v-model="addObj.activityName" placeholder="请输入活动名称" style="width: 220px;" />
                </el-form-item>

                <el-form-item prop="freeGold" label="免费金币:">
                    <el-radio-group v-model="addObj.freeGold">
                        <el-radio value="0" @change="addObj.rechargeRatio = '0'">无赠送</el-radio>
                        <el-radio value="1">有赠送</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item prop="rechargeRatio" label="免费金币兑换比:">
                    <el-input v-model="addObj.rechargeRatio" :disabled="addObj.freeGold === '0' ? true : false"
                        placeholder="请输入" style="width: 80px;" />：1
                    <div style="color: grey;">(提示：当前规则每10新币可兑换1免费金币)</div>
                </el-form-item>

                <el-form-item prop="startTime" label="开始时间:">
                    <el-date-picker v-model="addObj.startTime" type="date" placeholder="请选择开始时间"
                        @change="handleStartTimeChange" />
                </el-form-item>

                <el-form-item prop="endTime" label="结束时间:">
                    <el-date-picker v-model="addObj.endTime" type="date" placeholder="请选择结束时间" />
                </el-form-item>

                <el-form-item prop="adminName" label="添加人:">
                    <el-input v-model="addObj.adminName" disabled style="width: 220px;" />
                </el-form-item>

            </el-form>

            <div class="dialog-footer">
                <el-button @click="closeAddActivityVisible">取消</el-button>
                <el-button type="primary" @click="add()">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
.pagination {
    display: flex;
}

.status {
    display: flex;
}

.head-card {
    display: flex;
}

.head-card-element {
    margin-right: 20px;
}

.head-card-btn {
    margin-left: auto;
}
</style>