<template>
    <div>
        <!--    面包屑导航区    -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>测试发布</el-breadcrumb-item>
            <el-breadcrumb-item>发布版本管理</el-breadcrumb-item>
        </el-breadcrumb>

        <!--    卡片    -->
        <el-card>
            <!--    搜索    -->
            <el-form :inline="true">
                <el-form-item label="测试周期">
                    <el-date-picker v-model="queryDateList" type="daterange" :editable="false"
                                    format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" range-separator="至"
                                    start-placeholder="开始日期" end-placeholder="结束日期" clearable></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="queryPublishVersionByPage">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="showCreatePublishVersionDialog">新增发布计划</el-button>
                </el-form-item>
            </el-form>
            <!--    列表    -->
            <el-table :data="publishVersionTable" style="width: 100%" border
                      :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}">
                <el-table-column type="index"/>
                <el-table-column prop="versionName" label="版本名称" showOverflowTooltip/>
                <el-table-column prop="versionDescribe" label="版本描述" showOverflowTooltip/>
                <el-table-column prop="startTime" label="版本开始时间" showOverflowTooltip/>
                <el-table-column prop="endTime" label="发布时间" showOverflowTooltip/>
                <el-table-column prop="createUserName" label="创建人" showOverflowTooltip/>
                <el-table-column prop="status" label="发布状态" :formatter="statusFormatter" showOverflowTooltip/>
                <el-table-column label="操作" align="center" min-width="200px" showOverflowTooltip>
                    <template v-slot="{row}">
                        <el-button type="primary" size="mini" v-if="row.status === 'UN_PUBLISH'" @click="showRelationSubmitDialog(row.id)">关联迭代</el-button>
                        <el-button type="primary" size="mini" v-if="row.status === 'UN_PUBLISH'" @click="showEditPublishVersionDialog(row.id)">编辑</el-button>
                        <el-button type="primary" size="mini" @click="toDetail(row.id)">详情</el-button>
                        <el-button type="primary" size="mini" v-if="row.status === 'UN_PUBLISH'" @click="publish(row.id)">发布</el-button>
                        <el-button type="info" size="mini" v-else-if="row.status !== 'UN_PUBLISH'">已发布</el-button>

                    </template>
                </el-table-column>
            </el-table>
            <!--    分页    -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryPublishVersionParam.page"
                :page-sizes="[10, 20, 50, 100, 200]"
                :page-size="queryPublishVersionParam.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!--    创建版本的dialog    -->
        <el-dialog
            title="新增发布计划"
            :visible.sync="createPublishVersionDialogVisible"
            width="65%"
            :before-close="createPublishVersionDialogClose">
            <el-form :model="createPublishVersionForm" :rules="createPublishVersionFormRules"
                     ref="createPublishVersionFormRef" label-width="100px" inline>
                <el-form-item label="版本名称" prop="versionName">
                    <el-input v-model.trim="createPublishVersionForm.versionName"/>
                </el-form-item>
                <el-form-item label="版本描述" prop="versionDescribe">
                    <el-input v-model.trim="createPublishVersionForm.versionDescribe"/>
                </el-form-item>
                <el-form-item label="版本周期" prop="dateList">
                    <el-date-picker v-model="createPublishVersionForm.dateList" type="daterange" :editable="false"
                                    format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" range-separator="至"
                                    start-placeholder="开始日期" end-placeholder="结束日期" clearable></el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="createPublishVersionDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="createPublishVersion">确 定</el-button>
            </span>
        </el-dialog>

        <!--    编辑版本的dialog    -->
        <el-dialog
            title="新增发布计划"
            :visible.sync="editPublishVersionDialogVisible"
            width="65%"
            :before-close="editPublishVersionDialogClose">
            <el-form :model="editPublishVersionForm" :rules="editPublishVersionFormRules" ref="editPublishVersionFormRef" label-width="100px" inline>
                <el-form-item label="版本名称" prop="versionName">
                    <el-input v-model.trim="editPublishVersionForm.versionName"/>
                </el-form-item>
                <el-form-item label="版本描述" prop="versionDescribe">
                    <el-input v-model.trim="editPublishVersionForm.versionDescribe"/>
                </el-form-item>
                <el-form-item label="版本周期" prop="dateList">
                    <el-date-picker v-model="editPublishVersionForm.dateList" type="daterange" :editable="false"
                                    format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" range-separator="至"
                                    start-placeholder="开始日期" end-placeholder="结束日期" clearable></el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editPublishVersionDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editPublishVersion">确 定</el-button>
            </span>
        </el-dialog>

        <!--    关联迭代的dialog    -->
        <el-dialog title="关联迭代" width="50%"
                   :visible.sync="relationSubmitDialogVisible" :before-close="relationSubmitDialogClose">
            <el-form :model="relationSubmitForm" :rules="relationSubmitFormRules" ref="relationSubmitFormRef" label-width="100px" inline>
                <el-form-item label="可选迭代" prop="sprintIdList" style="width: 100%">
                    <el-select v-model="relationSubmitForm.sprintIdList" multiple placeholder="请选择" filterable style="width: 600px">
                        <el-option v-for="item in sprintList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="relationSubmitDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRelationSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "PublishVersionPage",
    data() {
        return {
            queryDateList: [],
            // 分页查询报告参数
            queryPublishVersionParam: {
                startTime: null,
                endTime: null,
                page: 1,
                size: 10
            },
            publishVersionTable: null,
            total: 0,
            // 发布状态显示枚举
            statusMap: {
                UN_PUBLISH: '未发布',
                PUBLISH: '已发布',
            },

            // 新增
            createPublishVersionDialogVisible: false,
            createPublishVersionForm: {},
            createPublishVersionFormRules: {
                versionName: [
                    {required: true, message: '请输入版本名称', trigger: 'blur'},
                ],
                versionDescribe: [
                    {required: true, message: '请输入版本描述', trigger: 'blur'},
                ],
                dateList: [
                    {required: true, message: '请选择版本周期', trigger: 'blur'},
                ]
            },


            // 关联迭代
            relationSubmitDialogVisible: false,
            sprintList: [],
            relationSubmitForm: {},
            relationSubmitFormRules: {
                sprintIdList: [
                    {required: true, message: '请选择关联的迭代', trigger: 'blur'},
                ],
            },

            // 编辑
            editPublishVersionDialogVisible: false,
            editPublishVersionForm: {},
            editPublishVersionFormRules: {
                versionName: [
                    {required: true, message: '请输入版本名称', trigger: 'blur'},
                ],
                versionDescribe: [
                    {required: true, message: '请输入版本描述', trigger: 'blur'},
                ],
                dateList: [
                    {required: true, message: '请选择版本周期', trigger: 'blur'},
                ]
            },
        }
    },
    methods: {
        // 状态格式化
        statusFormatter(row, column, cellValue) {
            return this.statusMap[cellValue]
        },
        // 版本内容分页查询
        async queryPublishVersionByPage() {
            if (this.queryDateList !== null && this.queryDateList !== [] && this.queryDateList.length !== 0) {
                this.queryPublishVersionParam.startTime = this.queryDateList[0]
                this.queryPublishVersionParam.endTime = this.queryDateList[1]
            } else {
                this.queryPublishVersionParam.startTime = null
                this.queryPublishVersionParam.endTime = null
            }
            const res = await this.$api.post("/sonar/publish/version/pages", this.queryPublishVersionParam)
            if (res.code !== 200 || res.data === null) return this.$message.error(res.message)
            this.publishVersionTable = res.data.records
            this.total = res.data.total
        },
        // 监听页大小改变的事件
        handleSizeChange(newSize) {
            this.queryPublishVersionParam.size = newSize;
            this.queryPublishVersionByPage()
        },
        // 监听页码改变的事件
        handleCurrentChange(newPage) {
            this.queryPublishVersionParam.page = newPage;
            this.queryPublishVersionByPage()
        },

        // 显示新增发布计划的弹框
        showCreatePublishVersionDialog() {
            this.createPublishVersionDialogVisible = true
        },
        // 关闭新增发布计划的弹框
        createPublishVersionDialogClose() {
            this.createPublishVersionForm = {}
            this.createPublishVersionDialogVisible = false
        },
        // 保存新增的发布计划
        createPublishVersion() {
            this.$refs.createPublishVersionFormRef.validate(async (valid) => {
                if (!valid) return
                this.createPublishVersionForm.startTime = this.createPublishVersionForm.dateList[0]
                this.createPublishVersionForm.endTime = this.createPublishVersionForm.dateList[1]
                this.createPublishVersionForm.createUserName = localStorage.getItem('username');
                const res = await this.$api.post("/sonar/publish/version/save", this.createPublishVersionForm)
                if (res.code !== 200 || res.data === null) return this.$message.error(res.message)
                this.$message.success("保存成功!")
                await this.queryPublishVersionByPage();
                this.createPublishVersionDialogClose()
            })
        },

        // 显示关联迭代的弹框
        async showRelationSubmitDialog(publishVersionId) {
            // 初始化关联列表
            this.relationSubmitForm = {
                sprintIdList: [] // 必须先初始化
            }
            this.relationSubmitForm.publishVersionId = publishVersionId
            // 根据id 查询可关联的迭代内容
            const canRelationRes = await this.$api.get("/sonar/publish/version/getCanRelationsById", {publishVersionId})
            if (canRelationRes.code !== 200 || canRelationRes.data === null) return this.$message.error(canRelationRes.message)
            this.sprintList = canRelationRes.data // 版本范围内的全部迭代信息

            const relationRes = await this.$api.get("/sonar/publish/version/getRelationIdsById", {publishVersionId})
            if (relationRes.code !== 200 || relationRes.data === null) return this.$message.error(relationRes.message)
            if (this.sprintList !== null && this.sprintList.length !== 0) {
                // 版本关联的迭代信息
                relationRes.data.forEach(a => this.relationSubmitForm.sprintIdList.push(a))
            }
            this.relationSubmitDialogVisible = true
        },
        // 关闭关联迭代的弹框
        relationSubmitDialogClose() {
            this.relationSubmitDialogVisible = false
        },
        // 保存关联的迭代
        saveRelationSubmit() {
            console.log(this.relationSubmitForm)
            this.$refs.relationSubmitFormRef.validate(async (valid) => {
                if (!valid) return
                const res = await this.$api.post("/sonar/publish/version/relationsById/" + this.relationSubmitForm.publishVersionId, this.relationSubmitForm.sprintIdList)
                if (res.code !== 200 || res.data === null) return this.$message.error(res.message)
                this.$message.success("关联成功!")
                await this.queryPublishVersionByPage();
            })
            this.relationSubmitDialogClose() // 关闭弹框
        },

        // 显示编辑版本的弹框
        async showEditPublishVersionDialog(publishVersionId) {
            this.editPublishVersionForm.id = publishVersionId
            const res = await this.$api.get("/sonar/publish/version/findById", {publishVersionId})
            if (res.code !== 200 || res.data === null) return this.$message.error(res.message)
            this.editPublishVersionForm = {...res.data, dateList: []}
            console.log(this.editPublishVersionForm)
            this.editPublishVersionForm.dateList.push(this.editPublishVersionForm.startTime, this.editPublishVersionForm.endTime)
            this.editPublishVersionDialogVisible = true
        },
        // 关闭编辑版本的弹框
        editPublishVersionDialogClose() {
            this.editPublishVersionDialogVisible = false
        },
        // 保存编辑的版本
        editPublishVersion() {
            this.$refs.editPublishVersionFormRef.validate(async (valid) => {
                if (!valid) return
                this.editPublishVersionForm.startTime = this.editPublishVersionForm.dateList[0]
                this.editPublishVersionForm.endTime = this.editPublishVersionForm.dateList[1]
                const res = await this.$api.post("/sonar/publish/version/update", this.editPublishVersionForm)
                if (res.code !== 200 || res.data === null) return this.$message.error(res.message)
                this.$message.success("编辑成功!")
                await this.queryPublishVersionByPage();
                this.editPublishVersionDialogClose()
            })
        },

        // 发布
        async publish(publishVersionId) {
            const confirmResult = await this.$confirm(
                '此操作将修改发布状态, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).catch((err) => err)

            if (confirmResult === 'cancel') {
                return this.$message.info('已取消发布！')
            }
            // 确认删除时, 调用接口
            if (confirmResult === 'confirm') {
                const res = await this.$api.postForm("/sonar/publish/version/updateStatusById",
                    {
                        publishVersionId,
                        userName: localStorage.getItem('username')
                    }
                )
                if (res.code !== 200 || res.data === null) return this.$message.error(res.message)
                this.$message.success('版本发布成功!')
                await this.queryPublishVersionByPage()
            }
        },

        // 跳转详情页
        async toDetail(publishVersionId) {
            const res = await this.$api.get("/sonar/publish/version/getRelationIdsById", {publishVersionId})
            if (res.code !== 200 || res.data === null) return this.$message.error(res.message)
            if (!res.data || res.data.length === 0){
                return this.$message.error('当前版本未关联迭代, 请关联后再查看详情')
            }
            this.$router.push(
                {
                    path: '/publish/version/detail/page',
                    query: {
                        publishVersionId: publishVersionId,
                    }
                }
            )
        }
    },
    created() {
        this.queryPublishVersionByPage()
    }
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
    height: 32px;
    line-height: 32px;
}

.el-dialog {
    .el-form-item {
        margin-right: 0;
    }
}

.el-table /deep/ .cell {
    white-space: nowrap;
}

.el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;

    .el-table {
        margin-top: 15px;
        margin-bottom: 15px;
    }

    .el-pagination {
        text-align: center;
        margin-top: 15px;
    }
}

.el-dialog {
    .el-card {
        margin-bottom: 10px;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;

        .summary {
            display: flex;
            flex-direction: column;
            width: 80%;
            color: #8A8C94 !important;

            .summaryTitle {
                line-height: 32px;
                font-size: 16px;
                padding: 0 0 0 18px;
                box-sizing: border-box;
                vertical-align: middle;
            }

            .summaryDetail {
                display: flex;
                justify-content: space-around;
                width: 100%;
                height: 64px;

                .summary-icon {
                    vertical-align: middle;
                    width: 100px;
                    position: relative;
                }

                .summary-icon div {
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translateX(-50%) translateY(-50%);

                    .iconfont {
                        line-height: 64px;
                        height: 64px;
                        width: 64px;
                        font-size: 32px;
                        text-align: center;
                    }
                }

                .labelName {
                    line-height: 32px;
                    font-size: 14px;
                    padding: 0;
                    box-sizing: border-box;
                    vertical-align: middle;
                    display: block;
                }
            }

            .summaryDetail div:not(:first-child) {
                padding-left: 20px;
                border-left: 1px solid #F5F5F5;
            }

            .summaryDetail div:nth-child(2) {
                margin-left: 80px;
                flex: 2;
            }

            .summaryDetail div:nth-child(3) {
                flex: 1;
            }

            .summaryDetail div:nth-child(4) {
                flex: 1;
            }

            .summaryDetail div:nth-child(5) {
                flex: 1;
            }
        }
    }
}


</style>