<template>
        <el-dialog title="赠送积分" :visible.sync="visible"  v-loading="saving">
            <el-form
                    :model="formData"
                    :rules="rules"
                    ref="form"
                    label-width="108px"
                    label-position="right"
                >
                <!-- 单个赠送 -->
                <div v-if="formData.userId">
                    <el-form-item label="用户ID">
                        {{userIntegral.userId}}
                    </el-form-item>
                    <el-form-item label="手机号">
                        {{userIntegral.phone}}
                    </el-form-item>
                    <el-form-item label="用户名称">
                        {{userIntegral.username}}
                    </el-form-item>
                    <el-form-item label="可用积分">
                        {{userIntegral.availableIntegral}}
                    </el-form-item>
                    <el-form-item label="消耗积分">
                        {{userIntegral.consumeIntegral}}
                    </el-form-item>
                </div>

                <!-- 批量赠送 -->
                <div v-if="!formData.userId">
                    <el-form-item label="赠送用户" prop="phone" :rules="[{ required: true, message: '请输入手机号' }]"  >
                        <el-input
                            v-model="formData.phone"
                            type="textarea"
                            :autosize="{ minRows: 5, maxRows: 20 }"
                            placeholder="可输入多个手机号，用空格或回车分隔，输入后点击检索用户"
                        ></el-input>
                        <el-button @click="searchPhone">检索用户</el-button>
                    </el-form-item>
                    
                    <div style="color:#cc0000;padding:20px;border-bottom:solid 1px #ddd;" v-if="phoneError">
                        {{phoneError}}
                    </div>
                    
                    <el-table :data="users" v-loading="searchingPhone">
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="id" label="用户ID"></el-table-column>
                        <el-table-column prop="username" label="用户名称"></el-table-column>
                        <el-table-column prop="nickname" label="昵称"></el-table-column>
                        <el-table-column prop="phone" label="用户手机号"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="{row}">
                                <el-button size="mini" type="danger"  @click="removeUser(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                    <el-form-item prop="integral" label="赠送积分">
                        <el-input-number
                                type="number"
                                v-model="formData.integral"
                                :min="1"
                            ></el-input-number>
                    </el-form-item>
            </el-form>
            <div class="exchange-footer">
                    <el-button @click="onSave" :loading="saving" type="primary"> 赠送 </el-button>
                    <el-button @click="visible=false;" :loading="saving" > 取消 </el-button>
            </div>
        </el-dialog>
</template>
<script>

export default {
    name: 'UserIntegralPresent',
    data() {
        return {
            saving: false,
            formData: {                
                userId: '',
                userIdList:[],
                integral: null,
                phone:"",
            },
            rules: {
                integral: [
                    {
                        required: true,
                        message: '赠送积分不能为空',
                        trigger: 'blur'
                    }
                ],
            },
            userIntegral:{},
            users:[],
            visible:false,
            searchingPhone: false,
            phoneError:"",
        };
    },
    computed: {
         
    },
    methods: {
        init(userId) {
            this.visible = true;
            this.formData.userId = userId;
            this.formData.phone = "";
            this.userIntegral = {};
            this.users = [];
            if(userId){
                this.saving = true;
                this.$http.get(`/userIntegral/get/${userId}`).then(res =>{
                    this.userIntegral = res;
                }).catch(e => {
                    this.$message.error(e.error);
                }).finally(() => {
                    this.saving = false;
                });
            }
            
        },
        searchPhone() {

            this.searchingPhone = true;
            this.$http
                .post('/user/searchByPhoneAdmin', { phone: this.formData.phone })
                .then(res => {
                    this.users = res.users || [];
                    if (res.notFound && res.notFound.length) {
                        this.phoneError = '未找到以下手机对应的用户：' + res.notFound.join('、');
                    }else{
                        this.phoneError = null;
                    }
                })
            .catch(e => {
                console.log(e);
            }).finally( () => {
                this.searchingPhone = false;
            });
        },
        removeUser(row){
            this.users = this.users.filter((item) => {
                if(item.id == row.id){
                    return false;
                }
                return true;
            });
        },
        onSave(){
            this.$refs["form"].validate(valid => {
                if (valid) {
                    const data = this.formData;
                    if(this.users){
                        data.userIdList = [];
                        this.users.forEach(item => {
                            data.userIdList.push(item.id);
                        });
                    }

                    if(!data.userId && (!data.userIdList || data.userIdList.length == 0)){
                        this.$message.error("赠送用户不能为空，请先检索用户");
                        return;
                    }
                    this.saving = true;
                    this.$http
                        .post('/userIntegralChangeLog/presentIntegral', data, { body: 'json' })
                        .then(res => {
                            this.saving = false;
                            this.$message.success('成功赠送' + res + "个用户" + data.integral + "积分");
                            this.visible = false;
                            this.$emit("refresh");
                        }).catch(e => {
                            console.log(e);
                            this.saving = false;
                            this.$message.error(e.error);
                        });
                }
            });
        }
    }
};
</script>

<style scoped>

    .exchange-footer{
        text-align: right;
    }
</style>