<template>
    <div class="edit-view">
        <page-title>
            <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
            <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id"> 删除 </el-button>
            <el-button @click="onSave" :loading="saving" type="primary">保存</el-button>
        </page-title>
        <div class="edit-view__content-wrapper" v-loading="saving">
            <div class="edit-view__content-section">
                <el-form
                    :model="formData"
                    :rules="rules"
                    ref="form"
                    label-width="160px"
                    label-position="right"
                    size="small"
                    style="max-width: 800px"
                >
                    <el-form-item label="项目" prop="projectId"  >
                        <project-select v-model="formData.projectId" :disabled="!canEdit"> </project-select>
                    </el-form-item>
                    <el-form-item  label="白名单用户">
                        <el-table :data="users">
                            <el-table-column type="index" label="#" width="50"></el-table-column>
                            <el-table-column label="手机" prop="phone"></el-table-column>
                            <el-table-column label="昵称" prop="nickname"></el-table-column>
                            <el-table-column width="80" align="center">
                                <template v-slot="{ row, $index }">
                                    <el-button type="text" @click="delUser($index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button @click="addUser" size="mini">添加</el-button>
                    </el-form-item>
                    <el-form-item  prop="phones" label="手机号" >
                        <div  style="max-width:80%;word-break:break-all;">{{formData.phones}}</div>
                    </el-form-item>
                    <el-form-item label="凭证类型" prop="itemId">
                        <el-select v-model="formData.itemId" :disabled="!canEdit">
                            <el-option :value="0" label="指定铸造者"></el-option>
                            <el-option :value="1" label="消耗性全局优先购凭证"></el-option>
                            <el-option :value="2" label="消耗性指定藏品优先购凭证"></el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item v-if="formData.itemId == 2" prop="collectionId"   label="需要持有的藏品">
                        <el-form-item prop="collectionId" :rules="{ required: true, message: '请选择藏品' }">
                            <collection-search v-model="formData.collectionId" :projectId="formData.projectId">
                            </collection-search>
                        </el-form-item>
                    </el-form-item> -->
                    <el-form-item prop="minterId" v-if="formData.itemId == 0" label="铸造者">
                        <minter-select
                            v-model="formData.minterId"
                            :projectId="formData.projectId"
                            :disabled="!canEdit"
                        ></minter-select>
                    </el-form-item>
                    <el-form-item v-if="formData.itemId == 2" prop="targetCollectionIdList" label="指定藏品">
                        <el-form-item prop="collectionId">
                            <collection-search
                                :isMultiple="true"
                                v-model="formData.targetCollectionIdList"
                                :projectId="formData.projectId"
                                :disabled="!canEdit"
                            >
                            </collection-search>

                            <!-- <div class="form_tip">不选择默认可优先购买所有藏品</div> -->
                        </el-form-item>
                    </el-form-item>
                    <el-form-item label="优先次数" prop="advancePurchaseCount">
                        <el-input-number v-model="formData.advancePurchaseCount" type="number"> </el-input-number>
                    </el-form-item>
                    <el-form-item label="优先时间" prop="advancePurchaseTime">
                        <el-input-number v-model="formData.advancePurchaseTime" type="number"> </el-input-number>
                        <div class="form_tip">提前购买时间（小时），示例：1小时 = 1 24小时 = 24；暂不支持小数</div>
                    </el-form-item>
                    <el-form-item label="过期时间" prop="overdueTime">
                        <el-date-picker
                            type="datetime"
                            v-model="formData.overdueTime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择过期时间"
                        >
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="说明">
                        <el-input v-model="formData.text" type="textarea" rows="5"></el-input>
                        <div class="form_tip"></div>
                    </el-form-item>

                    <el-form-item class="form-submit">
                        <el-button @click="onSave" :loading="saving" type="primary"> 保存 </el-button>
                        <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id">
                            删除
                        </el-button>
                        <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <el-dialog
            :visible.sync="showPhoneDialog"
            title="添加白名单用户"
            width="600px"
            :close-on-click-modal="false"
            :show-close="!searchingPhone"
        >
            <el-form :model="{ inputPhones }" ref="phoneForm">
                <el-form-item prop="inputPhones" :rules="[{ required: true, message: '请输入手机号' }]">
                    <el-input
                        v-model="inputPhones"
                        type="textarea"
                        :autosize="{ minRows: 3, maxRows: 20 }"
                        placeholder="可输入多个手机号，用空格或回车分隔"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="showPhoneDialog = false" :disabled="searchingPhone" size="mini">取消</el-button>
                <el-button @click="savePhone" :loading="searchingPhone" size="mini" type="primary">确定</el-button>
            </div>
        </el-dialog>


    </div>
</template>
<script>
import RichText from '../components/RichText.vue';
import SingleUpload from '../components/SingleUpload.vue';
export default {
    components: { RichText, SingleUpload },
    name: 'PreemptionWhiteEdit',
    created() {
        if (this.$route.query.id) {
            this.$http
                .get('/whiteListConfigInfo/get/' + this.$route.query.id)
                .then(res => {
                    this.formData = res;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
    },
    data() {
        return {
            saving: false,
            formData: {
                projectId: this.$store.state.projectId
            },
            rules: {
                phones: [
                    {
                        required: true,
                        message: '请添加白名单用户',
                        trigger: 'blur'
                    }
                ],
                itemId: [
                    {
                        required: true,
                        message: '请选择凭证类型',
                        trigger: 'blur'
                    }
                ],
                targetCollectionIdList: [
                    {
                        required: true,
                        message: '请选择指定优先藏品',
                        trigger: 'blur'
                    }
                ],
                advancePurchaseCount: [
                    {
                        required: true,
                        message: '请输入可提前购买次数',
                        trigger: 'blur'
                    }
                ],
                advancePurchaseTime: [
                    {
                        required: true,
                        message: '请输入可提前时间',
                        trigger: 'blur'
                    }
                ],
                overdueTime: [
                    {
                        required: true,
                        message: '请输入过期时间',
                        trigger: 'blur'
                    }
                ],
                projectId: [{ required: true, message: '请选择项目' }]
            },
            inputPhones:"",
            showPhoneDialog: false,
            searchingPhone: false,
            users: [],
        };
    },
    methods: {
        // 保存验证
        onSave() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        // 新增 / 编辑
        submit() {
            let data = { ...this.formData };
            
            this.saving = true;
            this.$http
                .post('/whiteListConfigInfo/batchSave', data, { body: 'json' })
                .then(res => {
                    this.saving = false;
                    this.$message.success('成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        addUser() {
            this.inputPhones = '';
            this.showPhoneDialog = true;
            if (this.$refs.phoneForm) {
                this.$nextTick(() => {
                    this.$refs.phoneForm.clearValidate();
                });
            }
        },
        savePhone() {
            this.$refs.phoneForm
                .validate()
                .then(res => {
                    this.searchingPhone = true;
                    this.$http
                        .post('/user/searchByPhoneAdmin', { phone: this.inputPhones })
                        .then(res => {
                            this.showPhoneDialog = false;
                            this.searchingPhone = false;
                            this.users = this.users.concat(res.users.filter(i => !this.users.find(e => e.id === i.id)));
                            if (res.notFound && res.notFound.length) {
                                this.$alert('未找到以下手机对应的用户：<br>' + res.notFound.join('、'), '', {
                                    dangerouslyUseHTMLString: true
                                });
                            }
                            
                        })
                        .catch(e => {
                            this.searchingPhone = false;
                            this.$message.error(e.error || e.message);
                        });
                })
                .catch(e => {                    
                    this.$message.error(e.error || e.message);
                });
        },
        delUser(index) {
            this.users.splice(index, 1);
        },
    },
    computed: {
        canEdit() {
            return !this.$route.query.id;
        }
    },
    watch:{
        "users":function(){
            this.formData.phones = "";
            if(this.users){
                this.formData.phones = this.users.map(item => {
                                return item.phone;
                            }).join(",");
            }
            
        }
    }
};
</script>
<style lang="less" scoped></style>
