<!-- 添加积分商品/优惠券 -->
<template>
    <div>
        <el-dialog :title="form.id ? '编辑商品' : '添加商品'" :visible.sync="dialogVisible" @close="reset">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
                <el-form-item label="奖品类型">
                    <el-radio-group v-model="form.goodsCategory">
                        <el-radio label="physical">实物商品</el-radio>
                        <!-- <el-radio label="coupon">优惠券</el-radio> -->
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品图片" prop="goodsImageUrl">
                    <div class="img_list">
                        <div class="item" v-if="form.goodsImageUrl" @click="form.goodsImageUrl = ''">
                            <el-image :src="form.goodsImageUrl" style="width: 100%;height: 100%" />
                            <div class="del">删除</div>
                        </div>
                        <div class="item upload" @click="$refs.addImg.show()" v-else>
                            <i class="icon el-icon-plus"></i>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="商品名称" prop="goodsName">
                    <el-input v-model="form.goodsName" placeholder="请输入商品名称" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="所需积分" prop="requiredPoints">
                    <el-input v-model="form.requiredPoints" style="width: 130px;"
                        @input="inputFilterInt($event, 'requiredPoints')">
                        <template slot="append">积分</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="额外价格" prop="extraPrice">
                    <el-input v-model="form.extraPrice" style="width: 130px;"
                        @input="inputFilterFloat($event, 'extraPrice')">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="数量">
                    <el-input-number v-model="form.quantity" :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input-number v-model="form.sort" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="是否上架">
                    <el-switch v-model.trim="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>
        <addImg ref="addImg" @successEvent="e => form.goodsImageUrl = e[0].url" />
    </div>
</template>

<script>
import { goodsSettingAdd } from '@/api/points.js'
import addImg from "@/views/product/components/addImages.vue";
export default {
    components: {
        addImg
    },
    data() {
        const validateCoverImg = (rule, value, callback) => {
            if (!this.form.goodsImageUrl) {
                callback(new Error("请上传商品图片"));
            } else {
                callback()
            }
        }
        return {
            dialogVisible: false,
            loading: false,
            form: {
                goodsCategory: 'physical',
                goodsName: '',
                goodsImageUrl: '',
                requiredPoints: '',
                extraPrice: 0,
                quantity: '',
                status: 1,
                sort: 0,
                goodsDescription: ''
            },
            resetForm: '',
            rules: {
                goodsName: [
                    {
                        required: true,
                        message: ' ',
                        trigger: 'blur'
                    }
                ],
                goodsImageUrl: [
                    {
                        required: true,
                        validator: validateCoverImg,
                        trigger: 'change'
                    }
                ],
                requiredPoints: [
                    {
                        required: true,
                        message: ' ',
                        trigger: 'blur'
                    }
                ],
                extraPrice: [
                    {
                        required: true,
                        message: ' ',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    mounted() {
        this.resetForm = { ...this.form }
    },
    methods: {
        // 过滤input只能输入整数
        inputFilterInt(e, key) {
            if (!e) return
            setTimeout(() => {
                this.form[key] = e.replace(/[^\d]/g, '')
            }, 50)
        },
        // 过滤input只能输入数字，并且最多输入两位小数
        inputFilterFloat(value, key) {
            if (!value) return
            // 去除首位小数点
            if (value.startsWith('.')) {
                value = value.slice(1);
            }
            // 清除非数字和小数点（除了第一个小数点）
            value = value.replace(/[^\d.]/g, '');
            // 确保最多只有一个小数点
            if (value.split('.').length > 2) {
                value = value.split('.').slice(0, 2).join('.');
            }
            // 限制小数位数为两位
            if (value.split('.')[1] && value.split('.')[1].length > 2) {
                value = value.split('.')[0] + '.' + value.split('.')[1].slice(0, 2);
            }
            setTimeout(() => {
                this.form[key] = value
            }, 50)
        },
        // 提交
        onSubmitHandle() {
            this.$refs.form.validate(async valid => {
                if (valid) {
                    try {
                        this.loading = true
                        this.form.shopId = localStorage.getItem('shopId')
                        await goodsSettingAdd(this.form)
                        this.loading = false
                        this.$notify({
                            title: '成功',
                            message: `${this.form.id ? '编辑' : '添加'}成功`,
                            type: 'success'
                        });
                        this.$emit('success')
                        this.close()
                    } catch (error) {
                        this.loading = false
                        console.log(error)
                    }
                }
            })
        },
        reset() {
            this.form = { ...this.resetForm }
        },
        close() {
            this.dialogVisible = false
        },
        show(row) {
            if (row && row.id) {
                this.form = { ...row }
            }
            this.dialogVisible = true
        }
    }
}
</script>

<style scoped lang="scss">
.img_list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .item {
        width: 100px;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #F5F7FA;
        position: relative;
        overflow: hidden;

        &.upload {
            border: 1px dashed #ddd;
        }

        &:hover {
            cursor: pointer;

            .del {
                transform: translateY(0);
            }
        }

        .del {
            width: 100%;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: absolute;
            left: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(3px);
            color: #fff;
            font-size: 12px;
            transform: translateY(100%);
            transition: all .2s ease-in-out;
        }

        .img {
            width: 100%;
            height: 100%;
            display: block;
        }

        .icon {
            font-size: 20px;
            color: #ddd;
        }
    }
}
</style>