<template>
    <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="140px" label-position="left">
            <el-form-item label="开启">
                <el-switch v-model.trim="form.status" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            <template v-if="form.status">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" style="width: 500px;" placeholder="例如：邀请1人可得，双方各得10元优惠券"></el-input>
                </el-form-item>
                <el-form-item label="分享封面图" prop="shareImg">
                    <div class="img_list">
                        <div class="item" v-if="form.shareImg">
                            <el-image :src="form.shareImg" style="width: 100%;height: 100%"
                                :preview-src-list="urlList" />
                            <div class="del" @click.stop="form.shareImg = ''">删除</div>
                        </div>
                        <div class="item upload" @click="formImgKey = 'shareImg'; $refs.addImg.show()" v-else>
                            <i class="icon el-icon-plus"></i>
                        </div>
                    </div>
                    <div class="tips">建议尺寸：750*622</div>
                </el-form-item>
                <el-form-item label="邀请顶部图" prop="invitedImg">
                    <div class="img_list">
                        <div class="item" v-if="form.invitedImg">
                            <el-image :src="form.invitedImg" style="width: 100%;height: 100%"
                                :preview-src-list="urlList" />
                            <div class="del" @click.stop="form.invitedImg = ''">删除</div>
                        </div>
                        <div class="item upload" @click="formImgKey = 'invitedImg'; $refs.addImg.show()" v-else>
                            <i class="icon el-icon-plus"></i>
                        </div>
                    </div>
                    <div class="tips">建议尺寸：750*622</div>
                </el-form-item>
                <el-form-item label="被邀顶部图" prop="beInvitedImg">
                    <div class="img_list">
                        <div class="item" v-if="form.beInvitedImg">
                            <el-image :src="form.beInvitedImg" style="width: 100%;height: 100%"
                                :preview-src-list="urlList" />
                            <div class="del" @click.stop="form.beInvitedImg = ''">删除</div>
                        </div>
                        <div class="item upload" @click="formImgKey = 'beInvitedImg'; $refs.addImg.show()" v-else>
                            <i class="icon el-icon-plus"></i>
                        </div>
                    </div>
                    <div class="tips">建议尺寸：750*622</div>
                </el-form-item>
                <el-form-item label="活动日期" prop="startTime">
                    <el-date-picker v-model="createdAt" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"
                        value-format="yyyy-MM-dd HH:mm:ss" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="新用户获得券" prop="newCoupons">
                    <div>
                        <el-button type="primary" @click="addRewardHandle('newCoupons')">添加券</el-button>
                        <div class="tips">新用户的定义：没领过该活动券的都属于新用户，不管有没有下过单和是否第一次登录小程序。</div>
                    </div>
                    <el-table :data="form.newCoupons" border style="width: 600px;">
                        <el-table-column label="券ID" prop="couponId"></el-table-column>
                        <el-table-column label="名称" prop="couponName"></el-table-column>
                        <el-table-column label="数量" prop="couponNum"></el-table-column>
                        <el-table-column label="操作">
                            <template v-slot="scope">
                                <el-button type="text"
                                    @click="addRewardHandle('newCoupons', 2, scope.row, scope.$index)">编辑</el-button>
                                <el-button type="text" @click="form.newCoupons.splice(scope.$index, 1)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="奖励券" prop="invitedNum">
                    <el-input v-model="form.invitedNum" style="width: 350px;"
                        @input="inputFilterInt($event, 'invitedNum')">
                        <template slot="prepend">用户每邀请</template>
                        <template slot="append">人，可获得奖励券</template>
                    </el-input>
                    <el-button type="primary" @click="addRewardHandle('rewardCoupons')">添加券</el-button>
                </el-form-item>
                <el-form-item prop="rewardCoupons">
                    <div>
                        <div class="tips">奖励券不受优惠券发放数量影响</div>
                    </div>
                    <el-table :data="form.rewardCoupons" border style="width: 600px;">
                        <el-table-column label="券ID" prop="couponId"></el-table-column>
                        <el-table-column label="名称" prop="couponName"></el-table-column>
                        <el-table-column label="数量" prop="couponNum"></el-table-column>
                        <el-table-column label="操作">
                            <template v-slot="scope">
                                <el-button type="text"
                                    @click="addRewardHandle('rewardCoupons', 2, scope.row, scope.$index)">编辑</el-button>
                                <el-button type="text"
                                    @click="form.rewardCoupons.splice(scope.$index, 1)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="奖励获得方法">
                    <el-radio-group v-model="form.getMethod">
                        <el-radio label="get">新用户领取获得</el-radio>
                        <el-radio label="use">仅新用户使用获得会员</el-radio>
                    </el-radio-group>
                </el-form-item>
            </template>
            <el-form-item>
                <el-button type="primary" :loading="loading" @click="onSubmitHandle">保存</el-button>
            </el-form-item>
        </el-form>
        <addImg ref="addImg" @successEvent="e => form[formImgKey] = e[0].url" />
        <AddCoupon ref="AddCoupon" @success="addCouponSuccess" />
    </div>
</template>

<script>
import { byShopId, tbShopShare } from '@/api/inviteFirend.js'
import addImg from "@/views/product/components/addImages.vue";
import AddCoupon from './addCoupon.vue'
export default {
    components: { addImg, AddCoupon },
    data() {
        const imgValidate1 = (rule, value, callback) => {
            if (!this.form.shareImg) {
                callback(new Error("请上传分享封面图"));
            } else {
                callback()
            }
        }
        const imgValidate2 = (rule, value, callback) => {
            if (!this.form.invitedImg) {
                callback(new Error("请上传邀请顶部图"));
            } else {
                callback()
            }
        }
        const imgValidate3 = (rule, value, callback) => {
            if (!this.form.beInvitedImg) {
                callback(new Error("请上传被邀顶部图"));
            } else {
                callback()
            }
        }
        const startTimeValidate = (rule, value, callback) => {
            if (!this.form.startTime) {
                callback(new Error("请选择活动日期"));
            } else {
                callback()
            }
        }
        const newCouponsValidate = (rule, value, callback) => {
            if (!this.form.newCoupons.length) {
                callback(new Error("请添加新用户获得券"));
            } else {
                callback()
            }
        }
        const rewardCouponsValidate = (rule, value, callback) => {
            if (!this.form.rewardCoupons.length) {
                callback(new Error("请添加奖励券"));
            } else {
                callback()
            }
        }
        return {
            loading: false,
            createdAt: [],
            formImgKey: '',
            couponKey: '',
            tableType: '1', // 1添加 2编辑
            tableEditorIndex: 0, // 编辑时的index
            form: {
                status: 1,
                title: '',
                shareImg: '',
                invitedImg: '',
                beInvitedImg: '',
                startTime: '',
                endTime: '',
                newCoupons: [],
                invitedNum: '1',
                rewardCoupons: [],
                getMethod: 'get'
            },
            rules: {
                title: [
                    {
                        required: true,
                        message: '请输入标题',
                        trigger: 'blur'
                    }
                ],
                shareImg: [
                    {
                        required: true,
                        validator: imgValidate1,
                        trigger: 'change'
                    }
                ],
                invitedImg: [
                    {
                        required: true,
                        validator: imgValidate2,
                        trigger: 'change'
                    }
                ],
                beInvitedImg: [
                    {
                        required: true,
                        validator: imgValidate3,
                        trigger: 'change'
                    }
                ],
                startTime: [
                    {
                        required: true,
                        validator: startTimeValidate,
                        trigger: 'change'
                    }
                ],
                newCoupons: [
                    {
                        required: true,
                        validator: newCouponsValidate,
                        trigger: 'change'
                    }
                ],
                invitedNum: [
                    {
                        required: true,
                        message: '请输入邀请人数',
                        trigger: 'blur'
                    }
                ],
                rewardCoupons: [
                    {
                        required: true,
                        validator: rewardCouponsValidate,
                        trigger: 'change'
                    }
                ],
            },
            urlList: []
        }
    },
    mounted() {
        this.byShopId()
    },
    methods: {
        // 添加完成优惠券
        addCouponSuccess(e) {
            if (this.tableType == 1) {
                this.form[this.couponKey].push({ ...e })
            } else {
                // this.form[this.couponKey][this.tableEditorIndex] = { ...e }
                this.$set(this.form[this.couponKey], this.tableEditorIndex, { ...e })
            }
        },
        // 添加奖励券
        addRewardHandle(key, type = 1, row = {}, index = 0) {
            this.tableEditorIndex = index
            this.tableType = type
            this.couponKey = key
            if (key == 'rewardCoupons' && !this.form.invitedNum) {
                this.$refs.form.validateField('invitedNum')
                return
            }
            this.$refs.AddCoupon.show(row)
        },
        // 日期回调
        timeChange(e) {
            this.form.startTime = e[0]
            this.form.endTime = e[1]
        },
        // 过滤input只能输入整数
        inputFilterInt(e, key) {
            if (!e) return
            setTimeout(() => {
                this.form[key] = e.replace(/[^\d]/g, '')
            }, 50)
        },
        // 提交
        onSubmitHandle() {
            this.$refs.form.validate(async valid => {
                if (valid) {
                    try {
                        this.loading = true
                        this.form.shopId = localStorage.getItem('shopId')
                        await tbShopShare(this.form)
                        this.loading = false
                        this.$notify({
                            title: '成功',
                            message: `保存成功`,
                            type: 'success'
                        });
                    } catch (error) {
                        this.loading = false
                        console.log(error)
                    }
                }
            })
        },
        // 获取店铺设置
        async byShopId() {
            try {
                const res = await byShopId()
                if (res.id) {
                    this.form = res
                    this.createdAt = [res.startTime, res.endTime]
                    this.urlList = [res.shareImg, res.invitedImg, res.beInvitedImg]
                }
            } catch (error) {
                console.log(error);
            }
        }
    }
}
</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(255, 0, 0, 0.6);
            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>