<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-width="120px" prop="orgIndex" v-if="userInfoVO.userType == '00'">
                    <el-select v-model="queryParams.orgIndex" placeholder="请选择门店" clearable filterable prefix-icon="el-icon-office-building" style="width: 240px">
                        <el-option v-for="store in storeList" :key="store.id + store.sourceType" :label="store.name" :value="store.id + ',' + store.sourceType"> </el-option>
                    </el-select>
                </el-form-item>
                <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="isUsed" v-if="isUsed != 'Y'">
                    <el-select v-model="queryParams.isUsed" placeholder="请选择使用状态" clearable style="width: 240px">
                        <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="有效期">
                    <el-date-picker v-model="queryParams.duringDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                        :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="客户手机号" prop="appUserPhoneNumber">
                    <el-input v-model="queryParams.appUserPhoneNumber" placeholder="请输入客户手机号" clearable
                        prefix-icon="el-icon-mobile-phone" 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">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['app:couponItem:add']">
                            发送优惠券
                        </el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </div>

            <!-- 数据列表 -->
            <Page uri="/mapi/app/couponItem/list" :request-params="queryParams" ref="pagination">
                <el-table-column type="selection" width="55" align="center" fixed="left" />
                <el-table-column label="编号" align="center" prop="id" width="80" />
                <el-table-column label="优惠券名称" align="center" prop="couponTypeTitle" 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" prop="orgName" width="120" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-tag size="mini" type="info" v-if="scope.row.orgName">{{ scope.row.orgName }}</el-tag>
                        <el-tag size="mini" type="info" v-else>全部门店</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="关联活动" align="center" prop="activityTitle" width="120" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-tag size="mini" type="warning" v-if="scope.row.activityTitle">{{ scope.row.activityTitle }}</el-tag>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column label="客户信息" align="center" min-width="180">
                    <template slot-scope="scope">
                        <div class="customer-info">
                            <span class="customer-name">{{ scope.row.appUserName }}</span>
                            <el-tag size="mini" type="info">{{ scope.row.appUserPhone }}</el-tag>
                        </div>
                    </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" width="120">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.isUsed === 'Y' ? 'success' : 'info'" size="mini">
                            {{ scope.row.isUsed === 'Y' ? '已使用' : '未使用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="使用信息" align="center" min-width="200" v-if="isUsed === 'Y'">
                    <template slot-scope="scope">
                        <div class="usage-info" v-if="scope.row.isUsed === 'Y'">
                            <div>
                                <el-tag size="mini" type="success">{{ scope.row.usedOrgName || '--' }}</el-tag>
                            </div>
                            <div>
                                <el-tag size="mini" type="warning">{{ scope.row.usedTime || '--' }}</el-tag>
                            </div>
                            <div>
                                <el-tag size="mini" type="info">{{ scope.row.deductOrderNo || '--' }}</el-tag>
                            </div>
                        </div>
                        <span v-else>--</span>
                    </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-edit" v-if="scope.row.isUsed == 'N'"
                            @click="handleUpdate(scope.row)" v-hasPermi="['app:couponItem:edit']">
                            修改有效期
                        </el-button>
                    </template>
                </el-table-column>
            </Page>
        </el-card>

        <!-- 发送优惠券对话框 -->
        <el-dialog :title="sendCouponTitle" :visible.sync="sendCouponOpen" width="600px"
            :close-on-click-modal="false" :before-close="handleSendCouponClose" 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="orgId">
                                <el-select v-model="sendCouponForm.orgId" style="width: 100%"
                                    @change="getAllValidList" placeholder="请选择门店"
                                    clearable filterable>
                                    <el-option v-for="item in storeList" :key="item.id"
                                        :label="item.name" :value="item.id">
                                        <span style="float: left">{{ item.name }}</span>
                                        <span style="float: right; color: #8492a6; font-size: 13px">
                                            <el-tag size="mini" type="info">{{ item.sourceType === '01' ? '工厂' : '门店' }}</el-tag>
                                        </span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="选择优惠券" prop="couponTypeId" v-if="sendCouponForm.orgId != null">
                                <el-select v-model="sendCouponForm.couponTypeId" style="width: 100%"
                                    placeholder="请选择优惠券" clearable filterable>
                                    <el-option v-for="item in couponList" :key="item.id"
                                        :label="item.title" :value="item.id">
                                        <span style="float: left">{{ item.title }}</span>
                                        <span style="float: right; color: #8492a6; font-size: 13px">
                                            <el-tag size="mini" :type="getDiscountTagType(item.discountWay)">
                                                {{ getDiscountText(item) }}
                                            </el-tag>
                                        </span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <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: 100%" />
                            </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: 100%" />
                            </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>

        <!-- 修改有效期对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" :close-on-click-modal="false" :before-close="handleClose" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="有效期" prop="duringDate">
                    <el-date-picker v-model="form.duringDate" type="daterange"
                        range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="yyyy-MM-dd"
                        style="width: 100%" :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
                <el-button @click="cancel">取 消</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'

export default {
    name: 'CouponItem',
    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: {
                duringDate: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
                orgId: [{ required: true, message: '门店不能为空', trigger: 'blur' }],
                couponTypeId: [{ required: true, message: '优惠券不能为空', trigger: 'blur' }],
                appUserPhoneNumber: [{ required: true, message: '用户手机号不能为空', trigger: 'blur' }],
                sendNum: [{ required: true, message: '发放数量不能为空', trigger: 'blur' }]
            },
            orgList: [],
            isUsed: null,
            storeList: [],
            factoryList: [],
            couponList: [],
            dateRange: [],
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            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() {
            if (this.queryParams.orgIndex != null) {
                this.queryParams.orgId = this.queryParams.orgIndex.split(',')[0]
                this.queryParams.sourceType = this.queryParams.orgIndex.split(',')[1]
            } else {
                delete this.queryParams.orgId
                delete this.queryParams.sourceType
            }
            if (null != this.queryParams.duringDate && this.queryParams.duringDate.length > 0) {
                this.queryParams.startDate = this.queryParams.duringDate[0]
                this.queryParams.endDate = this.queryParams.duringDate[1]
            } else {
                delete this.queryParams.startDate
                delete this.queryParams.endDate
            }
            this.$nextTick(() => {
                this.$refs.pagination.handleSearch(true)
            })
        },
        getAllValidList(id) {
            this.sendCouponForm.couponTypeId = null
            allValidList(id).then((res) => {
                this.couponList = res.data
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 取消按钮
        sendCouponCancel() {
            this.sendCouponOpen = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                orderNo: null,
                couponTypeId: null,
                activityInfoId: null,
                orgId: null,
                sourceType: null,
                appUserId: null,
                isUsed: null,
                usedOrgId: null,
                usedSourceType: null,
                usedTime: null,
                startDate: null,
                endDate: null,
                isUnique: null,
                canManual: null,
                deductAmount: null,
                deductOrderNo: null,
                createById: null,
                createBy: null,
                createTime: null,
                updateById: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.sendCouponForm = {
                couponTypeId: null,
                activityInfoId: null,
                orgId: null,
                sourceType: null,
                appUserPhoneNumber: null,
                sendNum: null
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        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() {
            this.reset()
            this.sendCouponOpen = true
            this.sendCouponTitle = '发送优惠券'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getCouponItem(id).then((response) => {
                var duringDate = []
                duringDate.push(response.data.startDate)
                duringDate.push(response.data.endDate)
                response.data.duringDate = duringDate
                this.form = response.data
                this.open = true
                this.title = '修改优惠券'
            })
        },
        /** 提交按钮 */
        submitForm() {
            var params = {}
            if (null != this.form.duringDate && this.form.duringDate.length > 0) {
                params['startDate'] = this.form.duringDate[0]
                params['endDate'] = this.form.duringDate[1]
            }
            params.id = this.form.id
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    // if (this.form.id != null) {
                    updateCouponItem(params).then((response) => {
                        this.$modal.msgSuccess('修改成功')
                        this.open = false
                        this.getList()
                    })
                    // } else {
                    //   addCouponItem(this.form).then(response => {
                    //     this.$modal.msgSuccess("新增成功");
                    //     this.open = false;
                    //     this.getList();
                    //   });
                    // }
                }
            })
        },
        /** 提交发送优惠券 */
        submitSendCouponForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    this.sendCouponForm.sourceType = '02'
                    sendCoupon(this.sendCouponForm).then(response => {
                        this.$modal.msgSuccess('发送成功')
                        this.sendCouponOpen = false
                        this.getList()
                    }).finally(() => {
                        this.submitLoading = false
                    })
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal
                .confirm('是否确认删除优惠券编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delCouponItem(ids)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'mapi/app/couponItem/export',
                {
                    ...this.queryParams
                },
                `couponItem_${new Date().getTime()}.xlsx`
            )
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        getDiscountTagType(discountWay) {
            const types = {
                '0': 'danger',   // 满减
                '1': 'warning',  // 满件减件
                '2': 'success'   // 折扣
            }
            return types[discountWay] || 'info'
        },
        getDiscountText(item) {
            if (item.discountWay == 0) {
                return `满${this.formatAmount(item.minAmount)}减${this.formatAmount(item.deductAmount)}`
            } else if (item.discountWay == 1) {
                return `满${item.minAmount}件减${item.deductAmount}件`
            } else {
                return `${item.discountRate}%折扣`
            }
        },
        formatAmount(amount) {
            return parseFloat(amount).toFixed(2)
        },
        handleSendCouponClose(done) {
            if (this.isFormChanged(this.sendCouponForm)) {
                this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.reset()
                    done()
                }).catch(() => {})
            } else {
                this.reset()
                done()
            }
        },
        handleClose(done) {
            if (this.isFormChanged(this.form)) {
                this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.reset()
                    done()
                }).catch(() => {})
            } else {
                this.reset()
                done()
            }
        },
        isFormChanged(form) {
            // Implement the logic to determine if the form has been changed
            // This is a placeholder and should be replaced with the actual implementation
            return false
        }
    }
}
</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;
    }

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

        .customer-name {
            font-weight: 500;
        }
    }

    .usage-info {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .el-tag {
            width: fit-content;
            margin: 0 auto;
        }
    }

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