<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: 750px"
                >
                    <el-form-item label="项目" prop="projectId">
                        <project-select v-model="formData.projectId" @input="changeProject" :disabled="!canEdit">
                        </project-select>
                    </el-form-item>
                    <el-form-item prop="name" label="活动名称">
                        <el-input v-model="formData.name" :disabled="!canEdit"></el-input>
                    </el-form-item>
                    <el-form-item prop="description" label="活动描述">
                        <rich-text v-model="formData.description" :disabled="!canEdit"></rich-text>
                    </el-form-item>
                    <el-form-item prop="pic" label="图片">
                        <single-upload v-model="formData.pic"></single-upload>
                    </el-form-item>
                    <el-form-item prop="type" label="兑换模式">
                        <el-radio-group v-model="formData.type" >
                            <el-radio label="ONE_TO_MANY" :disabled="!canEdit"  border="" >单一集齐</el-radio>
                            <el-radio label="MANY_TO_MANY" :disabled="!canEdit" border=""  >全部集齐</el-radio>
                            <el-radio label="ANY_TO_ONE" :disabled="!canEdit"   border="" >指定数量</el-radio>
                            <el-radio label="SOME_TO_ANY" :disabled="!canEdit"  border="" >全平台匹配 </el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item prop="startTime" label="活动开始时间">
                        <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 prop="endTime" label="活动结束时间">
                        <el-date-picker
                            v-model="formData.endTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间"
                            :disabled="!canEdit"
                        >
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item prop="needCollectedNum" v-if="formData.type == 'SOME_TO_ANY'" label="兑换总数">
                        <el-tooltip
                            class="item"
                            effect="dark"
                            content="此选项为活动要求收集总数量，公式为 兑换总数 减去 下方兑换藏品要求必须收集数量，剩余 任意藏品数量"
                            placement="top-start"
                        >
                            <el-input-number
                                type="number"
                                v-model="formData.needCollectedNum"
                                :disabled="!canEdit"
                                :min="1"
                            ></el-input-number>
                        </el-tooltip>
                    </el-form-item>
                </el-form>

                <div class="exchange-wrapper">
                    <fieldset class="first">
                        <legend>兑换藏品</legend>
                        <el-form
                            :model="{ activities }"
                            ref="formref"
                            label-position="right"
                            label-width="100px"
                            size="small"
                        >
                            <el-form-item
                                v-for="(item, index) in activities"
                                :label="'兑换藏品' + (index + 1)"
                                :key="item.key"
                                :prop="`activities[${index}].collectionId`"
                                :rules="{
                                    required: true,
                                    message: '藏品不能为空',
                                    trigger: 'change'
                                }"
                            >
                                <el-row :gutter="24">
                                    <el-col :span="6">
                                        <collection-search
                                            v-model="item.collectionId"
                                            :disabled="!canEdit"
                                            style="width: 100%"
                                            @select="changeCollection(arguments[0], item)"
                                            :projectId="formData.projectId"
                                        ></collection-search>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-tooltip
                                            class="item"
                                            effect="dark"
                                            content="需要持有该藏品最少数量"
                                            placement="top-start"
                                        >
                                            <el-input-number
                                                type="number"
                                                placeholder="兑换数量"
                                                v-model="item.num"
                                                :disabled="!canEdit"
                                                :min="item.mustNeedCollected ? 1 : 0"
                                            ></el-input-number>
                                        </el-tooltip>
                                    </el-col>
                                    
                                    <el-col :span="4">
                                            <el-tooltip
                                        class="item"
                                        effect="dark"
                                        :content="
                                            formData.type == 'ANY_TO_ONE'
                                                ? '该藏品是否必须收集，默认为必须收集，关闭可以不收集'
                                                : '该藏品是否必须收集，默认为必须收集，关闭则不允许使用该藏品兑换'
                                        "
                                        placement="top-start"
                                    >
                                            <el-switch
                                                :disabled="!canEdit"
                                                v-if="formData.type == 'ANY_TO_ONE' || formData.type == 'SOME_TO_ANY'"
                                                v-model="item.mustNeedCollected"
                                                active-text="必须收集"
                                                inactive-text="不必收集"
                                            ></el-switch>
                                               </el-tooltip>
                                    </el-col>
                                 
                                    <el-col :span="4">
                                        <el-tooltip
                                    class="item"
                                    effect="dark"
                                    content="该藏品是否禁止销毁"
                                    placement="top-start"
                                >
                                        <el-switch
                                            :disabled="!canEdit"
                                            v-model="item.notDestroy"
                                            active-text="禁止销毁"
                                            inactive-text="自动销毁"
                                        ></el-switch>
                                            </el-tooltip>
                                    </el-col>
                                  

                                    <el-col :span="3">
                                        <el-button
                                            :disabled="!canEdit"
                                            v-if="activities.length >= 2"
                                            @click.prevent="removeitem(item, activities)"
                                            >删除</el-button
                                        >
                                    </el-col>
                                </el-row>
                            </el-form-item>
                        </el-form>

                        <div class="exchange-operation">
                            <el-button :disabled="!canEdit" @click="additem(activities)" icon="el-icon-plus">
                                增加兑换藏品
                            </el-button>
                        </div>
                    </fieldset>

                    <fieldset class="two">
                        <legend>获得奖品</legend>
                        <el-form
                            :model="{ awardList }"
                            ref="formlist"
                            label-position="right"
                            label-width="100px"
                            size="small"
                        >
                            <el-form-item
                                v-for="(item, index) in awardList"
                                :key="index"
                                :rules="[{ required: true, message: '请选择获得奖品', trigger: 'blur' }]"
                                :prop="`awardList[${index}].collectionId`"
                                :label="'可获得奖品' + (index + 1)"
                            >
                                <el-row :gutter="20">
                                    <el-col :span="4">
                                        <el-select v-model="item.airDropType"  placeholder="请选择奖品类型"  :disabled="!canEdit">
                                            <el-option value="asset"  label="藏品">藏品</el-option>
                                            <el-option value="SURPRISE_BOX" label="惊喜盒子" >惊喜盒子</el-option>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="4">
                                        <div v-if="item.airDropType == 'asset'">
                                            <collection-search
                                                v-model="item.collectionId"
                                                :disabled="!canEdit"
                                                style="width: 100%"
                                                @select="changeCollection(arguments[0], item)"
                                                :projectId="formData.projectId"
                                            ></collection-search>
                                        </div>

                                        <div v-if="item.airDropType == 'SURPRISE_BOX'">
                                            <surprise-search
                                                 v-model="item.collectionId"
                                                :disabled="!canEdit"
                                                style="width: 100%"
                                                @select="changeCollection(arguments[0], item)"
                                                :projectId="formData.projectId"
                                            >

                                            </surprise-search>

                                        </div>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-tooltip
                                            class="item"
                                            effect="dark"
                                            content="该奖品可兑换库存"
                                            placement="top-start"
                                        >
                                            <el-input-number
                                                type="number"
                                                placeholder="发行数量"
                                                v-model="item.num"
                                                :disabled="!canEdit"
                                                :min="1"
                                            ></el-input-number>
                                        </el-tooltip>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-tooltip
                                            class="item"
                                            effect="dark"
                                            content="用户单次兑换获得数量"
                                            placement="top-start"
                                        >
                                            <el-input-number
                                                type="number"
                                                placeholder="可获得数量"
                                                v-model="item.exchangeNum"
                                                :disabled="!canEdit"
                                                :min="1"
                                                :max="item.num"
                                            ></el-input-number>
                                        </el-tooltip>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-button
                                            :disabled="!canEdit"
                                            v-if="awardList.length >= 2"
                                            @click.prevent="removeitem(item, awardList)"
                                            >删除</el-button
                                        >
                                    </el-col>
                                </el-row>
                            </el-form-item>
                        </el-form>

                        <div class="exchange-operation">
                            <el-button :disabled="!canEdit" @click="additem(awardList)" icon="el-icon-plus">
                                增加获得藏品
                            </el-button>
                        </div>
                    </fieldset>
                </div>

                <div class="exchange-footer">
                    <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>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: 'ActivityCollectionEdit',
    created() {
        if (this.$route.query.id) {
            this.$http
                .get('activityCollection/get/' + this.$route.query.id)
                .then(res => {
                    console.log(res, 'res');
                    this.awardList = res.awardList;
                    this.activities = res.activities;
                    this.formData = res;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
    },
    data() {
        return {
            saving: false,
            activities: [
                {
                    collectionId: '',
                    collectionName: '',
                    mustNeedCollected: true,
                    notDestroy:false,
                    num: 1
                }
            ],
            awardList: [
                {
                    collectionId: '',
                    collectionName: '',
                    num: 1,
                    exchangeNum: 1,
                    airDropType:"asset",
                }
            ],
            formData: {
                projectId: this.$store.state.projectId,
                type: 'ONE_TO_MANY',
                needCollectedNum: 1
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入名称',
                        trigger: 'blur'
                    }
                ],
                pic: [
                    {
                        required: true,
                        message: '请上传图片',
                        trigger: 'blur'
                    }
                ],
                collectionId: [
                    {
                        required: true,
                        message: '请选择兑换藏品',
                        trigger: 'blur'
                    }
                ],
                num: [
                    {
                        required: true,
                        message: '请输入兑换数量',
                        trigger: 'blur'
                    }
                ],
                startTime: [
                    {
                        required: true,
                        message: '请输入活动开始时间',
                        trigger: 'change'
                    }
                ],
                endTime: [
                    {
                        required: true,
                        message: '请输入活动结束时间',
                        trigger: 'change'
                    }
                ],
                total: [
                    {
                        required: true,
                        message: '请输入发行数量',
                        trigger: 'blur'
                    }
                ],
                awardCollectionId: [
                    {
                        required: true,
                        message: '请选择获得藏品',
                        trigger: 'blur'
                    }
                ]
            }
        };
    },
    computed: {
        canEdit() {
            return !this.$route.query.id;
        }
    },
    methods: {
        changeProject(val) {
            //因为选择的是旧项目数据，所以清空选择的
            this.activities.forEach(item => {
                item.collectionId = '';
            });
            this.awardList.forEach(item => {
                item.collectionId = '';
            });
        },
        onSave() {
            let list = [];
            list.push(this.submitForm('form'), this.submitForm('formref'), this.submitForm('formlist'));
            Promise.all(list).then(() => {
                const data = {
                    activities: this.activities,
                    awardList: this.awardList,
                    ...this.formData
                };
                console.log(data, 'data');
                this.submit();
            });
        },
        submitForm(formName) {
            return new Promise((resolve, reject) => {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        resolve();
                    } else reject();
                });
            });
        },
        removeitem(item, that) {
            var index = that.indexOf(item);
            if (index !== -1) {
                that.splice(index, 1);
            }
        },
        additem(that) {
            that.push({
                collectionId: '',
                collectionName: '',
                mustNeedCollected: true,
                notDestroy:false,
                num: 1,
                exchangeNum: 1,
                key: Date.now(),
                airDropType:"asset",
            });
        },
        submit() {
            // let data = { ...this.formData };
            const data = {
                activities: this.activities,
                awardList: this.awardList,
                ...this.formData
            };
            this.saving = true;
            this.$http
                .post('/activityCollection/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(`/activityCollection/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 || '删除失败');
                    }
                });
        },
        changeCollection(selected, item) {
            if(selected){
                item.collectionName = selected.name;
            }
            
        }
    }
};
</script>
<style lang="less" scoped>
/deep/.el-input.is-disabled .el-input__inner {
    color: #7c7e7e;
}
/deep/.el-radio__input.is-disabled + span.el-radio__label {
    color: #7c7e7e;
}

.exchange-wrapper {
    display: block;

    .first {
        margin-top:10px;
    }

    .two {
        margin-top:10px;
    }
}

.exchange-footer {
    padding-top: 30px;
}

.exchange-operation {
    padding: 10px;
}
</style>
