<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="title" label="活动名称">
                        <el-input v-model="formData.title" :disabled="!canEdit"></el-input>
                    </el-form-item>
                    <el-form-item prop="description" label="活动描述">
                        <el-input v-model="formData.description" :disabled="!canEdit"></el-input>
                    </el-form-item>
                    <el-form-item prop="viewType" label="抽奖形式">
                        <el-radio-group v-model="formData.viewType" >
                            <el-radio label="SUDOKU" :disabled="!canEdit" border>九宫格</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    
                    <el-form-item prop="needCollectedNum" label="积分数量">
                        <el-tooltip
                            class="item"
                            effect="dark"
                            content="此选项为活动每次点击需要消耗的积分数量"
                            placement="top-start"
                        >
                            <el-input-number
                                type="number"
                                v-model="formData.cost"
                                :disabled="!canEdit"
                                :min="1"
                            ></el-input-number>
                        </el-tooltip>
                    </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="选择日期时间"
                        >
                        </el-date-picker>
                    </el-form-item>

                </el-form>

                <div class="exchange-wrapper">
                    <fieldset class="two">
                        <legend>增加奖品</legend>
                        <el-form
                            :model="{ awardList }"
                            ref="formlist"
                            label-position="right"
                            label-width="100px"
                            size="small"
                            :inline="true"
                        >
                            
                            <div v-for="(item, index) in awardList"
                                :key="index"
                                :label="'可获得奖品' + (index + 1)"  class="item-line">
                                <el-form-item
                                    :prop="`awardList[${index}].type`"
                                    :rules="awardFormRules" class="item-cell">
                                    <el-select
                                        v-model="item.type"
                                        filterable
                                        placeholder="奖品类型"
                                        style="width: 100%"
                                        @change="changType(item)"
                                        :disabled="!canEdit"
                                    >
                                        <el-option
                                            v-for="row in typeList"
                                            :label="row.label"
                                            :value="row.value"
                                            :key="row.value"
                                        >
                                            <span style="float: left">{{ row.label }}</span>
                                            <span style="float: right; color: #8492a6; font-size: 13px"
                                                >#{{ row.value }}</span
                                            >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item
                                    :prop="`awardList[${index}].awardCollectionId`"
                                    :rules="awardFormRules" v-if="item.type == 'ASSET'" class="item-cell">
                                   <collection-search
                                            v-model="item.awardCollectionId"
                                            :disabled="!canEdit"
                                            style="width: 100%"
                                            @select="changeCollection(arguments[0], item)"
                                            :projectId="formData.projectId"
                                        ></collection-search>
                                </el-form-item>
                                <el-form-item v-if="item.type == 'MATERIAL' || item.type == 'EMPTY'" class="item-cell">
                                    <el-upload
                                            class="upload-demo"
                                            :action="uploadUrl"
                                            multiple
                                            :limit="1"
                                            :before-remove="
                                                (response, file, fileList) =>
                                                    beforeRemove(response, file, fileList, item)
                                            "
                                            :on-success="
                                                (response, file, fileList) =>
                                                    handleSuccess(response, file, fileList, item)
                                            "
                                        >
                                            <el-button size="small" type="primary" :disabled="!canEdit"
                                                >上传图片</el-button
                                            >
                                        </el-upload>
                                </el-form-item>
                                <el-form-item :prop="`awardList[${index}].pic`"
                                    :rules="awardFormRules"  class="item-cell">
                                   <el-image :src="item.pic" lazy  :preview-src-list="[item.pic]" style="height:80px;vertical-align:middle;" ></el-image>
                                </el-form-item>

                                <el-form-item  :prop="`awardList[${index}].name`"
                                    :rules="awardFormRules" class="item-cell">
                                    <el-tooltip
                                            class="item"
                                            effect="dark"
                                            content="奖品名称"
                                            placement="top-start"
                                        >
                                             <el-input placeholder="奖品名称" :disabled="!canEdit" v-model="item.name"></el-input>
                                        </el-tooltip>
                                </el-form-item>
                                <el-form-item
                                    :prop="`awardList[${index}].num`"
                                    :rules="awardFormRules" class="item-cell">
                                    <el-tooltip
                                            class="item"
                                            effect="dark"
                                            content="可获得的奖品总数量"
                                            placement="top-start"
                                        >
                                            <el-input-number
                                                type="number"
                                                placeholder="奖品总数"
                                                v-model="item.num"
                                                :disabled="!canEdit"
                                                :min="0"
                                            ></el-input-number>
                                        </el-tooltip>
                                </el-form-item>
                                <el-form-item class="item-cell">
                                    <el-tooltip
                                            class="item"
                                            effect="dark"
                                            content="奖品等级，由小到大排列"
                                            placement="top-start"
                                        >
                                            <el-input-number
                                                type="number"
                                                placeholder="奖品排序"
                                                v-model="item.orderNum"
                                                :disabled="!canEdit"
                                                :min="1"
                                            ></el-input-number>
                                        </el-tooltip>
                                </el-form-item>
                                <el-form-item >
                                    <el-tooltip
                                        class="item"
                                        effect="dark"
                                        content="是否稀有的开关，默认否"
                                        placement="top-start"
                                    >
                                         <el-switch
                                                :disabled="!canEdit"
                                                v-model="item.rare"
                                            ></el-switch>
                                    </el-tooltip>
                                </el-form-item>
                                <el-form-item>
                                   <el-button
                                            :disabled="!canEdit"
                                            v-if="awardList.length >= 2"
                                            @click.prevent="removeitem(item, awardList)"
                                            >删除</el-button
                                        >
                                </el-form-item>
                                <el-form-item v-if="!canEdit">
                                    剩余库存：{{item.stock}}
                                </el-form-item>
                                
                            </div>
                        </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>
import resolveUrl from 'resolve-url';

export default {
    name: 'PointRewardActivityEdit',
    created() {
        this.uploadUrl = resolveUrl(this.$baseUrl, 'upload/file');
        if (this.$route.query.id) {
            this.$http
                .get(`pointActivity/get/${this.$route.query.id}`)
                .then(res => {
                    this.awardList = res.awards;
                    this.formData = res;
                })
                .catch(e => {
                    this.$message.error(e.error);
                });
        }
    },
    data() {
        return {
            saving: false,
            typeList: [
                {
                    value: 'MATERIAL',
                    label: '实物'
                },
                {
                    value: 'ASSET',
                    label: '藏品'
                },
                {
                    value: 'EMPTY',
                    label: '空奖品'
                }
            ],
            awardList: [
                {
                    awardCollectionId: '',
                    pic: '',
                    name: '',
                    type: '',
                    num: 1,
                    rare: false,
                    orderNum: 0
                }
            ],
            formData: {
                projectId: this.$store.state.projectId,
                viewType: 'SUDOKU',
                cost: 1,
                needCollectedNum: 1
            },
            rules: {
                title: [
                    {
                        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'
                    }
                ]
            },
            awardFormRules:[                
                { required: true, message: '不能为空', trigger: 'blur' }
            ]
        };
    },
    computed: {
        canEdit() {
            return !this.$route.query.id;
        }
    },
    methods: {
        handleSuccess(response, file, fileList, item) {
            console.log(response, file, fileList, item, '4==========');
            return (item.pic = response);
        },
        beforeRemove(response, file, fileList, item) {
            this.$confirm(`确定移除上传的图片？`)
                .then(() => {
                    return (item.pic = '');
                })
                .catch(e => {});
        },
        changType(val) {
            console.log(val, 'val');
        },
        changeProject(val) {
            //因为选择的是旧项目数据，所以清空选择的
            this.activities.forEach(item => {
                item.collectionId = '';
            });
            this.awardList.forEach(item => {
                item.collectionId = '';
            });
        },
        onSave() {
            let list = [];
            list.push(this.submitForm('form'), this.submitForm('formlist'));
            Promise.all(list).then(() => {
                const data = {
                    activities: this.activities,
                    awardList: this.awardList,
                    ...this.formData
                };
                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({
                name: '', // 奖品名称
                pic: '', //奖品地址
                type: '', // 奖品类型
                awardCollectionId: '', //获得的藏品Id
                num: 1, // 可获得的奖品数量
                rare: false, // 是否稀有
                orderNum: '', // 排序字段
                key: Date.now()
            });
        },
        submit() {
            // let data = { ...this.formData };
            const data = {
                awards: this.awardList,
                ...this.formData
            };
            this.saving = true;
            this.$http
                .post('/pointActivity/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.name = selected.name;
                item.pic = selected.pic[0].url;
            }
            
        }
    }
};
</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: flex;

    .first {
        flex: 2;
    }

    .two {
        flex: 3;
    }
}

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

.exchange-operation {
    padding: 10px;
}

.item-line{
    border-bottom:solid 1px #efefef;
    margin-bottom:6px;
    max-height:80px;
    display:flex;
    align-items:center;
}

.item-cell{
    width:160px;
    padding:8px;
}
</style>
