<template>
    <div class="wrap">
       <el-card shadow="hover" class="mgb20">
            <div class="flex-between">
                <div class="per_title" v-preventReClick @click="$router.back()">
                    <i class="el-icon-arrow-left"></i>
                    <span class="per_back">返回</span>
                    <span class="per_school" v-text="id ? '编辑更新日志' : '新增更新日志'"></span>
                </div>
                <div>
                    <el-button type="primary" round v-preventReClick @click="submit(0)">发布</el-button>
                    <el-button v-if="draft || !id" type="primary" round v-preventReClick @click="submit(1)">草稿</el-button>
                </div>
            </div>              
        </el-card>
        
        <el-card class="page" shadow="hover">
            <el-form class="form" ref="form" label-width="120px" center>
                <el-form-item class="required" label="版本标题">
                    <el-input placeholder="请输入版本标题" v-model="form.versionName" maxlength="30" style="width: 400px" @change="nameChange"></el-input>
                </el-form-item>
                <el-form-item label="封面图片">
                    <el-upload
                        class="avatar-uploader"
                        accept=".jpg,.png,.jpeg"
                        :on-remove="handleRemove"
                        :on-error="uploadError"
                        :on-success="uploadSuccess"
                        :before-remove="beforeRemove"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :action="this.api.fileupload"
                        :headers="headers"
                        name="file"
                    >
                        <img v-if="form.coverUrl" :src="form.coverUrl" class="avatar">
                        <div class="uploader-default" v-else>
                            <i class="el-icon-plus"></i>
                            <p>上传封面</p>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item class="required" label="更新内容">
                    <ul class="contents">
                        <li v-for="(item, i) in form.logContents" :key="i">
                            <div class="action">
                                <el-select v-model="item.type" size="small" placeholder="请选择">
                                    <el-option
                                        v-for="item in funcList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                                <div class="btns">
                                    <i v-if="i === form.logContents.length - 1" class="el-icon-circle-plus-outline" @click="add"></i>
                                    <i class="el-icon-delete" @click="del(i)"></i>
                                </div>
                            </div>
                            <el-input
                                type="textarea"
                                :rows="5"
                                placeholder="请输入"
                                v-model="item.content">
                            </el-input>
                        </li>
                    </ul>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import Setting from '@/setting'
export default {
    data() {
        return {
            id : this.$route.query.id,
            platformId: this.$route.query.platformId,
            draft : this.$route.query.draft === '1',
            headers: {
                token: sessionStorage.getItem("token")
            },
            funcList: [
                {
                    id: 0,
                    name: '新功能'
                },
                {
                    id: 1,
                    name: '修复'
                },
                {
                    id: 2,
                    name: '优化'
                }
            ],
            nameRepeat: false,
            originName: '',
            form: {
                versionName: '',
                coverUrl: '',
                logContents: []
            },
            originContent: {
                type: '',
                content: ''
            },
            submiting: false
        };
    },
    mounted() {
        this.id ? this.getData() : this.form.logContents.push(JSON.parse(JSON.stringify(this.originContent)))
    },
    methods: {
        // 获取详情
        getData() {
            this.$get(`${this.api.logGet}?logId=${this.id}`).then(res => {
                const { log } = res
                this.form = {
                  versionName: log.versionName,
                  coverUrl: log.coverUrl,
                  logContents: log.logContents.length ? log.logContents : [JSON.parse(JSON.stringify(this.originContent))]
                }
                this.originName = log.versionName
            }).catch(res => {})
        },
        // 版本标题判重
        nameChange(val) {
          if (this.originName === val) {
            this.nameRepeat = false
          } else {
            this.$get(`${this.api.checkRepeat}?platformId=${this.platformId}&versionName=${val}`).then(res => {
              this.nameRepeat = false
            }).catch(res => {
              this.nameRepeat = true
            })
          }
        },
        // 新增内容
        add() {
            this.form.logContents.push(JSON.parse(JSON.stringify(this.originContent)))
        },
        // 删除内容
        del(i) {
            this.form.logContents.splice(i, 1)
        },
        handleExceed(files, fileList) { // 上传文件
            util.warningMsg("当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！");
        },
        uploadSuccess(res, file, fileList) {
            this.form.coverUrl = res.data.filesResult.fileUrl
        },
        uploadError(err, file, fileList) {
            this.$message({
                message: "上传出错，请重试！",
                type: "error",
                center: true
            });
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        handleRemove(file, fileList) {
            let fileName = this.coverUrl.replace("https://liuwanr.oss-cn-shenzhen.aliyuncs.com/", "");
            this.$del(`${this.api.fileDeletion}?keys=${fileName}`).then(res => {
                this.coverUrl = ''
            }).catch(res => {});
        },
        // 保存
        submit(draft){
            if (this.submiting) return false
            const { versionName, logContents } = this.form
            const id = this.id
            if (!versionName) return this.$message.error('请输入版本标题')
            if (this.nameRepeat) return this.$message.error('版本名称已存在！')
            if (!logContents.length || !logContents.find(e => e.type !== '' && e.content)) return this.$message.error('请输入更新内容')
            this.submiting = true
            const data = {
                platformId: this.platformId,
                versionName,
                coverUrl: this.form.coverUrl,
                logContents,
                withdraw: 0,
                open: draft, // 启用禁用，0:启用，1:禁用
                draft // 状态，0:发布，1:草稿
            }
            if (id) {
                data.logId = id
                this.$post(this.api.listUpdate, data).then(res => {
                    this.$message.success('编辑成功')
                    this.$router.back()
                }).catch(res => {
                    this.submiting = false
                })
            } else {
                this.$post(this.api.logAdd, data).then(res => {
                    this.$message.success('新增成功')
                    this.$router.back()
                }).catch(res => {
                    this.submiting = false
                })
            }
        },
    }
};
</script>

<style lang="scss" scoped>
.page {
    display: flex;
    justify-content: center;
    min-height: calc(100vh - 310px);
    /deep/.required {
      label:before {
        content: '*';
        margin-right: 5px;
        vertical-align: middle;
        color: #f00;
      }
    }
}
$avatar-width: 104px;
/deep/ .avatar-uploader {
    .el-upload {
        position: relative;
        width: $avatar-width;
        height: auto;
        border: 1px dashed #d9d9d9;
        border-radius: 2px;
        cursor: pointer;
        overflow: hidden;

        &:hover {
            border-color: #409EFF;
        }

        .uploader-default {
            display: flex;
            flex-direction: column;
            justify-content: center;
            width: $avatar-width !important;
            height: $avatar-width;
            text-align: center;
            background: rgba(0, 0, 0, 0.04);

            i {
                font-size: 20px;
                font-weight: bold;
                color: #8c939d;
            }

            p {
                margin-top: 10px;
                font-size: 14px;
                color: rgba(0, 0, 0, 0.65);
                line-height: 1;
            }
        }

        .avatar {
            width: $avatar-width;
            height: $avatar-width;
            display: block;
        }
    }

    .el-upload__tip {
        margin-top: 0;

        p {
            font-size: 14px;
            color: rgba(0, 0, 0, 0.45);
            line-height: 1;

            &:first-child {
                margin-bottom: 5px;
            }
        }
    }
}
.contents {
    width: 700px;
    li {
        padding: 15px;
        margin-bottom: 20px;
        border: 1px dashed #e9e9e9;
        border-radius: 8px;
    }
    .action {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
    }
    .btns {
        i {
            margin-left: 10px;
            color: #9076FF;
            cursor: pointer;
            &:hover {
                opacity: .9;
            }
        }
    }
}
</style>
