<template>
    <div class="edit-view">
        <el-form
            :model="formData"
            :rules="rules"
            ref="form"
            label-width="52px"
            label-position="right"
            size="small"
            style="max-width: 500px;"
        >
            <el-form-item prop="name" label="名称">
                <el-input v-model="formData.name" :disabled="!!formData.id"></el-input>
            </el-form-item>
            <el-form-item prop="content" label="内容" style="width:800px">
                <div v-if="formData.name === '游玩项目'">
                    <el-form
                        v-for="(item, i) in list"
                        :key="i"
                        :model="item"
                        ref="subform"
                        label-position="right"
                        label-width="60px"
                        class="subform"
                        :rules="subrule"
                    >
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="item.name"></el-input>
                        </el-form-item>
                        <el-form-item label="描述" prop="desc">
                            <el-input v-model="item.desc" :rows="5" type="textarea"></el-input>
                        </el-form-item>
                        <el-form-item label="视频" prop="video">
                            <video-upload v-model="item.video"></video-upload>
                        </el-form-item>
                        <el-form-item label="图片" prop="img">
                            <multi-upload v-model="item.img"></multi-upload>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="delItem(i)">删除</el-button>
                        </el-form-item>
                    </el-form>
                    <el-button @click="list.push({ name: '', desc: '', img: [] })">添加</el-button>
                </div>
                <rich-text v-model="formData.content" v-else></rich-text>
            </el-form-item>
            <el-form-item>
                <el-button @click="onSave" :loading="saving" type="primary">保存</el-button>
                <el-button @click="onDelete" :loading="saving" type="danger" v-if="formData.id">删除 </el-button>
                <el-button @click="$router.go(-1)">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
export default {
    name: 'ArticleEdit',
    created() {
        if (this.$route.query.id) {
            this.$http
                .get('article/get/' + this.$route.query.id)
                .then(res => {
                    this.formData = res;
                    if (res.name === '游玩项目') {
                        this.list = JSON.parse(res.content) || [];
                    }
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
    },
    data() {
        return {
            saving: false,
            formData: {},
            rules: {},
            list: [],
            subrule: {
                name: { required: true, message: '请输入名称', trigger: 'blur' },
                desc: { required: true, message: '请输入描述', trigger: 'blur' },
                img: {
                    validator: (rule, value, callback) => {
                        if (value && value.length > 0) {
                            callback();
                        } else {
                            callback(new Error('请上传图片'));
                        }
                    },
                    trigger: 'blur'
                }
            }
        };
    },
    computed: {
        headers() {
            return {
                Authorization: 'Bearer ' + localStorage.getItem('token')
            };
        }
    },
    methods: {
        onSave() {
            if (this.formData.name === '游玩项目') {
                Promise.all(this.$refs.subform.map(i => i.validate())).then(() => {
                    this.$refs.form.validate(valid => {
                        if (valid) {
                            this.submit();
                        } else {
                            return false;
                        }
                    });
                });
            } else {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.submit();
                    } else {
                        return false;
                    }
                });
            }
        },
        submit() {
            let data = { ...this.formData };
            if (this.formData.name === '游玩项目') {
                data.content = JSON.stringify(this.list);
            }
            this.saving = true;
            this.$http
                .post('/article/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.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/article/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);
                    }
                });
        },
        delItem(i) {
            this.list.splice(i, 1);
        }
    }
};
</script>
<style lang="less" scoped>
.subform {
    padding: 16px 16px 1px 16px;
    background: #f2f3f5;
    border-radius: 8px;
    border: 1px solid #eee;
    margin-bottom: 20px;
}
</style>
