<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-wrapper" shadow="never">
            <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch">
                <el-form-item label="活动标题" prop="title">
                    <el-input v-model="queryParams.title" placeholder="请输入活动标题" clearable style="width: 240px" @keyup.enter.native="handleQuery">
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                </el-form-item>
                <el-form-item label="活动时间" prop="dateRange">
                    <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 240px"> </el-date-picker>
                </el-form-item>
                <el-form-item label="活动状态" prop="status">
                    <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable style="width: 180px">
                        <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作按钮区 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['activity:couponInfo:add']"> 新增活动 </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 列表区域 -->
        <el-card shadow="never">
            <Page uri="/mapi/activity/couponInfo/list" :request-params="queryParams" ref="pagination">
              <el-table-column label="活动编号" align="center" prop="id" width="100" />
              <el-table-column label="活动信息" min-width="250" align="left">
                    <template slot-scope="scope">
                        <div class="activity-card">
                            <div class="activity-main">
                                <image-preview :src="scope.row.imgUrl" :width="80" :height="80" class="activity-img" />
                                <div class="activity-content">
                                    <div class="activity-title">
                                        <span>{{ scope.row.title }}</span>
                                    </div>
                                    <div class="activity-desc">{{ scope.row.description }}</div>
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <!-- 重要信息列 -->
                <el-table-column label="活动价格" align="center" width="100">
                    <template slot-scope="scope">
                        <el-tag size="medium" type="danger">¥{{ scope.row.price }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="活动时间" align="center" min-width="150">
                    <template slot-scope="scope"> {{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }} 至 {{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }} </template>
                </el-table-column>
                <el-table-column label="优惠券数量" align="center" width="120">
                    <template slot-scope="scope">
                        <el-tag size="medium" type="primary">{{ scope.row.couponNum }}张</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="使用范围" align="center" min-width="150">
                    <template slot-scope="scope">
                        <div class="tag-group">
                            <el-tag size="mini" effect="plain" type="primary">{{ getUserScopeLabel(scope.row.userScope) }}</el-tag>
                            <el-tag size="mini" effect="plain" type="success">{{ getStoreScopeLabel(scope.row.storeScope) }}</el-tag>
                        </div>
                    </template>
                </el-table-column>
          <el-table-column label="限购" align="center" min-width="150">
            <template slot-scope="scope">
              <div class="tag-group">
                <el-tag size="mini" effect="plain" type="warning" v-if="scope.row.maxBuyNum==9999"> 不限 </el-tag>
                <el-tag size="mini" effect="plain" type="warning" v-else> {{ scope.row.maxBuyNum }} 张</el-tag>
              </div>
            </template>
          </el-table-column>
                <el-table-column label="活动状态" align="center" width="100">
                    <template slot-scope="scope">
                        <div class="status-column">
                            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" width="150" />

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                        <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" >修改</el-button>
                        <el-button type="text" icon="el-icon-s-shop"  @click="handleSetCouponItems(scope.row)" >设置优惠券</el-button>
                        <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" >删除</el-button>
                    </template>
                </el-table-column>
            </Page>
        </el-card>

        <!-- 编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body class="activity-dialog" :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="基本信息" name="basic">
                        <el-row :gutter="20">
                            <el-col :span="14">
                                <el-form-item label="活动标题" prop="title">
                                    <el-input v-model="form.title" placeholder="请输入活动标题" maxlength="200" show-word-limit />
                                </el-form-item>
                                <el-form-item label="活动描述" prop="description">
                                    <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入活动描述" maxlength="500" show-word-limit />
                                </el-form-item>
                                <el-form-item label="活动时间" prop="duringDate" required>
                                    <el-date-picker v-model="form.duringDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 100%"> </el-date-picker>
                                </el-form-item>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="活动价格" prop="price">
                                            <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" controls-position="right" style="width: 100%">
                                                <template slot="prefix">¥</template>
                                            </el-input-number>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="购买限制" prop="maxBuyNum">
                                            <el-checkbox v-model="form.isUnlimited" @change="handleUnlimitedChange">不限</el-checkbox>
                                            <el-input-number v-if="!form.isUnlimited" v-model="form.maxBuyNum" :min="1" :max="9998" :precision="0" controls-position="right" style="width: 100%">
                                                <template slot="suffix">张</template>
                                            </el-input-number>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="宣传图片" prop="imgUrl">
                                    <image-upload v-model="form.imgUrl" :limit="1" :is-show-tip="true" :file-size="5" accept=".jpg,.jpeg,.png" tip-text="建议尺寸：800x400px，大小不超过5MB" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-tab-pane>

                    <el-tab-pane label="使用规则" name="rules">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="适用用户" prop="userScope">
                                    <el-radio-group v-model="form.userScope" class="radio-group-block">
                                        <el-radio-button v-for="dict in dict.type.activity_user_scope" :key="dict.value" :label="dict.value">
                                            {{ dict.label }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="使用范围" prop="storeScope">
                                    <el-radio-group v-model="form.storeScope" class="radio-group-block">
                                        <el-radio-button v-for="dict in dict.type.coupon_use_range" :key="dict.value" :label="parseInt(dict.value)">
                                            {{ dict.label }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="活动状态" prop="status">
                                    <el-radio-group v-model="form.status">
                                        <el-radio-button v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">
                                            {{ dict.label }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-form-item label="适用门店" prop="selectStoreIds" v-if="form.storeScope === 1">
                            <el-transfer v-model="form.selectStoreIds" :data="form.storeVOS" :titles="['可选门店', '已选门店']" :button-texts="['移除', '选择']" filterable> </el-transfer>
                        </el-form-item>
                    </el-tab-pane>

                    <el-tab-pane label="活动详情" name="content">
                        <el-form-item label="活动详情" prop="content">
                            <wang-editor v-model="form.content" :height="400" :min-height="300" @editorContent="getEditorContent" placeholder="请输入活动详情内容..." />
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 详情弹窗 -->
        <el-dialog title="活动详情" :visible.sync="viewOpen" width="800px" append-to-body>
            <el-descriptions class="margin-top" :column="2" border>
                <el-descriptions-item label="活动标题">{{ viewForm.title }}</el-descriptions-item>
                <el-descriptions-item label="活动状态">
                    <dict-tag :options="dict.type.sys_normal_disable" :value="viewForm.status" />
                </el-descriptions-item>
                <el-descriptions-item label="活动价格">¥{{ viewForm.price }}</el-descriptions-item>
                <el-descriptions-item label="购买限制">
                    <span v-if="viewForm.maxBuyNum === 9999">不限</span>
                    <span v-else>限购{{ viewForm.maxBuyNum }}张</span>
                </el-descriptions-item>
                <el-descriptions-item label="活动时间">
                    {{ parseTime(viewForm.startDate, '{y}-{m}-{d}') }} 至 {{ parseTime(viewForm.endDate, '{y}-{m}-{d}') }}
                </el-descriptions-item>
                <el-descriptions-item label="优惠券数量">{{ viewForm.couponNum }}张</el-descriptions-item>
                <el-descriptions-item label="适用用户">
                    <dict-tag :options="dict.type.activity_user_scope" :value="viewForm.userScope" />
                </el-descriptions-item>
                <el-descriptions-item label="使用范围">
                    <dict-tag :options="dict.type.coupon_use_range" :value="viewForm.storeScope" />
                </el-descriptions-item>
                <el-descriptions-item :span="2" label="活动描述">{{ viewForm.description }}</el-descriptions-item>
                <el-descriptions-item :span="2" label="活动图片">
                    <image-preview :src="viewForm.imgUrl" :width="200" :height="100" />
                </el-descriptions-item>
                <el-descriptions-item :span="2" label="活动详情">
                    <div v-html="viewForm.content"></div>
                </el-descriptions-item>
            </el-descriptions>
            <div slot="footer" class="dialog-footer">
                <el-button @click="viewOpen = false">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCouponInfo, getInfo, delCouponInfo, addCouponInfo, updateCouponInfo } from '@/api/activity/couponInfo'
import { updateInfoStatus } from '@/api/activity/info'
import WangEditor from '@/components/wangEditor/index.vue'

export default {
    name: 'CouponInfo',
    components: {
        WangEditor
    },
    dicts: ['sys_normal_disable', 'coupon_use_range', 'coupon_from_type', 'sys_yes_no', 'activity_user_scope', 'activity_pay_scope'],
    data() {
        return {
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 送券活动表格数据
            couponInfoList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 是否正在提交或处理中
            processing: false,
            // 查询参数
            queryParams: {
                title: undefined,
                status: undefined,
                dateRange: []
            },
            // 表单参数
            form: {
                id: null,
                duringDate: [],
                activityType: '1',
                status: '0',
                canMultiUse: 'N',
                maxUseCount: 1,
                isShowAppBuyPage: null,
                isShowWxBuyPage: null,
                isShowWxBuyPageFromQrcode: null,
                storeScope: null,
                couponFrom: null,
                maxBuyNum: null,
                isUnlimited: false,
                createById: null,
                createBy: null,
                createTime: null,
                updateById: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                selectStoreIds: [],
                content: '',
                imgUrl: '',
                title: '',
                description: '',
                storeVOS: []
            },
            // 表单校验
            rules: {
                title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
                description: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
                imgUrl: [{ required: true, message: '宣传图片不能为空', trigger: 'blur' }],
                content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
                duringDate: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
                userScope: [{ required: true, message: '适用用户范围不能为空', trigger: 'change' }],
                payScope: [{ required: true, message: '支付范围不能为空', trigger: 'change' }],
                activityType: [{ required: true, message: '活动类型不能为空', trigger: 'change' }],
                status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
                canMultiUse: [{ required: true, message: '是否可多张使用不能为空', trigger: 'change' }],
                maxUseCount: [{ required: true, message: '单次订单最多使用券数不能为空', trigger: 'blur' }],
                isShowAppBuyPage: [{ required: true, message: '是否展示在app购买页不能为空', trigger: 'change' }],
                isShowWxBuyPage: [{ required: true, message: '是否展示在小程序购买页不能为空', trigger: 'change' }],
                isShowWxBuyPageFromQrcode: [{ required: true, message: '是否展示在小程序购买页不能为空', trigger: 'change' }],
                storeScope: [{ required: true, message: '优惠券使用范围不能为空', trigger: 'change' }],
                couponFrom: [{ required: true, message: '优惠券来源不能为空', trigger: 'change' }],
                maxBuyNum: [{ required: true, message: '最大可购买数量不能为空', trigger: 'blur' }],
                price: [{ required: true, message: '活动价格不能为空', trigger: 'blur' }]
            },
            activeTab: 'basic',
            // 是否正在关闭
            isClosing: false,
            // 是否显示详情弹出层
            viewOpen: false,
            // 详情表单参数
            viewForm: {}
        }
    },
    created() {
        this.getList()
    },
    methods: {
        /** 查询送券活动列表 */
        getList() {
            this.$nextTick(() => {
                this.$refs.pagination.handleSearch(true)
            })
        },
        // 获取编辑器内容
        getEditorContent(content) {
            this.form.content = content
        },
        // 处理弹窗关闭
        handleClose(done) {
            if (this.isClosing || this.loading || this.processing) {
                return
            }

            // 设置关闭状态
            this.isClosing = true

            // 使用 Promise 确保状态更新完成
            Promise.resolve()
                .then(() => {
                    // 重置所有状态
                    this.loading = false
                    this.processing = false
                    this.activeTab = 'basic'

                    // 关闭弹窗
                    this.open = false

                    // 清空表单数据
                    this.reset()

                    if (typeof done === 'function') {
                        done()
                    }
                })
                .catch((error) => {
                    console.error('关闭弹窗出错:', error)
                })
                .finally(() => {
                    // 重置关闭状态
                    this.isClosing = false
                })
        },

        // 弹窗完全关闭后的回调
        handleClosed() {
            // 使用 Promise 确保状态更新完成
            Promise.resolve().then(() => {
                this.isClosing = false
                this.loading = false
                this.processing = false
                this.reset()
            })
        },

        // 取消按钮
        cancel() {
            if (this.isClosing || this.loading || this.processing) {
                return
            }
            this.handleClose()
        },

        // 表单重置
        reset() {
            try {
                // 清理表单验证
                if (this.$refs.form) {
                    this.$refs.form.clearValidate()
                }

                // 重置表单数据
                this.form = {
                    id: null,
                    duringDate: [],
                    activityType: '1',
                    status: '0',
                    canMultiUse: 'N',
                    maxUseCount: 1,
                    isShowAppBuyPage: null,
                    isShowWxBuyPage: null,
                    isShowWxBuyPageFromQrcode: null,
                    storeScope: null,
                    couponFrom: null,
                    maxBuyNum: null,
                    isUnlimited: false,
                    createById: null,
                    createBy: null,
                    createTime: null,
                    updateById: null,
                    updateBy: null,
                    updateTime: null,
                    remark: null,
                    selectStoreIds: [],
                    content: '',
                    imgUrl: '',
                    title: '',
                    description: '',
                    storeVOS: []
                }
            } catch (error) {
                console.error('重置表单出错:', error)
            }
        },
        /** 设置价格 */
        handleSetCouponItems(row) {
            this.$tab.openPage(row.title + '的优惠券', '/activity/couponItem/' + row.id)
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            if (this.isClosing) return

            this.reset()
            this.loading = false
            this.processing = false
            this.activeTab = 'basic'

            getInfo()
                .then((response) => {
                    var duringDate = []
                    response.data.duringDate = duringDate
                    response.data.status = '0'
                    this.form = { ...this.form, ...response.data }
                    this.open = true
                    this.title = '新增送券活动'
                })
                .catch((error) => {
                    this.$modal.msgError('获取数据失败：' + (error.message || '未知错误'))
                })
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            if (this.isClosing) return

            this.reset()
            this.loading = false
            this.processing = false
            this.activeTab = 'basic'

            const id = row.id || this.ids
            getInfo(id)
                .then((response) => {
                    var duringDate = []
                    duringDate.push(response.data.startDate)
                    duringDate.push(response.data.endDate)
                    response.data.duringDate = duringDate
                    // 设置不限标识
                    response.data.isUnlimited = response.data.maxBuyNum === 9999
                    this.form = { ...this.form, ...response.data }
                    this.open = true
                    this.title = '修改送券活动'
                })
                .catch((error) => {
                    this.$modal.msgError('获取数据失败：' + (error.message || '未知错误'))
                })
        },
        /** 提交按钮 */
        submitForm() {
            if (this.processing) return // 如果正在处理中，不允许重复提交

            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.loading = true
                    this.processing = true

                    if (null != this.form.duringDate && this.form.duringDate.length > 0) {
                        this.form['startDate'] = this.form.duringDate[0]
                        this.form['endDate'] = this.form.duringDate[1]
                    } else {
                        delete this.form.startDate
                        delete this.form.endDate
                    }

                    const submitRequest = this.form.id != null ? updateCouponInfo(this.form) : addCouponInfo(this.form)

                    submitRequest
                        .then((response) => {
                            this.$modal.msgSuccess(this.form.id != null ? '修改成功' : '新增成功')
                            this.$nextTick(() => {
                                this.open = false
                                this.getList()
                            })
                        })
                        .catch((error) => {
                            console.error('提交失败:', error)
                            this.$modal.msgError('操作失败：' + (error.message || '未知错误'))
                        })
                        .finally(() => {
                            this.loading = false
                            this.processing = false
                        })
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal
                .confirm('是否确认删除送券活动编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delCouponInfo(ids)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'mapi/activity/couponInfo/export',
                {
                    ...this.queryParams
                },
                `couponInfo_${new Date().getTime()}.xlsx`
            )
        },
        handleStatusChange(row) {
            let text = row.status === '0' ? '启用' : '停用'
            this.$confirm('确认要' + text + ' ' + row.title + ' 吗？')
                .then(function () {
                    return updateInfoStatus(row.id, row.status)
                })
                .then(() => {
                    this.$modal.msgSuccess(text + '成功')
                })
                .catch(function () {
                    row.status = row.status === '0' ? '1' : '0'
                })
        },
        // 获取用户范围标签
        getUserScopeLabel(value) {
            const item = this.dict.type.activity_user_scope.find((d) => d.value === value)
            return item ? item.label : ''
        },
        // 获取门店范围标签
        getStoreScopeLabel(value) {
            const item = this.dict.type.coupon_use_range.find((d) => d.value === value)
            return item ? item.label : ''
        },
        // 处理下拉菜单命令
        handleCommand(command, row) {
            switch (command) {
                case 'edit':
                    this.handleUpdate(row)
                    break
                case 'setCoupons':
                    this.handleSetCouponItems(row)
                    break
                case 'delete':
                    this.handleDelete(row)
                    break
            }
        },
        handleUnlimitedChange(val) {
            if (val) {
                this.form.maxBuyNum = 9999
            } else {
                this.form.maxBuyNum = 1
            }
        },
        /** 查看按钮操作 */
        handleView(row) {
            this.viewForm = { ...row }
            this.viewOpen = true
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    .search-wrapper {
        margin-bottom: 10px;
    }

    .activity-card {
        padding: 15px;
        background: #fff;
        border-radius: 4px;

        .activity-main {
            display: flex;
            align-items: flex-start;

            .activity-img {
                margin-right: 20px;
                border-radius: 4px;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }

            .activity-content {
                flex: 1;
                min-width: 0;

                .activity-title {
                    display: flex;
                    align-items: center;
                    margin-bottom: 10px;

                    span {
                        font-size: 16px;
                        font-weight: 500;
                        color: #303133;
                    }
                }

                .activity-desc {
                    font-size: 14px;
                    color: #606266;
                    line-height: 1.4;
                }
            }
        }
    }

    .status-column {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;

        .status-tag {
            margin-bottom: 4px;
        }
    }

    .tag-group {
        display: flex;
        gap: 8px;
        justify-content: center;
        flex-wrap: wrap;

        .el-tag {
            margin: 2px;
        }
    }
}

.activity-dialog {
    .el-dialog__body {
        padding: 20px 30px;
    }

    .radio-group-block {
        // display: flex;
        width: 100%;

        .el-radio-button {
            flex: 1;

            &__inner {
                width: 100%;
            }
        }
    }

    .el-transfer {
        width: 100%;

        .el-transfer-panel {
            width: 45%;

            &__body {
                height: 300px;
            }
        }
    }
}

// 下拉菜单样式
.dropdown-danger {
    color: #f56c6c;
}

:deep(.el-table) {
    // 移除表格边框
    border: none;

    &::before {
        display: none;
    }

    .el-table__header-wrapper {
        display: none;
    }

    .el-table__row {
        background-color: transparent;
    }

    .el-table__cell {
        background-color: transparent;
    }
}
</style>
