<!--  -->
<template>
    <div class="m-container">
        <h2>
            <div class="squrt"></div>奖品设置
        </h2>
        <div class="newBand" v-permission="'luckDrawPrize/batchAdd'" @click="onOperationTrophy('create')">添加</div>
        <!-- 搜索标题 -->
        <save-form :inline="true"
                class="searchForm"
                @submit="getList"
                :model="searchForm">
            <el-form-item>
                <el-input v-model.trim="searchForm.name" clearable
                        placeholder="请输入奖品名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select v-model.trim="searchForm.groupId"
                        style="width: 100% !important"
                        placeholder="请选择所属活动">
                    <el-option v-for="item in groupList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button native-type="submit" type="danger">搜索</el-button>
            </el-form-item>
        </save-form>
        <!-- 列表 -->
        <div class="tableWrap">
            <el-table :data="tableList"
                        :header-cell-style="{background:'#EDEEF0',color:'#444'}">
                <el-table-column align="center"
                                prop="name"
                                label="奖品名称"></el-table-column>
                <!-- <el-table-column align="center"
                                prop="groupName"
                                label="所属活动"></el-table-column> -->
                <el-table-column align="center"
                                prop="chances"
                                label="中奖概率">
                    <template slot-scope="scope">
                        {{ Number((scope.row.chances * 100).toFixed(4)) }}%
                    </template>
                </el-table-column>
                <el-table-column align="center"
                                prop="stock"
                                label="库存"></el-table-column>
                <el-table-column align="center"
                                prop="enabled"
                                label="是否启用">
                    <template slot-scope="scope">
                        {{ scope.row.enabled ? '启用' : '不启用' }}
                    </template>
                </el-table-column>
                <el-table-column align="center"
                                prop="isDefault"
                                label="是否默认">
                    <template slot-scope="scope">
                        {{ scope.row.isDefault ? '是' : '否' }}
                    </template>
                </el-table-column>
                <el-table-column align="center"
                                prop="memo"
                                label="备注">
                    <template slot-scope="scope">
                        <tooltip :content="scope.row.memo" />
                    </template>
                </el-table-column>

                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                        <el-button @click="onOperationTrophy('update', scope.row)" v-permission="'luckDrawPrize/update'" type="text">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination sync :total.sync="pageInfo.total"
                        :page.sync="pageInfo.page"
                        :limit.sync="pageInfo.limit"
                        :page-sizes="pageInfo.page_size"
                        @pagination="getList" />
        </div>

        <el-dialog :title="formTitle[formActionTitle]"
                :visible.sync="lotteryCreateStatus"
                width="800px">
            <trophy-create :groupList="groupList"
                        :getList="getList"
                        :close="onPopupClose"></trophy-create>
        </el-dialog>

        <el-dialog :title="formTitle[formActionTitle]"
                :visible.sync="lotteryStatus"
                @close="onFormClose('trophyForm')"
                width="500px">
            <el-form :model="form"
                    :rules="rules"
                    label-width="100PX"
                    ref="trophyForm">
                <el-form-item label="奖品名称"
                            prop="name">
                <el-input v-model.trim="form.name"
                            autocomplete="off"
                            placeholder="请输入奖品名称"></el-input>
                </el-form-item>
                <el-form-item label="所属活动" prop="groupId">
                    <el-select v-model.trim="form.groupId"
                            style="width: 100% !important"
                            placeholder="请选择所属活动">
                        <el-option v-for="item in groupList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="中奖概率"
                            prop="chances">
                    <el-input v-model.trim="form.chances"
                            type="number"
                            autocomplete="off"
                            placeholder="请输入中奖概率">
                        <i slot="suffix" class="el-input__icon" style="padding-right: 5px;">%</i>
                    </el-input>
                </el-form-item>
                <el-form-item label="库存"
                            prop="stock">
                    <el-input v-model.trim="form.stock"
                            type="number"
                            autocomplete="off"
                            placeholder="请输入库存">
                    </el-input>
                </el-form-item>
                <el-form-item label="是否默认"
                            prop="isDefault">
                    <el-select v-model.trim="form.isDefault"
                            style="width: 100% !important"
                            placeholder="请选择是否是默认">
                        <el-option :value="true" label="是"></el-option>
                        <el-option :value="false" label="否"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注"
                            prop="memo">
                    <el-input type="textarea" :rows="2" v-model.trim="form.memo"
                            autocomplete="off"
                            placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer"
                    class="dialog-footer">
                <el-button @click="lotteryStatus = false">取 消</el-button>
                <el-button type="primary" @click="onSubmit('trophyForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Tooltip from '@/components/Tooltip/index'
import pagination from "@/components/Pagination/index";
import trophyCreate from './trophyCreate'
import dayjs from 'dayjs';
import numeral from 'numeral';
import cleanDeep from 'clean-deep';
import { luckDrawPrizeList, luckDrawPrizeUpdate, luckDrawGroupFindAll } from './api'
const validNumber1 = (rule, value, callback) => {
    const re = /^[0-9]+$/
    if (value == '' && typeof value == 'string' || value == null) {
        callback(new Error('请输入库存'))
    } else if (!re.test(value) && value < 0) {
        callback(new Error('输入库存为正整数'))
    } else {
        callback()
    }
}
const validNumber = (rule, value, callback) => {
    if (value == '' && typeof value == 'string' || value == null) {
        callback(new Error('请输入中奖概率'))
    } else if (value < 0) {
        callback(new Error('输入值不能小于0'))
    } else {
        callback()
    }
}
export default {
    components: { pagination, Tooltip, trophyCreate },
    data () {
        return {
            searchForm: {
                name: null,
                groupId: null
            },
            formTitle: {
                create: "添加奖品",
                update: "修改奖品"
            },
            formActionTitle: 'create',
            lotteryStatus: false,
            lotteryCreateStatus: false,
            tableList: [],
            groupList: [],
            form: {
                name: null,
                groupId: null,
                chances: null,
                stock: null,
                memo: null,
                isDefault: null
            },
            rules: {
                name: [{required: true, message:'请输入活动名称', trigger: 'blur'}],
                groupId: [{required: true, message:'请选择所属活动', trigger: 'change'}],
                chances: [{required: true, validator: validNumber, trigger: 'blur'}],
                stock: [{required: true, validator: validNumber1, trigger: 'blur'}],
                enabled: [{required: true, message:'请选择是否启用', trigger: 'change'}],
                isDefault: [{required: true, message:'请选择是否默认', trigger: 'change'}]
            },
            pageInfo: {
                // 分页规则
                limit: 10, // 限制显示条数
                page: 1, // 当前页
                total: 1, // 总条数
                page_size: [10, 20, 40, 50] // 选择限制显示条数
            }
        };
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created () {
        // 设置默认为当前周
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    async mounted () {
        await this.__init()
    },
    methods: {
        async __init() {
            const query = this.$route.query
            await luckDrawGroupFindAll({ page: 1, rows: 9999 }).then(res => {
                const result = res.data
                if(res.code == 200) {
                    this.groupList = result?.length > 0 ? result : []
                    this.searchForm.groupId = query.groupId ? Number(query.groupId) : this.groupList[0]?.id
                }
            })

            this.getList()
        },
        onOperationTrophy(type, data) {
            this.formActionTitle = type
            if(type == 'update') {
                this.$nextTick(() => {
                    this.form = {
                        id: data.id,
                        name: data.name,
                        groupId: data.groupId,
                        chances: data.chances * 100,
                        stock: data.stock,
                        isDefault: data.isDefault,
                        memo: data.memo
                    }
                })
                this.lotteryStatus = true
            } else if(type == 'create') {
                this.lotteryCreateStatus = true
            }
        },
        onSubmit(formName) {
            this.$refs[formName].validate(item => {
                if(item) {
                    let form = Object.assign({}, this.form)
                    let params = {
                        name: form.name,
                        groupId: form.groupId,
                        chances: numeral(form.chances ? form.chances / 100 : 0).format('0.0000'),
                        stock: form.stock,
                        memo: form.memo,
                        isDefault: form.isDefault,
                        enabled: 1
                    }
                    if(this.formActionTitle == 'update') {
                        params.id = form.id
                        luckDrawPrizeUpdate(params).then(res => {
                            this.messageTips('修改', res)
                        })
                    }
                }
            })
        },
        onPopupClose() {
            this.lotteryCreateStatus = false
        },
        onFormClose(formName) {
            this.$refs[formName].resetFields()
        },
        messageTips (title, res) {
            if (res.code == 200) {
                this.$message.success(title + '成功')
                this.lotteryStatus = false
                this.getList()
            } else {
                this.$message.error(res.msg)
            }
        },
        getList() {
            let params = Object.assign({}, this.searchForm)
            params.rows = this.pageInfo.limit
            params.page = this.pageInfo.page
            luckDrawPrizeList(cleanDeep(params)).then(res => {
                if (res.code == 200 && res.data) {
                    this.tableList = res.data.rows
                    this.pageInfo.total = res.data.total
                }
            })
        }
    }
};
</script>