<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
            <el-form-item label-width="120px" prop="orgIndex" v-if="userInfoVO.userType == '00'">
                <el-select v-model="queryParams.orgIndex" placeholder="请选择门店" clearable filterable>
                    <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 prop="discountWay">
                <el-select v-model="queryParams.discountWay" placeholder="请选择优惠券类型" clearable>
                    <el-option v-for="dict in dict.type.coupon_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item prop="isUsed" v-if="isUsed != 'Y'">
                <el-select v-model="queryParams.isUsed" placeholder="请选择是否核销" clearable>
                    <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>
                <el-date-picker v-model="queryParams.duringDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item prop="appUserPhoneNumber">
                <el-input v-model="queryParams.appUserPhoneNumber" placeholder="请输入客户手机号" clearable @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-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>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" @click="handleExport" v-hasPermi="['app:couponItem:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <Page uri="/mapi/app/couponItem/list" :request-params="queryParams" ref="pagination">
            <el-table-column label="编号" align="center" prop="id" fixed="left" />
            <el-table-column label="优惠券名称" align="center" prop="couponTypeTitle" width="120" :show-overflow-tooltip="true" />
            <el-table-column label="优惠券类型" align="center" prop="discountWay" width="120" :show-overflow-tooltip="true">
                <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" prop="deductAmount" width="150">
                <template slot-scope="scope">
                    <span v-if="scope.row.discountWay == 0">满{{ scope.row.minAmount }}元减{{ scope.row.deductAmount }}元</span>
                    <span v-if="scope.row.discountWay == 1">满{{ scope.row.minAmount }}件减{{ scope.row.deductAmount }}件</span>
                    <span v-if="scope.row.discountWay == 2">{{ scope.row.discountRate }}%折扣</span>
                </template>
            </el-table-column>
            <el-table-column label="所属门店" align="center" prop="orgName" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span v-if="scope.row.orgName">{{ scope.row.orgName }}</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>
            <el-table-column label="关联活动" align="center" prop="activityTitle" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span v-if="scope.row.activityTitle">{{ scope.row.activityTitle }}</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>
            <el-table-column label="客户姓名" align="center" prop="appUserName" width="150">
                <template slot-scope="scope"> {{ scope.row.appUserName }}/{{ scope.row.appUserPhone }} </template>
            </el-table-column>

            <el-table-column label="有效期开始时间" align="center" prop="startDate" width="140"> </el-table-column>
            <el-table-column label="有效期结束时间" align="center" prop="endDate" width="140"> </el-table-column>
            <el-table-column label="是否核销" align="center" prop="isUsed" width="80">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isUsed" />
                </template>
            </el-table-column>
            <el-table-column label="核销门店" align="center" prop="usedOrgName" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span v-if="scope.row.usedOrgName">{{ scope.row.usedOrgName }}</span>
                    <span v-else>未核销</span>
                </template>
            </el-table-column>
            <el-table-column label="核销时间" align="center" prop="usedTime" width="140">
                <template slot-scope="scope">
                    <span v-if="scope.row.usedTime">{{ scope.row.usedTime }}</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>
            <el-table-column label="核销订单编码" align="center" prop="deductOrderNo" width="150" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" 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>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 发送优惠券对话框 -->
        <el-dialog :title="sendCouponTitle" :visible.sync="sendCouponOpen" size="30%" append-to-body>
            <el-row :gutter="15">
                <el-form ref="form" :model="sendCouponForm" :rules="rules" label-width="140px">
                    <el-col :span="24">
                        <el-form-item label="门店" prop="orgId">
                            <el-select v-model="sendCouponForm.orgId" style="width: 200px" @input="getAllValidList(sendCouponForm.orgId)" placeholder="请选择门店" clearable filterable>
                                <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
                            </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: 200px" placeholder="请选择优惠劵" clearable>
                                <el-option v-for="item in couponList" :key="item.id" :label="item.title" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="用户手机号" prop="appUserPhoneNumber">
                            <el-input style="width: 200px" v-model.number="sendCouponForm.appUserPhoneNumber" placeholder="请输入手机号" clearable maxlength="11" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="一次性发送数量" prop="sendNum">
                            <el-input-number v-model.number="sendCouponForm.sendNum" placeholder="请输入发送数量" :controls="false" min="1" />
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitSendCouponForm" style="margin-left: 5%">提交</el-button>
                <el-button @click="sendCouponCancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加或修改优惠券对话框 -->
        <el-dialog :title="title" :visible.sync="open" size="30%" append-to-body>
            <el-row :gutter="15">
                <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                    <el-col :span="24">
                        <el-form-item label="有效期" prop="duringDate">
                            <el-date-picker v-model="form.duringDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" style="margin-left: 5%">提交</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: []
        }
    },
    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.sendCouponForm.sourceType = '02'
                    sendCoupon(this.sendCouponForm).then((response) => {
                        this.$modal.msgSuccess('提交成功')
                        this.sendCouponOpen = false
                        this.getList()
                    })
                }
            })
        },
        /** 删除按钮操作 */
        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(() => {})
        }
    }
}
</script>
