<!--
 * @Description: 模板管理
 * @Author: xiaofengzhou
 * @Email: 2946471396@qq.com
 * @Date: 2022-08-03 14:10:07
 * @LastEditTime: 2022-10-26 09:55:50
 * @LastEditors: xiaofengzhou
-->
<template>
    <a-layout>
        <a-layout-header>
            <a-row>
                <a-col :span="2" style="text-align:right">
                    模板名称:
                </a-col>
                <a-col :span="4">
                    <a-input style="margin-left:10px" v-model="templateName" placeholder="请输入模板名称" />
                </a-col>
                <a-col :span="8" style="text-align:center">
                    模板类型:
                    <a-select v-model="templateType" show-search placeholder="请选择模板类型" style="width: 200px"
                        :options="templateTypeOptions" @search="handleTemplateTypeSearch">
                    </a-select>
                </a-col>
                <a-col :span="8" style="text-align:left">
                    <a-button type="normal" @click="clearInput()">重置</a-button>
                    &nbsp;&nbsp;
                    <a-button type="primary" @click="search">查询</a-button>
                </a-col>
            </a-row>
        </a-layout-header>
        <a-layout-content>
            <div class="table-btn">
                <a-button type="normal" @click="showRes">
                    <span class="iconfont icon-system" style="color: #006cff;font-size: 14px;">&nbsp;仓库配置</span>
                </a-button>
                <a-button type="normal" @click="addNewProject">
                    <span class="iconfont icon-add" style="color: #006cff;font-size: 14px;"> &nbsp;添加模板</span>
                </a-button>
            </div>
            <a-table :dataSource="dataSource" :columns="columns" :pagination="false" rowKey="templateId">
                <template slot="action" slot-scope="text, record">
                    <span>
                        <a @click="editWithData(record)">修改</a>&nbsp;
                        <a @click="removeCurrent(record)">删除</a>&nbsp;
                    </span>
                </template>
                <template slot="switch" slot-scope="text, record">
                    <a-switch v-model:checked="record.openFlag" checked-children="是" un-checked-children="否"
                        @change="switchChange($event, record)" />
                </template>
            </a-table>
        </a-layout-content>
        <a-layout-footer>
            <a-pagination :page-size="10" @change="onShowPageChange" v-model="pagination.current"
                :total="pagination.totalCount" />
        </a-layout-footer>
        <a-modal :maskClosable="false" v-model:visible="modalVisible" centered class="addTempform" width="700px"
            @ok="addTemplate" okText="确定" cancelText="取消">
            <div class="head-content" v-if="action === 'add'">
                <span class="iconfont icon-document"></span>
                <span>添加模板</span>
            </div>
            <div class="head-content" v-else-if="action === 'view'">
                <span class="iconfont icon-document"></span>
                <span>修改模板</span>
            </div>
            <a-form-model :style="{ width: '100%' }" layout="horizontal" v-bind="{
                labelCol: { span: 6 },
                wrapperCol: { span: 18 },
            }" :colon="true" labelAlign="right" :model="formData" :rules="rules" ref="templateForm" width="1000px">
                <a-row>
                    <a-col :span="24">
                        <a-form-model-item label="模板名称" prop="templateName" v-bind="{}">
                            <a-input size="large" v-model="formData.templateName" placeholder="请输入模板名称" />
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-model-item label="工程类型" prop="projectType" v-bind="{}">
                            <a-select size="large" v-model="formData.projectType" placeholder="请输入工程类型">
                                <a-select-option value="0">
                                    前端工程
                                </a-select-option>
                                <a-select-option value="1">
                                    后端工程
                                </a-select-option>
                                <a-select-option value="2">
                                    移动端工程
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>

                    </a-col>
                </a-row>
                <a-row>
                    <a-col>
                        <a-form-model-item label="模板类型" prop="templateType" v-bind="{}">
                            <a-select size="large" v-model="formData.templateType" show-search placeholder="请输入或选择模板类型"
                                :options="templateTypeOptions" @search="handleTemplateTypeSearch">
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-model-item label="分支名" prop="branchName" v-bind="{}">
                            <a-input size="large" v-model="formData.branchName" placeholder="请输入模板名称" />
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-model-item v-show="action === 'add'" label="是否为公开模板仓库" prop="openFlag" v-bind="{}">
                            <a-switch v-model:checked="formData.openFlag" checked-children="是" un-checked-children="否"
                                @change="switchOpenFlag($event)" />
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col>
                        <a-form-model-item label="模板描述" prop="description" v-bind="{}">
                            <a-textarea type="textarea" v-model="formData.description" placeholder="请输入模板描述" />
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12" style="text-align: left;">
                        <span v-show="action === 'view'">
                            操作人{{ formData.operator.loginName }}
                        </span>
                    </a-col>
                    <a-col :span="12" style="text-align: right;">
                        <span v-show="action === 'view'">

                            操作时间{{ formatTime(formData.createTime) }}
                        </span>

                    </a-col>

                </a-row>

                <a-form-model-item label="操作栏" v-bind="{}" v-show="action !== 'view' && action !== 'add'">
                </a-form-model-item>
            </a-form-model>
        </a-modal>
        <a-modal :maskClosable="false" v-model:visible="modalRespVisible" centered @ok="hanokRepo" okText="保存"
            cancelText="取消">
            <a-form-model :model="repository" :rules="rules" ref="repositoryForm">
                <a-form-model-item label="仓库地址" prop="storageAddress" v-bind="{}">
                    <a-input size="large" v-model="repository.storageAddress" placeholder="请输入仓库完整地址" />
                </a-form-model-item>
                <a-form-model-item label="登录账号" prop="storageAccount" v-bind="{}">
                    <a-input size="large" v-model="repository.storageAccount" placeholder="请输入仓库登录账号" />
                </a-form-model-item>
                <a-form-model-item label="登录密码" prop="storagePassword" v-bind="{}">
                    <a-input size="large" type="password" v-model="repository.storagePassword" placeholder="请输入仓库登录密码"
                        @click="clearInputPass" />
                </a-form-model-item>
            </a-form-model>
        </a-modal>
        <PromptBox ref="PromptBox" />
        <ConfirmDeletion :delete="hanDelOk" ref="ConfirmDeletion" />
    </a-layout>
</template>

<script>
import ConfirmDeletion from '../../../components/ConfirmDeletion';
import PromptBox from '../../../components/PromptBox'
import { manageTemplateApi, getSearchTemplateType, updateTemplate, getRepository, addTemplate, deleteTemplate, getPubKey, updateRepository } from "../../../../packages/api/manage.js";
import { time } from '../../../../packages/utils/time'
import '../../../../static/icons2/iconfont.css'
export default {
    components: {
        PromptBox,
        ConfirmDeletion
    },
    props: [],
    data() {
        let validateType = (rule, value, callback) => {
            if (this.formData.templateType === "" || this.formData.templateType === undefined) {
                callback(new Error("模板类型不能为空"));
            } else {
                callback()
            }
        };
        return {
            tempTypeSearch: [],
            templateTypeOptions: [],
            templateName: '',
            templateType: '',
            formData: {
                templateName: '',
                projectType: undefined,
                templateType: undefined,
                branchName: '',
                openFlag: true,
                description: undefined,
                createTime: '',
                operator: {
                    loginName: ''
                }
            },
            defaultFormData: {
                templateName: '',
                projectType: undefined,
                templateType: undefined,
                branchName: '',
                openFlag: true,
                description: undefined,
                createTime: '',
                operator: {
                    loginName: ''
                }
            },
            rules: {
                storageAddress: [
                    {
                        required: true,
                        message: "仓库地址不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "仓库地址最大长度不能大于255",
                        trigger: "blur",
                    },
                ],
                storageAccount: [
                    {
                        required: true,
                        message: "用户名不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "用户名最大长度不能大于255",
                        trigger: "blur",
                    },
                ],
                storagePassword: [
                    {
                        required: true,
                        message: "密码不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "密码最大长度不能大于255,修改需重新输入",
                        trigger: "blur",
                    },
                ],
                templateName: [
                    {
                        required: true,
                        message: "模板名称不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "模板名称长度不能大于255",
                        trigger: "blur",
                    },
                ],
                projectType: [
                    {
                        required: true,
                        message: "工程类型不能为空",
                        trigger: "change"

                    }
                ],
                templateType: [
                    // {
                    //     required: true,
                    //     message: "模板类型不能为空",
                    //     trigger: "blur"
                    // },
                    // {
                    //     required: true,
                    //     message: "模板类型不能为空",
                    //     trigger: "change"
                    // }
                    { validator: validateType, trigger: "change" },
                    { validator: validateType, trigger: "blur" }
                ],
                branchName: [
                    {
                        required: true,
                        message: "分支名不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "分支名长度不能大于255",
                        trigger: "blur",
                    },
                ],
                description: [
                    {
                        required: true,
                        message: "模板描述不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 255,
                        message: "模板描述长度不能大于255",
                        trigger: "blur",
                    },
                ],

            },
            modalVisible: false,
            pagination: {
                current: 1,
                pageSize: 10,
                pageNum: 1,
                totalCount: 100
            },
            dataSource: [

            ],
            searchDataSource: [],
            columns: [
                {
                    title: "序号",
                    dataIndex: "seq",
                    key: "seq",
                    align: 'center'
                },
                {
                    title: "模板名称",
                    dataIndex: "templateName",
                    key: "templateName",
                    align: 'center'
                },
                {
                    title: "工程类型",
                    dataIndex: "projectType",
                    key: "projectType",
                    customRender: (text, record, index) => {
                        if (record.projectType === '0') {
                            return "前端工程"
                        } else if (record.projectType === '1') {
                            return "后端工程"
                        } else if (record.projectType === '2') {
                            return "移动端工程"
                        }
                    },
                    align: 'center'
                },
                {
                    title: "模板类型",
                    dataIndex: "templateType",
                    key: "templateType",
                    align: 'center'
                },
                {
                    title: "分支名",
                    dataIndex: "branchName",
                    key: "branchName",
                    align: 'center'
                },
                {
                    title: "是否为公开库",
                    key: "openFlag",
                    scopedSlots: { customRender: "switch" },
                    align: 'center'

                },
                {
                    title: "模板描述",
                    dataIndex: "description",
                    key: "description",
                    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'
                },
            ],
            repository: {
                storageAddress: '',
                storageAccount: '',
                storagePassword: ''
            },
            modalRespVisible: false,
            action: "view",
            currentRemoveId: '',
            repositoryList: {},
            publicKey: ''

        };
    },
    computed: {},
    watch: {},
    created() {
        this.getData(1, 10)
        this.getRepositoryList()
        // 默认发起一次请求
        this.getSearchTempType()
        // 获取加密公钥
        this.getPubKey()

    },
    mounted() {

    },
    methods: {
        clearInputPass() {
            if (this.repository.storagePassword.length > 100) {
                this.repository.storagePassword = ""

            }
        },
        getPubKey() {
            getPubKey().then(res => {
                this.publicKey = res.message
            })
        },
        handleTemplateTypeSearch(val) {
            this.getSearchTempType()
            if (val) {
                this.formData.templateType = val
            }
        },
        // 查询模板名称接口
        getSearchTempType() {
            getSearchTemplateType().then((res) => {
                let result = []
                let tempTypeOptions = []
                result = res.result
                result.forEach((item) => {
                    tempTypeOptions.push({
                        label: item,
                        value: item
                    })
                    this.templateTypeOptions = tempTypeOptions
                })

            })
        },
        //清空输入
        clearInput() {
            this.templateName = "";
            this.templateType = ""
            this.getData(1, 10)
        },
        // 添加模板
        addNewProject() {

            this.formData = JSON.parse(JSON.stringify(this.defaultFormData))
            this.action = 'add'
            this.modalVisible = true;
        },
        // 弹出框
        showRes() {
            this.getRepositoryList()
            this.modalRespVisible = true

        },
        // 编辑
        editWithData(record) {
            this.action = "view"
            this.modalVisible = true
            this.formData = JSON.parse(JSON.stringify(record))
        },
        // 移除当前
        removeCurrent(record) {
            this.$refs.ConfirmDeletion.init()
            this.currentRemoveId = record.templateId
            this.$refs.ConfirmDeletion.visible = true
        },
        // 确认删除
        hanDelOk() {
            deleteTemplate(this.currentRemoveId).then((res) => {
                let calcPage = this.calcPageNo(this.pagination.totalCount, this.pagination.current, 10, 1)
                this.getData(calcPage, 10)
                this.$refs.ConfirmDeletion.visible = false
            }).catch(err => {
                this.$message.error("删除失败")
            })
        },
        // 获取数据
        getData(pageNum = 1, pageSize = 10, templateName = '', templateType = '') {
            manageTemplateApi({ pageNum: pageNum, pageSize: pageSize, templateName: templateName, templateType: templateType }).then((res) => {
                let result = res.result.data
                result.map((item, index) => {
                    item.key = index
                    item.seq = (this.pagination.current - 1) * 10 + index + 1
                    return item.openFlag === '0' ? item.openFlag = true : item.openFlag = false
                })
                this.dataSource = result
                this.searchDataSource = result
                this.pagination.totalCount = res.result.totalCount
            })
        },
        // 获取仓库数据
        getRepositoryList() {
            getRepository().then((res) => {
                this.repository = res.result
                // 密码清空，避免二次加密
                // this.repository.storagePassword=""
            })
        },
        // 公开非公开切换
        switchChange(e, row) {

            let params = {
                templateId: row.templateId,
                templateName: row.templateName,
                projectType: row.projectType,
                templateType: row.templateType,
                branchName: row.branchName,
                description: row.description,
                openFlag: e === true ? '0' : '1',
            }
            updateTemplate(params).then((res) => {
            }).catch(err => {
                if (err.data.code === '9999') {
                    this.getData(this.pagination.current, 10)
                }
            })
        },
        // 添加模板
        addTemplate() {

            this.$refs["templateForm"].validate((valid) => {
                if (!valid) {
                } else {

                    if (this.action === 'view') {
                        let params = {
                            templateId: this.formData.templateId,
                            templateName: this.formData.templateName,
                            projectType: this.formData.projectType,
                            templateType: this.formData.templateType,
                            branchName: this.formData.branchName,
                            description: this.formData.description,
                            openFlag: this.formData.openFlag === true ? '0' : '1'
                        }
                        updateTemplate(params).then((res) => {
                            this.getData(this.pagination.current, 10)
                            this.$refs.PromptBox.visible = true
                            this.$refs.PromptBox.init("更新成功")
                        }).catch(err => {
                            this.$message.error("更新失败")
                        })
                        this.modalVisible = false;
                    } else if (this.action === 'add') {
                        let params = {
                            templateName: this.formData.templateName,
                            projectType: this.formData.projectType,
                            templateType: this.formData.templateType,
                            branchName: this.formData.branchName,
                            description: this.formData.description,
                            openFlag: this.formData.openFlag === true ? '0' : '1'
                        }
                        addTemplate(params).then((res) => {
                            this.getData(1, 10)
                            this.$refs.PromptBox.visible = true
                            this.$refs.PromptBox.init("添加成功")
                        }).catch(err => {
                            this.$message.error("添加失败")
                        })
                        this.modalVisible = false;
                    }
                }
            });
        },
        // 切换
        switchOpenFlag(e, r) {
            this.formData.openFlag = e
        },
        // 搜索
        search() {
            // 发起查询请求
            if (this.templateName !== '' && this.templateType !== "") {
                this.getData(1, 10, this.templateName, this.templateType)
            } else if (this.templateName !== '' && this.templateType === "") {
                this.getData(1, 10, this.templateName)
            } else if (this.templateName === '' && this.templateType !== "") {
                this.getData(1, 10, _, this.templateType)
            } else if (this.templateName === '' && this.templateType === "") {
                this.getData(1, 10)
            }
        },
        // 时间格式化
        formatTime(timemill) {
            return time.formatTime(timemill, "yyyy/MM/dd")
        },
        // 更新
        hanokRepo() {
            const jse = new this.$jsEncrypt();
            jse.setPublicKey(this.$store.getters.publicKey);
            this.$refs["repositoryForm"].validate((valid) => {
                if (!valid) {
                } else {
                    let password = ""
                    if (this.repository.storagePassword.length < 100) {
                        password = jse.encrypt(this.repository.storagePassword)
                    } else {
                        password = this.repository.storagePassword
                    }
                    let param = {
                        storageId: this.repository.storageId,
                        storageAccount: this.repository.storageAccount,
                        storageAddress: this.repository.storageAddress,
                        storagePassword: password,
                    }
                    updateRepository(param).then((res) => {
                        this.$refs.PromptBox.visible = true
                        this.$refs.PromptBox.init("更新成功")
                        this.modalRespVisible = false
                    })
                }
            })
        },
        // 分页
        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
        },

    },
};
</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;
}

.ant-layout-header {
    background: fixed white;
}

.ant-pagination {
    text-align: right;
    margin-top: 20px;
}

.ant-layout-content {
    // margin-top: 20px;
    /* // border: 1px solid red; */
}

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

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

.ant-select {
    min-width: 150px;
}

.addTempform .ant-input,
.addTempform .ant-select {
    width: 459px;
}

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

.head-content {
    text-align: center;

}

.head-content span:nth-child(1) {
    font-size: 38px;
    vertical-align: middle;
    color: #284f84;
}

.head-content span:nth-child(2) {
    font-size: 18px;
    vertical-align: middle;
    color: #284f84;
}
</style>
