<template>
    <div>
        <el-dialog title="添加优惠券" :visible.sync="dialogVisible" @close="reset">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
                <el-form-item label="优惠卷名称" prop="title">
                    <el-input v-model="form.title" placeholder="请输入优惠卷名称" style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item label="类型">
                    <el-radio-group v-model="form.classType">
                        <el-radio :label="item.value" v-for="item in couponEnum.classType" :key="item.value">
                            {{ item.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="选择商品" v-if="form.classType == 'product'" prop="classType">
                    <div>
                        <el-button type="primary" icon="el-icon-plus" @click="$refs.shopListRef.show([...productIds])">
                            添加商品
                        </el-button>
                    </div>
                    <div class="shop_list">
                        <div class="item_wrap" v-for="(item, index) in productIds" :key="item.id"
                            @click="productIds.splice(index, 1)">
                            <div class="item" :data-index="index + 1">
                                <el-image :src="item.coverImg" style="width: 100%;height: 100%;"></el-image>
                            </div>
                            <div class="name">{{ item.name }}</div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="优惠类型">
                    <el-radio-group v-model="form.type">
                        <el-radio :label="item.value" v-for="item in couponEnum.type" :key="item.value">
                            {{ item.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="满减限制" v-if="form.type == '0'">
                    <el-input-number v-model="form.limitAmount" controls-position="right" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="折扣" v-if="form.type == '1'">
                    <el-input-number v-model="form.ratio" controls-position="right" :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="优惠券面额">
                    <el-input-number v-model="form.amount" controls-position="right" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="发放数量">
                    <el-input-number v-model="form.number" controls-position="right" :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="限领数量">
                    <el-input-number v-model="form.limitNumber" controls-position="right" :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="有效期">
                    <el-radio-group v-model="form.effectType">
                        <el-radio :label="item.value" v-for="item in couponEnum.effectType" :key="item.value">
                            {{ item.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="有效时间" v-if="form.effectType == 1">
                    <el-date-picker v-model="selectTime" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"
                        value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" :loading="loading" @click="onSubmitHandle">确 定</el-button>
            </span>
        </el-dialog>
        <shopList ref="shopListRef" @success="slectShop" />
    </div>
</template>

<script>
import couponEnum from './../couponEnum'
import shopList from '@/components/shopList'
import { tbMerchantCoupon } from '@/api/shop'
export default {
    components: { shopList },
    data() {
        const validateProduct = (rule, value, callback) => {
            if (!this.productIds.length) {
                callback(new Error('请选择商品'))
            } else {
                callback()
            }
        }
        return {
            couponEnum,
            dialogVisible: false,
            loading: false,
            selectTime: [],
            form: {
                id: '',
                title: '',
                classType: 'product',
                type: '0',
                limitAmount: '',
                ratio: '1',
                amount: '',
                number: '1',
                limitNumber: '1',
                effectType: '0',
                fromTime: '',
                toTime: '',
                relationIds: '',
                status: 1
            },
            rules: {
                title: [
                    {
                        required: true,
                        message: ' ',
                        trigger: 'blur'
                    }
                ],
                classType: [
                    {
                        required: true,
                        validator: validateProduct,
                        trigger: 'change'
                    }
                ]
            },
            resetForm: '',
            productIds: []
        }
    },
    mounted() {
        this.resetForm = { ...this.form }
    },
    methods: {
        // 选择商品
        slectShop(res) {
            if (this.productIds.length) {
                res.map(async item => {
                    if (!await this.checkShop(item.id)) {
                        this.productIds.push({ ...item })
                    }
                })
            } else {
                this.productIds = res
            }
        },
        // 判断是否存在重复商品
        checkShop(id) {
            let falg = false
            this.productIds.map(item => {
                if (item.id == id) {
                    falg = true
                }
            })
            return falg
        },
        // 提交
        onSubmitHandle() {
            console.log(this.form)
            this.$refs.form.validate(async valid => {
                if (valid) {
                    try {
                        this.loading = true
                        this.form.shopId = localStorage.getItem('shopId')
                        this.form.fromTime = this.selectTime[0] || ''
                        this.form.toTime = this.selectTime[1] || ''

                        let arr = []
                        if (this.form.classType == 'product') {
                            arr = this.productIds.map(item => item.id)
                        }

                        this.form.relationIds = arr.join(',')

                        let res = await tbMerchantCoupon(this.form, this.form.id ? 'put' : 'post')
                        this.$emit('success', res)
                        this.close()
                        this.$notify({
                            title: '成功',
                            message: `${this.form.id ? '编辑' : '添加'}成功`,
                            type: 'success'
                        });
                        this.loading = false
                    } catch (error) {
                        this.loading = false
                        console.log(error)
                    }
                }
            })
        },
        show(obj) {
            this.dialogVisible = true
            if (obj && obj.id) {
                this.form = { ...obj }
            }
        },
        close() {
            this.dialogVisible = false
        },
        reset() {
            this.form = { ...this.resetForm }
        }
    }
}
</script>

<style scoped lang="scss">
.shop_list {
    display: flex;
    flex-wrap: wrap;

    .item_wrap {
        $size: 80px;

        .item {
            $radius: 4px;
            width: $size;
            height: $size;
            border-radius: $radius;
            overflow: hidden;
            position: relative;
            margin-right: 10px;
            margin-top: 10px;

            &:hover {
                cursor: pointer;
            }

            &::after {
                content: attr(data-index);
                font-size: 12px;
                height: 20px;
                display: flex;
                padding: 0 10px;
                border-radius: 0 0 $radius 0;
                align-items: center;
                background-color: rgba(0, 0, 0, 0.3);
                backdrop-filter: blur(10px);
                color: #fff;
                position: absolute;
                top: 0;
                left: 0;
                z-index: 10;
            }

            &::before {
                content: '删除';
                font-size: 12px;
                width: 100%;
                height: 20px;
                display: flex;
                padding: 0 10px;
                align-items: center;
                justify-content: center;
                background-color: rgba(0, 0, 0, 0.3);
                backdrop-filter: blur(10px);
                color: #fff;
                position: absolute;
                bottom: 0;
                left: 0;
                z-index: 10;
                transition: all .1s ease-in-out;
            }
        }

        .name {
            width: $size;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}
</style>