<template>
    <div class="app-container">
        <!-- 搜索区域卡片 -->
        <el-card class="box-card" shadow="never">
            <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="100px">
                <el-form-item label="优惠券类型" prop="discountWay">
                    <el-select v-model="queryParams.discountWay" placeholder="请选择优惠券类型" clearable style="width: 240px">
                        <el-option v-for="dict in dict.type.coupon_type" :key="dict.value" :label="dict.label" :value="dict.value">
                            <span style="float: left">{{ dict.label }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="优惠券名称" prop="title">
                    <el-input v-model="queryParams.title" placeholder="请输入优惠券名称" clearable 
                        prefix-icon="el-icon-ticket" style="width: 240px" @keyup.enter.native="handleQuery" />
                </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-card class="box-card table-card" shadow="never">
            <div slot="header" class="clearfix">
                <el-row :gutter="10" class="mb8">
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </div>

            <!-- 数据列表 -->
            <Page uri="/mapi/activity/couponInfo/listByStore" :request-params="queryParams" ref="pagination">
                <el-table-column label="编号" align="center" prop="id" width="80" />
                <el-table-column label="名称" align="center" prop="title" min-width="150" :show-overflow-tooltip="true" />
                <el-table-column label="优惠券类型" align="center" prop="discountWay" width="120">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.coupon_type" :value="scope.row.discountWay" />
                    </template>
                </el-table-column>
                <el-table-column label="券值信息" align="center" width="150">
                    <template slot-scope="scope">
                        <el-tag size="mini" :type="getDiscountTagType(scope.row.discountWay)">
                            <template v-if="scope.row.discountWay == 0">
                                满{{ formatAmount(scope.row.minAmount) }}减{{ formatAmount(scope.row.deductAmount) }}
                            </template>
                            <template v-else-if="scope.row.discountWay == 1">
                                满{{ scope.row.minAmount }}件减{{ scope.row.deductAmount }}件
                            </template>
                            <template v-else>
                                {{ scope.row.discountRate }}%折扣
                            </template>
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="有效期" align="center" width="340">
                    <template slot-scope="scope">
                        <span>{{ scope.row.startDate }} 至 {{ scope.row.endDate }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="适用范围" align="center" prop="useScope" width="120">
                    <template slot-scope="scope">
                        <el-tag size="mini" :type="scope.row.useScope === 1 ? 'success' : 'warning'">
                            {{ scope.row.useScope === 1 ? '全部衣服' : '指定衣服' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="库存" align="center" width="120">
                    <template slot-scope="scope">
                        <el-tag size="mini" :type="getStockTagType(scope.row.couponStock)">
                            {{ scope.row.couponStock }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="备注" align="center" prop="remark" min-width="120" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <span>{{ scope.row.remark || '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建信息" align="center" min-width="200">
                    <template slot-scope="scope">
                        <div class="create-info">
                            <el-tag size="mini" type="info">{{ scope.row.createBy }}</el-tag>
                            <el-tag size="mini" type="info">{{ scope.row.createTime }}</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="150" v-if="isUsed != 'Y'">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-plus" @click="handleAdd(scope.row)" 
                            v-hasPermi="['app:couponItem:add']">
                            发放优惠券
                        </el-button>
                    </template>
                </el-table-column>
            </Page>
        </el-card>

        <!-- 发送优惠券对话框 -->
        <el-dialog :title="sendCouponTitle" :visible.sync="sendCouponOpen" width="500px" 
            :close-on-click-modal="false" :before-close="handleDialogClose" append-to-body>
            <el-form ref="form" :model="sendCouponForm" :rules="rules" label-width="120px">
                <el-card class="box-card" shadow="never">
                    <div slot="header">
                        <span>发送信息</span>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="客户手机号" prop="appUserPhoneNumber">
                                <el-input v-model="sendCouponForm.appUserPhoneNumber" 
                                    placeholder="请输入手机号" clearable maxlength="11"
                                    prefix-icon="el-icon-mobile-phone" style="width: 300px" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="发送数量" prop="sendNum">
                                <el-input-number v-model="sendCouponForm.sendNum" 
                                    placeholder="请输入发送数量" :min="1" :max="100"
                                    style="width: 300px" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitSendCouponForm" :loading="submitLoading">确 定</el-button>
                <el-button @click="sendCouponCancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCouponItem, getCouponItem, delCouponItem, sendCoupon, updateCouponItem, updateCouponItemStatus } from '@/api/coupon/item'
import { allOrg } from '@/api/system/store'
import { allValidList } from '@/api/coupon/type'
import { listByStore } from '@/api/activity/couponInfo'

export default {
    name: 'StoreSendCoupon',
    dicts: ['sys_source_type', 'sys_yes_no', 'coupon_type'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 优惠券表格数据
            couponItemList: [],
            // 弹出层标题
            title: '',
            sendCouponTitle: '',
            // 是否显示弹出层
            open: false,
            sendCouponOpen: false,
            // 查询参数
            queryParams: {
                orgIndex: null,
                dateRange: []
            },
            // 表单参数
            form: {},
            // 表单参数
            sendCouponForm: {},
            // 表单校验
            rules: {
                appUserPhoneNumber: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                sendNum: [
                    { required: true, message: '发放数量不能为空', trigger: 'blur' },
                    { type: 'number', min: 1, max: 100, message: '发放数量必须在1-100之间', trigger: 'blur' }
                ]
            },
            orgList: [],
            isUsed: null,
            storeList: [],
            factoryList: [],
            dateRange: [],
            submitLoading: false
        }
    },
    created() {
        this.handleUser()
        this.isUsed = this.getUrlParam('isUsed')
        if (this.isUsed == 'Y') {
            this.queryParams.isUsed = this.isUsed
        }
        this.getList()
        allOrg().then((res) => {
            this.orgList = res.data
            this.orgList.forEach((org) => {
                if (org.sourceType == '01') {
                    this.factoryList.push(org)
                } else {
                    this.storeList.push(org)
                }
            })
        })
    },
    methods: {
        handleUser() {
            this.userInfoVO = this.getUserInfo()
        },
        /** 查询优惠券列表 */
        getList() {
            this.$nextTick(() => {
                this.$refs.pagination.handleSearch(true)
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 取消按钮
        sendCouponCancel() {
            this.sendCouponOpen = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.sendCouponForm = {
                couponTypeId: null,
                activityId: null,
                orgId: null,
                sourceType: null,
                appUserPhoneNumber: null,
                sendNum: null
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 发送优惠券按钮操作 */
        handleAdd(row) {
            this.reset()
            this.sendCouponForm.couponTypeId = row.id
            this.sendCouponOpen = true
            this.sendCouponTitle = '发送优惠券'
        },
        /** 提交发送优惠券 */
        submitSendCouponForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    this.sendCouponForm.sourceType = this.userInfoVO.userType
                    this.sendCouponForm.orgId = this.userInfoVO.storeId
                    sendCoupon(this.sendCouponForm)
                        .then((response) => {
                            this.$modal.msgSuccess('发放成功')
                            this.sendCouponOpen = false
                            this.getList()
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                }
            })
        },
        handleDialogClose(done) {
            if (this.isFormChanged()) {
                this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.reset()
                    done()
                }).catch(() => {})
            } else {
                this.reset()
                done()
            }
        },
        getDiscountTagType(discountWay) {
            const types = {
                '0': 'danger',   // 满减
                '1': 'warning',  // 满件减件
                '2': 'success'   // 折扣
            }
            return types[discountWay] || 'info'
        },
        getStockTagType(stock) {
            if (stock <= 0) return 'danger'
            if (stock <= 10) return 'warning'
            return 'success'
        },
        formatAmount(amount) {
            return parseFloat(amount).toFixed(2)
        },
        isFormChanged() {
            return this.sendCouponForm.appUserPhoneNumber || this.sendCouponForm.sendNum
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
    background-color: #f5f7fa;

    .box-card {
        margin-bottom: 20px;
        transition: all 0.3s ease-in-out;

        &.table-card {
            margin-bottom: 0;
        }

        &:hover {
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
    }

    .el-card__header {
        padding: 15px 20px;
        border-bottom: 1px solid #ebeef5;
        background-color: #fafafa;
    }

    .el-card__body {
        padding: 20px;
    }

    .create-info {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;

        .el-tag {
            margin: 0 4px;
        }
    }

    .dialog-footer {
        text-align: right;
        padding-top: 20px;
    }
}
</style>
