<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">
            <div class="edit-view__content-section">
                <el-form
                    :model="formData"
                    :rules="rules"
                    ref="form"
                    label-width="108px"
                    label-position="right"
                    size="small"
                    style="max-width: 600px"
                >
                    <el-form-item prop="name" label="活动名称">
                        <el-input v-model="formData.name" class="width"></el-input>
                    </el-form-item>
                    <el-form-item prop="minterId" label="铸造者">
                        <minter-select
                            v-model="formData.minterId"
                            @detail="onMinterDetail"
                            class="width"
                        ></minter-select>
                    </el-form-item>
                    <el-form-item prop="cover" label="封面">
                        <single-upload v-model="formData.cover"></single-upload>
                    </el-form-item>
                    <el-form-item prop="detail" label="活动详情" style="width: calc(100vw - 450px)">
                        <rich-text v-model="formData.detail"></rich-text>
                    </el-form-item>
                    <el-form-item prop="audit" label="是否需要审核">
                        <el-radio-group v-model="formData.audit">
                            <el-radio :label="true">人工审核</el-radio>
                            <el-radio :label="false">自动匹配</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item prop="collectionName" label="藏品名称" v-if="formData.audit === true">
                        <el-input v-model="formData.collectionName" :disabled="!canEdit" class="width"></el-input>
                    </el-form-item>
                    <el-form-item prop="rule" label="匹配规则设置" v-if="formData.audit === false">
                        <template v-if="formData.rule && formData.rule.and">
                            <div v-for="(item, i) in formData.rule.and" class="rule-item">
                                <el-select v-model="item.detail.tag" value-key="id" size="mini">
                                    <el-option
                                        v-for="item in tags"
                                        :key="item.id"
                                        :value="item"
                                        :label="item.name"
                                    ></el-option>
                                </el-select>
                                <span style="padding: 0 10px; color: #606266; font-weight: bold">×&nbsp;1</span>
                                <i @click="delRule(i)" class="el-icon-delete icon-del"></i>
                            </div>
                        </template>
                        <el-button size="mini" @click="addRule">添加</el-button>
                    </el-form-item>
                    <el-form-item prop="num" label="藏品数量">
                        <el-input-number
                            type="number"
                            v-model="formData.num"
                            :disabled="!canEdit"
                            :step="1"
                            :min="0"
                            class="width1"
                        ></el-input-number>
                        <div class="tip">0表示不限</div>
                    </el-form-item>
                    <el-form-item prop="consume" label="是否消耗藏品">
                        <el-radio-group v-model="formData.consume" :disabled="!canEdit">
                            <el-radio :label="true">是</el-radio>
                            <el-radio :label="false">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <!-- <div class="inline-wrapper"> -->
                    <el-form-item prop="total" label="发行数量">
                        <el-input-number
                            type="number"
                            v-model="formData.total"
                            :disabled="!canEdit"
                            :step="1"
                            :min="0"
                            class="width1"
                        ></el-input-number>
                    </el-form-item>
                    <el-form-item prop="gasPrice" label="铸造gas费">
                        <el-input-number v-model="formData.gasPrice" :min="0" class="width1"></el-input-number>
                    </el-form-item>
                    <!-- </div> -->
                    <el-form-item prop="airDrop" label="类型">
                        <el-radio v-model="formData.airDrop" :label="true" :disabled="!canEdit">空投铸造</el-radio>
                        <el-radio v-model="formData.airDrop" :label="false" :disabled="!canEdit">实物铸造</el-radio>
                    </el-form-item>
                    <el-form-item prop="autoDrop" label="自动空投" v-if="formData.airDrop === true">
                        <el-radio v-model="formData.autoDrop" :label="true">是</el-radio>
                        <el-radio v-model="formData.autoDrop" :label="false">否</el-radio>
                    </el-form-item>
                    <el-form-item
                        prop="airDropCollectionId"
                        label="空投藏品"
                        v-if="formData.airDrop === true && formData.autoDrop === true"
                    >
                        <collection-search v-model="formData.airDropCollectionId"></collection-search>
                    </el-form-item>
                    <el-form-item prop="onShelf" label="上架">
                        <el-radio v-model="formData.onShelf" :label="true">是</el-radio>
                        <el-radio v-model="formData.onShelf" :label="false">否</el-radio>
                    </el-form-item>
                    <el-form-item prop="startTime" label="定时发布">
                        <el-radio v-model="formData.scheduleSale" :label="true">是</el-radio>
                        <el-radio v-model="formData.scheduleSale" :label="false">否</el-radio>
                    </el-form-item>
                    <el-form-item prop="startTime" label="发布时间" v-if="formData.scheduleSale">
                        <el-date-picker
                            v-model="formData.startTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="发布时间"
                        ></el-date-picker>
                    </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>
    </div>
</template>
<script>
import { format, parse, isBefore } from 'date-fns';
import TagSelect from '@/components/TagSelect';
export default {
    name: 'MintActivityEdit',
    created() {
        if (this.$route.query.id) {
            this.$http
                .get('mintActivity/get/' + this.$route.query.id)
                .then(res => {
                    this.formData = res;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
        this.$http.post('/tag/all', { size: 10000 }, { body: 'json' }).then(res => {
            this.tags = res.content;
        });
    },
    data() {
        return {
            saving: false,
            formData: {
                onShelf: false,
                scheduleSale: true,
                rule: {
                    and: []
                },
                autoDrop: false
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入名称',
                        trigger: 'blur'
                    }
                ],
                minterId: [
                    {
                        required: true,
                        message: '请输入铸造者ID',
                        trigger: 'blur'
                    }
                ],
                total: [
                    {
                        required: true,
                        message: '请输入发行数量',
                        trigger: 'blur'
                    }
                ],
                num: [
                    {
                        required: true,
                        message: '请输入藏品数量',
                        trigger: 'blur'
                    }
                ],
                consume: [
                    {
                        required: true,
                        message: '请选择是否消耗藏品',
                        trigger: 'blur'
                    }
                ],
                audit: [
                    {
                        required: true,
                        message: '请选择是否需要审核',
                        trigger: 'blur'
                    }
                ],
                gasPrice: [
                    {
                        required: true,
                        message: '请输入铸造GAS费',
                        trigger: 'blur'
                    }
                ],
                airDrop: [
                    {
                        required: true,
                        message: '请选择类型',
                        trigger: 'blur'
                    }
                ],
                startTime: [
                    {
                        validator: (rule, value, callback) => {
                            if (this.formData.scheduleSale) {
                                if (!value) {
                                    callback(new Error('请填写发布时间'));
                                } else if (isBefore(parse(value, 'yyyy-MM-dd HH:mm:ss', new Date()), new Date())) {
                                    callback(new Error('发布时间不能小于当前时间'));
                                } else {
                                    callback();
                                }
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                rule: [
                    { required: true, message: '请选择规则', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!this.formData.audit) {
                                if (!this.formData.rule) {
                                    callback(new Error('请填写规则'));
                                } else if (!this.formData.rule.and) {
                                    callback(new Error('请填写规则'));
                                } else if (!this.formData.rule.and.length) {
                                    callback(new Error('请填写规则'));
                                } else {
                                    for (let i = 0; i < this.formData.rule.and.length; i++) {
                                        if (
                                            !(this.formData.rule.and[i].detail && this.formData.rule.and[i].detail.tag)
                                        ) {
                                            callback(new Error('请选择'));
                                            callback = null;
                                            break;
                                        }
                                    }
                                    if (callback) {
                                        callback();
                                    }
                                }
                            } else {
                                callback();
                            }
                        }
                    }
                ],
                autoDrop: [
                    {
                        required: true,
                        message: '请选择是否自动空投',
                        trigger: 'blur'
                    }
                ],
                airDropCollectionId: [
                    {
                        required: true,
                        message: '请选择空投藏品',
                        trigger: 'blur'
                    }
                ]
            },
            tags: []
        };
    },
    computed: {
        canEdit() {
            return !!!this.$route.query.id;
        }
    },
    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('/mintActivity/save', 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);
                });
        },
        onDelete() {
            this.$confirm('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/mintActivity/del/${this.formData.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        console.log(e);
                        this.$message.error((e || {}).error || '删除失败');
                    }
                });
        },
        onMinterDetail(e) {
            console.log(e);
            this.$set(this.formData, 'minter', e.nickname);
            this.$set(this.formData, 'minterAvatar', e.avatar);
        },
        addRule() {
            if (!(this.formData.rule && this.formData.rule.and)) {
                this.$set(this.formData, 'rule', { and: [] });
            }
            this.formData.rule.and.push({ detail: { tag: null, num: 1 } });
        },
        delRule(i) {
            this.formData.rule.and.splice(i, 1);
        }
    }
};
</script>
<style lang="less" scoped>
.inline-wrapper {
    .el-form-item {
        display: inline-block;
        width: 270px;
    }
}
.tip {
    font-size: 12px;
    color: @text3;
    margin-top: 5px;
}
.width {
    width: 300px;
}
.width1 {
    width: 150px;
}
/deep/.el-input.is-disabled .el-input__inner {
    color: #7c7e7e;
}
/deep/.el-radio__input.is-disabled + span.el-radio__label {
    color: #7c7e7e;
}
.rule-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .icon-del {
        color: #f56c6c;
        cursor: pointer;
        font-size: 18px;
    }
}
</style>
