<!--
 * @Description: 版本管理
 * @Author: xiaofengzhou
 * @Email: 2946471396@qq.com
 * @Date: 2022-09-05 10:36:17
 * @LastEditTime: 2022-10-19 12:13:27
 * @LastEditors: xiaofengzhou
-->
<!-- 版本管理 -->
<template>
    <div class=''>
        <div class="table-btn">
            <a-button type="normal" @click="addNewHelp">
                <span class="iconfont icon-add" style="color: #006cff;font-size: 14px;">添加版本</span>
            </a-button>
        </div>
        <!-- 管理功能 -->
        <a-table :dataSource="dataSource" :columns="columns" :pagination="false">
            <template slot="action" slot-scope="text, record">
                <span>
                    <a @click="showEdit(record)">修改</a>&nbsp;
                    <a @click="delCurrent(record)">删除</a>&nbsp;
                </span>
            </template>
        </a-table>
        <div style="text-align:right ;margin-top:20px">
            <a-pagination :page-size="10" @change="onShowPageChange" v-model="pagination.current"
                :total="pagination.totalCount" />
        </div>
        <!-- 编辑 -->
        <a-modal v-model="visible" @ok="onOk" @cancel="onCancel" width="1000px" style="overflow: scroll;">
            <div class="head">
                <span class="iconfont icon-repo head-icon"></span>
                &nbsp;&nbsp;
                <span class="head-text">编辑版本详情</span>

            </div>
            <a-form-model :style="{ width: '100%' }" layout="horizontal" v-bind="{
                labelCol: { span: 6 },
                wrapperCol: { span: 16 },
            }" :colon="true" labelAlign="right" :model="formData" :rules="rules" ref="form">
                <a-form-model-item label="请输入名称" prop="versionName" v-bind="{}">
                    <a-input size="large" v-model="formData.versionName" placeholder="请输入名称"></a-input>
                </a-form-model-item>
                <a-form-model-item label="请输入版本描述" prop="versionDescription" v-bind="{}">
                    <a-input size="large" v-model="formData.versionDescription" placeholder="请输入版本描述"></a-input>
                </a-form-model-item>
                <a-form-model-item label="请输入版本描述" prop="versionContent" v-bind="{}">
                    <div style="border:1px solid black">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                            :mode="mode" />
                        <Editor style="height: 400px; overflow-y: hidden;" v-model="formData.versionContent"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
                    </div>

                </a-form-model-item>
            </a-form-model>


        </a-modal>

        <ConfirmDeletion :delete="sureDelete" ref="ConfirmDeletion" />
        <PromptBox ref="PromptBox" />
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {time} from '../../../../packages/utils/time'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import ConfirmDeletion from '../../../components/ConfirmDeletion';
import PromptBox from '../../../components/PromptBox';
import { getVersionList, deleteVersion, addVersion, editVersion, uploadImagesForVersion } from '../../../../packages/api/manage'
export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
        Editor, Toolbar, ConfirmDeletion, PromptBox
    },
    data() {
        //这里存放数据
        return {
            action: "view",
            currentEdit: '',
            currentDel: '',
            // 分页数据
            pagination: {
                current: 1,
                pageSize: 10,
                pageNum: 1,
                totalCount: 10
            },
            formData: {
                versionName: '',
                versionDescription: '',
                versionContent: ''
            },
            defaultFormData: {
                versionName: '',
                versionDescription: '',
                versionContent: ''
            },

            // 编辑器实例
            editor: null,
            toolbarConfig: {
                excludeKeys: [
                    'insertVideo',
                    'uploadVideo',
                    'group-video'
                ]
            },
            editorConfig: {
                placeholder: '请输入内容...', MENU_CONF: {
                    //配置上传图片
                    uploadImage: {
                        customUpload: this.uploadImg
                    }
                }
            },
            mode: 'default', // or 'simple'
            visible: false,

            dataSource: [

            ],
            columns: [
                {
                    title: "序号",
                    dataIndex: "index",
                    key: "index",
                    align: 'center'
                },
                {
                    title: "版本号",
                    dataIndex: "versionName",
                    key: "versionName",
                    align: 'center'
                },
                {
                    title: "版本描述",
                    dataIndex: "versionDescription",
                    key: "versionDescription",
                    align: 'center'
                },
                {
                    title: "操作人",
                    dataIndex: "operator.loginName",
                    key: "operator.loginName",
                    align: 'center'
                },

                {
                    title: "操作时间",
                    dataIndex: "createTime",
                    key: "createTime",
                    customRender: (text, record, index) => {
                        if (record.updateTime !== null) {
                            return time.formatTime(record.updateTime, "yyyy/MM/dd")
                        } else {
                            return time.formatTime(record.createTime, "yyyy/MM/dd")
                        }

                    },
                    align: 'center'
                },
                {
                    title: "操作栏",
                    key: "action",
                    scopedSlots: { customRender: "action" },
                    align: 'center'
                },
            ],
            rules: {
                versionName: [
                    {
                        required: true,
                        message: "名称不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "名称长度不能大于255",
                        trigger: "blur",
                    },
                ],
                versionDescription: [
                    {
                        required: true,
                        message: "类别不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "类别长度不能大于255",
                        trigger: "blur",
                    },
                ],
                versionContent: [
                    {
                        required: true,
                        message: "简介不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "简介长度不能大于255",
                        trigger: "blur",
                    },
                ],
                resolvent: [
                    {
                        required: true,
                        message: "示例不能为空",
                        trigger: "blur",
                    }

                ],
            }



        };
    },
    //监听属性 类似于data概念
    computed: {


    },
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        getData(pageNum = 1, pageSize = 10, versionName = '') {
            getVersionList({ pageNum: pageNum, pageSize: pageSize, versionName: versionName }).then((res) => {
                this.pagination.totalCount = res.result.totalCount
                let result = res.result.data
                let resolve = []
                result.map((item, index) => {
                    item.index = (this.pagination.current - 1) * 10 + index + 1
                    item.key = item.versionId
                    resolve.push(item)
                })
                this.dataSource = resolve


            })
        },

        onOk() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const { versionName, versionDescription, versionContent } = this.formData
                    if (this.action === 'add') {
                        let params = { versionName: versionName, versionDescription: versionDescription, versionContent: versionContent }
                        // 添加的接口
                        addVersion(params).then((res) => {
                            this.visible = false
                            this.$refs.PromptBox.init("添加成功")
                            this.$refs.PromptBox.visible = true
                            this.getData(this.pagination.current, 10)
                        }).catch(err => {
                            this.$message.error("添加失败")
                        })


                    } else if (this.action === 'edit') {
                        let params = { versionName: versionName, versionDescription: versionDescription, versionContent: versionContent, versionId: this.currentEdit }
                        editVersion(params).then((res) => {
                            this.visible = false
                            this.$refs.PromptBox.init("修改成功")
                            this.$refs.PromptBox.visible = true

                            this.getData(this.pagination.current, 10)
                        }).catch(err => {
                            this.$message.error("修改失败")
                        })
                        //修改的接口


                    }

                }
            })
        },
        onCancel() {
            this.formData = Object.assign({}, this.defaultFormData)

        },
        showEdit(record) {
            this.currentEdit = record.versionId
            this.action = 'edit'
            this.visible = true

            this.formData = Object.assign({}, record)
        },
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
        addNewHelp() {
            // 赋初始值
            this.formData = Object.assign({}, this.defaultFormData)

            this.action = 'add'
            this.visible = true
        },
        delCurrent(record) {
            this.currentDel = record.versionId
            // 是否确认删除
            // 删除api
            this.$refs.ConfirmDeletion.visible = true


        },
        sureDelete() {
            deleteVersion(this.currentDel).then(res => {
                this.$refs.ConfirmDeletion.visible = false

                // 如果删除成功
                this.$refs.PromptBox.init("删除成功")
                this.$refs.PromptBox.visible = true
                let calcPage = this.calcPageNo(this.pagination.totalCount, this.pagination.current, 10, 1)
                this.getData(calcPage, 10)
                // 重新请求数据
            }).catch(err => {
                this.$message.error("删除失败")
            })


        },
        uploadImg(file, insertFn) {
            let imgData = new FormData();
            imgData.append('file', file);

            uploadImagesForVersion(imgData).then(res => {
                insertFn(res.result);
            }).catch(err => {
                this.$message.error("图片上传失败")
            })


        },
        onShowPageChange(page, pagesize) {
            // 修改当前页码
            this.pagination.current = page

            // this.getData(page, pagesize, this.templateName !== "" ? this.templateName : '', this.templateType !== "" ? this.templateType : '')
        },
        // 计算分页
        calcPageNo(total, pageNo = 1, pageSize = 10, delNum = 1) {
            const restNum = total - pageSize * (pageNo - 1)
            let pageNoDiff = Math.floor((delNum - restNum) / pageSize) + 1
            pageNoDiff < 0 && (pageNoDiff = 0)
            pageNo = pageNo - pageNoDiff
            pageNo < 1 && (pageNo = 1)
            return pageNo
        },

    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.getData()
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped lang="less">
/deep/ .ant-input{
    font-size: 16px !important;
}
/deep/ .ant-select{
    font-size: 16px !important;
}
/deep/ .ant-btn{
    font-size: 16px !important;
}

/deep/ .ant-form label{
    font-size: 16px !important;
}
/deep/.ant-modal-body {
    height: 500px;
    overflow: scroll;
}
/deep/ .ant-modal-body{
    height: 700px;
}

.head {
    text-align: center;
    margin-bottom: 5px;

    .head-icon {
        font-size: 28px;
        vertical-align: middle;
        color: #284f84;
    }

    .head-text {
        font-size: 18px;
        vertical-align: middle;
        color: #284f84;
    }
}

.table-btn {
    text-align: right;
    // margin-bottom: 20px;
}

.table-btn button {
    margin-left: 5px;
}

/deep/ .ant-table-tbody tr {
    background-color: white;
}
</style>