<template>
    <el-card class="card1" style="margin-bottom: 1vh;">
        <div class="condition">
            <div class="condition-item">
                <el-text size="large" class="label-text">{{ t('common.activityName') }}：</el-text>
                <el-input v-model="searchForm.activityName" class="input-width" :placeholder="t('common.activityNamePlaceholder')" clearable />
            </div>
            <div class="condition-item">
                <el-text size="large" class="label-text">{{ t('common.type') }}：</el-text>
                <!-- <el-cascader v-model="searchForm.businessBelong" :options="marketOptions" placeholder="请选择所属地区" clearable
                style="width: 10vw" /> -->
                <el-select v-model="searchForm.businessBelong" :placeholder="t('common.typePlaceholder')" class="input-width" clearable>
                    <el-option :label="t('common.customerBelong')" value="客户归属地" />
                    <el-option :label="t('common.activityBelong')" value="活动归属地" />
                </el-select>
            </div>
            <div class="condition-item">
                <el-text size="large" class="label-text">{{ t('common.startTime') }}：</el-text>
                <el-date-picker v-model="searchForm.startTime" type="datetime" :placeholder="t('common.startTime')"
                    format="YYYY-MM-DD HH:mm:ss" :default-time="defaultStartTime" class="input-width" clearable />
            </div>
            <div class="condition-item">
                <el-text size="large" class="label-text">{{ t('common.endTime') }}：</el-text>
                <el-date-picker v-model="searchForm.endTime" type="datetime" :placeholder="t('common.endTime')"
                    format="YYYY-MM-DD HH:mm:ss" :default-time="defaultEndTime" class="input-width" clearable />
            </div>
            <div class="condition-buttons">
                <el-button type="primary" @click="getActivity">{{ t('common.search') }}</el-button>
                <el-button type="success" @click="reset">{{ t('common.reset') }}</el-button>
            </div>
        </div>
    </el-card>



    <el-card class="card2">
        <div class="add-item">
            <el-button type="success" @click="showAdd = true">{{ t('common.addActivity') }}</el-button>
        </div>
        <div>
            <el-table :data="tableData" style="width: 82vw;height:70vh;" :row-style="{ height: '50px' }">
                <el-table-column type="index" :label="t('common_list.id')" width="100px" fixed="left">
                    <template #default="scope">
                        <span>{{ scope.$index + 1 + (pagination.pageNum - 1) * pagination.pageSize }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="activityName" :label="t('common_list.activity')" width="150px" show-overflow-tooltip />
                <el-table-column prop="businessBelong" :label="t('common_list.businessBelong')" width="150px" />
                <el-table-column prop="areaName" :label="t('common_list.market')" width="150px" />
                <el-table-column prop="startTime" :label="t('common_list.startTime')" width="200px">
                    <template #default="scope">
                        {{ moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </el-table-column>
                <el-table-column prop="endTime" :label="t('common_list.endTime')" width="200px">
                    <template #default="scope">
                        {{
                            moment(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss')
                        }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" :label="t('common_list.status')" width="150px">
                    <template #default="scope">
                        {{ getActivityStatusText(scope.row.status) }}
                    </template>
                </el-table-column>
                <el-table-column prop="creatorName" :label="t('common_list.creator')" width="150px" />
                <el-table-column prop="operation" :label="t('common_list.operation')" width="220px">
                    <template #default="scope">
                        <el-button type="primary" text @click="editOpen(scope.row)">{{ t('common.edit') }}</el-button>
                        <!-- <el-button type="danger" text @click="openDel(scope.row)">删除</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div style="margin-top: 20px;display: flex;">
            <el-pagination background v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" style="margin-top: 1vh;"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </el-card>

    <el-dialog v-model="showAdd" width="20vw" draggable align-center style="background-color: rgb(243,250,254);">
        <div class="add-item">
            <el-text size="large">{{ t('common_add.activity') }}：</el-text>
            <el-input v-model="addForm.activityName" style="width: 12vw" :placeholder="t('common_add.activityPlaceholder')" maxlength="200" clearable />
        </div>
        <div class="add-item">
            <el-text size="large">{{ t('common_add.businessBelong') }}：</el-text>
            <el-radio-group v-model="addForm.businessBelong" style="width: 12vw">
                <el-radio size="large" value="客户归属地">{{ t('common.customerBelong') }}</el-radio>
                <el-radio size="large" value="活动归属地">{{ t('common.activityBelong') }}</el-radio>
            </el-radio-group>
        </div>
        <div class="add-item" v-show="addForm.businessBelong === '活动归属地'">
            <el-text size="large">{{ t('common_add.market') }}：</el-text>
            <el-cascader v-model="addForm.area" :options="marketOptions" :placeholder="t('common_add.marketPlaceholder')" clearable
                style="width: 12vw" />
        </div>
        <div class="add-item">
            <el-text size="large">{{ t('common_add.startTime') }}：</el-text>
            <el-date-picker v-model="addForm.startTime" type="datetime" :placeholder="t('common_add.startTime')"
                :default-time="defaultStartTime" style="width: 12vw" />
        </div>
        <div class="add-item">
            <el-text size="large">{{ t('common_add.endTime') }}：</el-text>
            <el-date-picker v-model="addForm.endTime" type="datetime" :placeholder="t('common_add.endTime')"
                :default-time="defaultEndTime" style="width: 12vw" />
        </div>
        <div style="display: flex; justify-content: center; margin-top: 5vh;">
            <el-button type="primary" @click="hideAdd">{{ t('common.cancel') }}</el-button>
            <el-button type="primary" @click="throttleGetActivity">{{ t('common.confirm') }}</el-button>
        </div>
    </el-dialog>

    <el-dialog v-model="showEdit" width="20vw" draggable align-center style="background-color: rgb(243,250,254);">
        <div class="edit-item">
            <el-text size="large">{{ t('common_add.activity') }}：</el-text>
            <el-input v-model="editForm.activityName" style="width: 12vw" :placeholder="t('common_add.activityPlaceholder')" maxlength="200" clearable />
        </div>

        <div class="edit-item">
            <el-text size="large">{{ t('common_add.businessBelong') }}：</el-text>
            <el-radio-group v-model="editForm.businessBelong" style="width: 12vw">
                <el-radio size="large" value="客户归属地">{{ t('common.customerBelong') }}</el-radio>
                <el-radio size="large" value="活动归属地">{{ t('common.activityBelong') }}</el-radio>
            </el-radio-group>
        </div>
        <div class="edit-item" v-show="editForm.businessBelong === '活动归属地'">
            <el-text size="large">{{ t('common_add.market') }}：</el-text>
            <el-cascader v-model="editForm.area" :options="marketOptions" :placeholder="t('common_add.marketPlaceholder')" clearable
                style="width: 12vw" />
        </div>
        <div class="edit-item">
            <el-text size="large">{{ t('common_add.startTime') }}：</el-text>
            <el-date-picker v-model="editForm.startTime" type="datetime" :placeholder="t('common_add.startTime')"
                :default-time="defaultStartTime" style="width: 12vw" />
        </div>
        <div class="edit-item">
            <el-text size="large">{{ t('common_add.endTime') }}：</el-text>
            <el-date-picker v-model="editForm.endTime" type="datetime" :placeholder="t('common_add.endTime')"
                :default-time="defaultEndTime" style="width: 12vw" />
        </div>
        <div style="display: flex; justify-content: center; margin-top: 5vh;">
            <el-button type="primary" @click="hideEdit">{{ t('common.cancel') }}</el-button>
            <el-button type="primary" @click="handleEdit">{{ t('common.confirm') }}</el-button>
        </div>
    </el-dialog>

    <ConfirmDialog v-model="showDel" :message="t('common.deleteActivityRecord')" @confirm="handleDel()" @cancel="hideDel" @close="hideDel" />
</template>
<script setup>
import { ElMessage, ElPagination } from 'element-plus';
import { onMounted, ref } from 'vue'
import API from "@/util/http.js"
import moment from 'moment'
import { useAdminStore } from "@/store/index.js"
import { storeToRefs } from "pinia"
import { permissionMapping, hasMenuPermission } from "@/utils/menuTreePermission.js"
const adminStore = useAdminStore();
const { adminData, menuTree } = storeToRefs(adminStore)
import ConfirmDialog from '@/components/dialogs/ConfirmDialog.vue'
import _ from 'lodash'
// 国际化
import { useI18n } from 'vue-i18n';
const {t} = useI18n();

const getActivityStatusText = (status) => {
    if (status === '0') return t('common_list.activityStatus.notStarted')
    if (status === '1') return t('common_list.activityStatus.inProgress')
    if (status === '2') return t('common_list.activityStatus.ended')
    return status
}

const activityNameReg = /^[\u4e00-\u9fa5a-zA-Z0-9，。！？、；：“”（）‘’《》【】{}——~,.!?:;'()\[\]_&+=\/-]+$/;
const tableData = ref([])
const pagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
const searchForm = ref({
    activityName: ''
})
const showAdd = ref(false)
const showEdit = ref(false)
const showDel = ref(false)
const currentDelRow = ref(null)
const addForm = ref({
    activityName: '',
    area: []
})
const editForm = ref({
    activityName: '',
    businessBelong: '',
    area: [],
    startTime: null,
    endTime: null,
    id: ''
})
const marketOptions = ref([])
const getActivity = async function () {
    if (!hasMenuPermission(menuTree.value,permissionMapping.view_activity)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    const rechargeActivity = {
        activityName: searchForm.value.activityName,
        businessBelong: searchForm.value.businessBelong,
    }
    if (searchForm.value.startTime && moment(searchForm.value.startTime).isValid()) {
        rechargeActivity.startTime = moment(searchForm.value.startTime).format('YYYY-MM-DD HH:mm:ss');
    }

    if (searchForm.value.endTime && moment(searchForm.value.endTime).isValid()) {
        rechargeActivity.endTime = moment(searchForm.value.endTime).format('YYYY-MM-DD HH:mm:ss');
    }
    const params = {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        rechargeActivity
    }
    const res = await API({
        url: '/admin/coin/rechargeActivityCenter/queryActivity',
        data: params
    })
    if (res.code === 200) {
        tableData.value = res.data.list
        pagination.value.total = res.data.total
    }
}
const handleAdd = async function () {
    if (!hasMenuPermission(menuTree.value,permissionMapping.add_activity)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    const activityName = addForm.value.activityName
    if (!validateActivityName(activityName)) return

    if (!addForm.value.businessBelong) {
        ElMessage.error(t('elmessage.selectBusinessBelong'))
        return
    }
    if (addForm.value.businessBelong === '活动归属地' && addForm.value.area.length === 0) {
        ElMessage.error(t('elmessage.selectMarket'))
        return
    }
    if (!addForm.value.startTime) {
        ElMessage.error(t('elmessage.selectStartTime'))
        return
    }
    if (!addForm.value.endTime) {
        ElMessage.error(t('elmessage.selectEndTime'))
        return
    }
    if (addForm.value.businessBelong === '客户归属地') {
        addForm.value.area = []
    }

    const params = {
        activityName: addForm.value.activityName,
        businessBelong: addForm.value.businessBelong,
        area: addForm.value.area.length > 0 ? addForm.value.area.slice(-1)[0] : null,
        startTime: moment(addForm.value.startTime).format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(addForm.value.endTime).format('YYYY-MM-DD HH:mm:ss'),
        creator: adminData.value.id
    }

    const res = await API({
        url: '/admin/coin/rechargeActivityCenter/addActivity',
        data: params
    })
    if (res.code === 200) {
        ElMessage.success(t('elmessage.addSuccess'))
        getActivity()
        hideAdd()
        addForm.value = {
            activityName: '',
            businessBelong: '',
            area: [],
            startTime: null,
            endTime: null,
        }
    } else {
        ElMessage.error(res.msg || t('elmessage.addFailed'))
        return
    }
}
// 新增节流
const throttleGetActivity = _.throttle(handleAdd, 5000, { trailing: false });
const handleEdit = async function () {
    if (!hasMenuPermission(menuTree.value,permissionMapping.edit_activity)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    const activityName = editForm.value.activityName
    if (!validateActivityName(activityName)) return

    if (!editForm.value.activityName) {
        ElMessage.error(t('elmessage.checkActivity'))
        return
    }
    if (!editForm.value.businessBelong) {
        ElMessage.error(t('elmessage.selectBusinessBelong'))
        return
    }
    if (editForm.value.businessBelong === '活动归属地' && editForm.value.area.length === 0) {
        ElMessage.error(t('elmessage.selectMarket'))
        return
    }
    if (!editForm.value.startTime) {
        ElMessage.error(t('elmessage.selectStartTime'))
        return
    }
    if (!editForm.value.endTime) {
        ElMessage.error(t('elmessage.selectEndTime'))
        return
    }

    if(editForm.value.businessBelong === '客户归属地'){
        editForm.value.area = []
    }

    const params = {
        id: editForm.value.id,
        activityName: editForm.value.activityName,
        businessBelong: editForm.value.businessBelong,
        area: editForm.value.area.length > 0 ? editForm.value.area.slice(-1)[0] : null,
        startTime: moment(editForm.value.startTime).format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(editForm.value.endTime).format('YYYY-MM-DD HH:mm:ss'),
        creator: adminData.value.id
    }
    console.log('看看修改params', params)
    const res = await API({
        url: '/admin/coin/rechargeActivityCenter/updateActivity',
        data: params
    })
    if (res.code === 200) {
        ElMessage.success(t('elmessage.editSuccess'))
        getActivity()
        hideEdit()
    }
}
const handleDel = async function (row) {
    if (!hasMenuPermission(menuTree.value,permissionMapping.delete_activity)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    if (!currentDelRow.value) {
        ElMessage.error(t('elmessage.currentSelectionEmpty'))
        return
    }
    const res = await API({
        url: '/admin/coin/rechargeActivityCenter/deleteActivity',
        data: {
            id: currentDelRow.value.id,
        }
    })
    if (res.code === 200) {
        ElMessage.success(t('elmessage.deleteSuccess'))
        getActivity()
        showDel.value = false
    }
}
const getmarkets = async function () {
    try {
        const result = await API({
            url: '/market/selectMarket',
        });
        console.log('请求成功', result)
        // 递归转换树形结构为级联选择器需要的格式（跳过第一级节点）
        const transformTree = (nodes) => {
            // 直接处理第一级节点的子节点
            const allChildren = nodes.flatMap(node => node.children || []);
            return allChildren.map(child => {
                const grandchildren = child.children && child.children.length
                    ? transformTree([child]) // 递归处理子节点
                    : null;
                return {
                    value: child.id,
                    label: child.name,
                    children: grandchildren
                }
            })
        }
        marketOptions.value = transformTree(result.data)
        console.log('转换后的地区树', marketOptions.value)
    } catch (error) {
        console.log('请求失败', error)
    }
}
const defaultStartTime = [
    new Date(2000, 1, 1, 0, 0, 0)
]
const defaultEndTime = [
    new Date(2000, 2, 1, 23, 59, 59)
]
const hideEdit = () => {
    showEdit.value = false
    editForm.value = {
        activityName: '',
        businessBelong: '',
        area: [],
        startTime: null,
        endTime: null,
        id: ''
    }
}
const editOpen = (row) => {
    editForm.value = {
        id: row.id,
        activityName: row.activityName,
        businessBelong: row.businessBelong,
        area: row.area ? [...row.area] : []
    }

    if (row.startTime) {
        editForm.value.startTime = moment(row.startTime).toDate()
    }
    if (row.endTime) {
        editForm.value.endTime = moment(row.endTime).toDate()
    }
    console.log('看看editForm', editForm.value)
    showEdit.value = true
}
const openDel = (row) => {
    currentDelRow.value = row
    showDel.value = true
}
const hideDel = () => {
    showDel.value = false
    currentDelRow.value = null
}
const reset = () => {
    searchForm.value = {
        activityName: '',
        businessBelong: '',
        startTime: null,
        endTime: null
    }
    getActivity()
}
const hideAdd = () => {
    showAdd.value = false
    addForm.value = {
        activityName: '',
        area: [],
        startTime: null,
        endTime: null
    }
}
const validateActivityName = (name) => {
    const value = name.trim()
    // 非空校验
    if (!value) {
        ElMessage.error('活动名称不能为空');
        return false;
    }
    // 长度校验（限制100字符）
    if (value.length > 100) {
        ElMessage.error('活动名称长度不能超过100字符');
        return false;
    }
    // 字符格式校验
    if (!activityNameReg.test(value)) {
        ElMessage.error('活动名称仅支持汉字、英文字母、数字及常见标点，中文字符，。！？、；：“ ” ‘ ’ （）《》【】——～，英文字符, . ! ? : ;  " ( ) [ ] - _ & + =/')
        return false;
    }
    return true;
};
const handleSizeChange = function (val) {
    pagination.pageSize = val
    getActivity()
}
const handleCurrentChange = function (val) {
    pagination.pageNum = val
    getActivity()
}
onMounted(() => {
    getActivity()
    getmarkets()
    console.log('看看adminData', adminData.value)
})
</script>
<style scoped lang="scss">
// 搜索的卡片样式
.card1 {
    background: #F3FAFE;
}

// 表单的卡片样式
.card2 {
    background: #E7F4FD;
}

// 表头背景等
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
/* 表格 */
:deep(.el-table__body td) {
    background-color: #F3FAFE !important;
}

/* 表头 */
:deep(.el-table__header th) {
    background-color: #F3FAFE !important;
}

/* 鼠标悬停 */
:deep(.el-table__row:hover > .el-table__cell) {
    background-color: #E5EBFE !important;
}

.condition {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.condition-item {
    display: flex;
    align-items: center;
    margin-right: 10px;
}

.label-text {
    white-space: nowrap;
}

.input-width {
    width: 160px;
}

.condition-buttons {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-left: 10px;
}

.add-item {
    display: flex;
    align-items: center;
    margin-bottom: 1vh;
    /* 去掉固定宽度以适应英文文本 */
}

.edit-item {
    display: flex;
    align-items: center;
    margin-bottom: 1vh;
    /* 去掉固定宽度以适应英文文本 */
}
</style>
