<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>授权中心</title>
    <script type="text/javascript" src="themes/js/vue.min.js"></script>
    <script type="text/javascript" src="themes/js/index.js"></script>
    <script type="text/javascript" src="themes/js/axios.min.js"></script>
    <script type="text/javascript" src="themes/js/jquery.js"></script>
    <script type="text/javascript" src="themes/js/jquery.qrcode.min.js"></script>
    <script type="text/javascript" src="themes/js/moment.js"></script>
    <link rel="stylesheet" href="themes/css/index.css" type="text/css">
    <link rel="stylesheet" href="themes/css/main.css" type="text/css">
</head>

<body>
<div id="app">
    <div class="header">
        <div class="logo" style="float: left">
            <div class="logo-image"></div>
        </div>

        <div style="float: right;margin-right: 20px;margin-top: 15px;">
            <el-button type="primary" @click="openShow">修改密码</el-button>
        </div>
    </div>

    <div class="card-main">
        <div class="main">
            <div class="top">
                <div class="labe">授权企业详情</div>
            </div>

            <div class="company">
                <div class="company-det">
                    <div class="company-lint">
                        <div class="company-name">
                            <div class="company-logo">
                                <img src="themes/img/logo.png" alt="超然X-in智慧管理平台">
                            </div>
                            <div style="margin-left: 20px;">{{companyName}}</div>
                        </div>

                        <div style="margin: 10px;">
                            <div class="address">地址：{{companyAddress}}</div>
                            <div class="des">简介：{{companyIntroduce}}</div>
                            <div class="des">授权码：
                                <span style="color: green">已生成</span>
                                <span>
                                    <el-link type="primary" :underline="false"
                                             style=" font-size: 12px;margin-left: 8px;"
                                             @click="toSeeCode">查看</el-link>
                                </span>
                            </div>
                            <div class="des">授权文件：
                                <span style="color: green">正常</span>
                                <span>
                                    <el-link type="primary" :underline="false" style="font-size: 12px;margin-left: 8px;"
                                             @click="openUploadLicense">
                                        更换授权文件
                                    </el-link>
                                </span>
                            </div>
                            <div class="des">配置文件
                                <el-link type="primary" :underline="false"
                                         style="font-size: 12px;margin-left: 8px;" @click="openConfigSet">设置
                                </el-link>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card-main">
        <div class="main">
            <div class="top">
                <div class="labe">{{single.group}}</div>
            </div>
            <div class="pubg">
                <div class="applist">
                    <div class="app" v-for="(item,i) in single.appList" @click="showDetail(item)">
                        <div class="app-det">
                            <img :src="item.logo ? item.logo : 'themes/img/mk.png'" :alt="item.name">
                        </div>
                        <div class="app-name">{{item.name}}</div>
                        <div class="app-des">版本：{{item.version}}</div>
                        <div class="app-license">{{item.grade == 'custom' ? '定制授权' : item.gradeName}}</div>
                        <div class="app-time" style="color: green"
                             v-if="new Date().getTime() < new Date(item.expiryTime).getTime()">
                            {{item.expiryTime | dateFilter('YYYY-MM-DD')}}到期
                        </div>
                        <div v-else style="color: red">已过期</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <el-dialog title="修改密码" :visible.sync="showPassChange" width="500px" @close="closeShow"
               :close-on-click-modal="false">
        <el-form :model="from" id="passLogin" :rules="rules" ref="user"
                 label-width="80px" @keyup.enter.native="login">
            <el-form-item label="原密码" class="demo-dynamic" prop="pass">
                <el-input v-model="from.pass" size="small" placeholder="请输入原密码" type="password"
                          show-password clearable></el-input>
            </el-form-item>
            <el-form-item label="新密码" class="demo-dynamic" prop="editPass">
                <el-input size="small" v-model="from.editPass" placeholder="请输入要修改的密码" type="password"
                          show-password clearable></el-input>
            </el-form-item>
            <el-form-item label="确认密码" class="demo-dynamic" prop="checkPass">
                <el-input size="small" v-model="from.checkPass" placeholder="请确认改改的密码" type="password"
                          show-password clearable></el-input>
            </el-form-item>
            <el-form-item>
                <div style="text-align: center;">
                    <el-button @click="closeShow">取 消</el-button>

                    <el-button type="primary" @click="edit('user')">确认修改</el-button>
                </div>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog title="授权码" :visible.sync="dialogCodeVisible" :close-on-click-modal="false">
        <div class="demo-input-suffix">
            <div style="display: flex;margin-top: 10px;">
                <div style="display: flex;width: 200px;">
                    <div id="qrcode" style="width:200px;height: 200px;"></div>
                </div>

                <el-input type="textarea" ref="copy" autosize="true" v-model="single.code" resize="none"
                          readonly="true" :autosize="{ minRows: 9, maxRows: 10}"
                          style="flex:1;margin-left: 10px"></el-input>
            </div>
        </div>

        <div style="padding:10px;display: block">
            <el-button style="float: right; " icon="el-icon-document-copy" @click="copy()"
                       type="text">
                复制授权码
            </el-button>
        </div>
    </el-dialog>

    <el-dialog title="授权文件修改" :visible.sync="dialogTableVisible" :close-on-click-modal="false">
        <div slot="header">
            <span>上传授权文件</span>
        </div>
        <span class="tip"></span>
        <div align="center">
            <el-upload class="upload-demo" accept enctype="multipart/form-data" drag action="/xinadmin/upload"
                       multiple="false" show-file-list="false"
                       drag="true" auto-upload="true" limit="1" :on-success="Success">
                <i class="el-icon-upload" style="height: 10px;"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">请将您获得的授权文件(LICENSE)传入系统进行校验</div>
            </el-upload>
        </div>
    </el-dialog>

    <el-dialog :title="rightDialogTitle" :modal-append-to-body="true" :visible.sync="rightDialogVisible"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="closeDetail">
        <div style="max-height: 500px;overflow-y: auto">
            <el-table :data="tableData" size="mini" row-key="code" ref="tableData" border>
                <el-table-column prop="description" label="权限"></el-table-column>
                <el-table-column prop="value" label="参数"></el-table-column>
            </el-table>
        </div>
    </el-dialog>

    <el-dialog title="系统配置文件设置" :visible.sync="configSetVis" :close-on-click-modal="false">
        <el-row style="margin-top: -20px;margin-bottom: 10px;" :gutter="10">
            <el-col :span="8">
                <el-input v-model="configSetPath" placeholder="手动输入文件路径,例如：C:\test.txt"></el-input>
            </el-col>
            <el-col :span="16">
                <el-button @click="readFileInfo" :loading="readBtnLoad">读取配置</el-button>
                <el-button @click="keepFileInfo" :disabled="!apiReadFile" :loading="keepBtnLoad">保存配置</el-button>
            </el-col>
        </el-row>

        <el-input type="textarea" :disabled="!apiReadFile" :autosize="{ minRows: 20, maxRows: 20}"
                  v-model="configSetValue" v-loading="readBtnLoad"></el-input>
    </el-dialog>
</div>

<script>
    function generateQRCode(rendermethod, picwidth, picheight, url) {
        $("#qrcode").qrcode({
            render: rendermethod, // 渲染方式有table方式（IE兼容）和canvas方式
            width: picwidth, //宽度
            height: picheight, //高度
            text: utf16to8(url), //内容
            typeNumber: -1,//计算模式
            correctLevel: 2,//二维码纠错级别
            background: "#ffffff",//背景颜色
            foreground: "#000000"  //二维码颜色
        });
    }

    //中文编码格式转换
    function utf16to8(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }

    Vue.filter("dateFilter", function (date, formatPattern) {
        return moment(date).format(formatPattern || "YYYY-MM-DD HH:mm:ss");
    });

    const home = new Vue({
        el: '#app',
        data() {
            const validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.from.checkPass !== '') {
                        this.$refs.user.validateField('checkPass');
                    }
                    callback();
                }
            };

            const validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.from.editPass) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };

            return {
                single: [],
                dialogCodeVisible: false,
                dialogTableVisible: false,
                rightDialogVisible: false,
                rightDialogTitle: '',
                tableData: [],
                companyName: '',
                companyAddress: '',
                companyIntroduce: '',
                showPassChange: false,
                from: {
                    pass: '',
                    editPass: '',
                    checkPass: ''
                },
                rules: {
                    pass: [
                        {required: true, message: '请输入原密码', trigger: 'blur'},
                    ],
                    editPass: [
                        {required: true, message: '请输入要修改的密码', trigger: 'blur'},
                        {
                            pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,16}$/g,
                            message: '密码必须包含大小写字母及数字，允许特殊字符，长度6-16'
                        },
                        {validator: validatePass, trigger: 'blur'}
                    ],
                    checkPass: [
                        {required: true, message: '请再次输入修改的密码', trigger: 'blur'},
                        {validator: validatePass2, trigger: 'blur'}
                    ]
                },
                generalQrCode: false,
                configSetVis: false,
                configSetPath: 'C:\\Users\\tiany\\Desktop\\tets\\datasource.xml',
                apiReadFile: false,
                configSetValue: '',
                readBtnLoad: false,
                keepBtnLoad: false,
            }
        },
        created: function () {
            this.checkLogin();
            this.singlecode();
        },
        //绑定方法
        methods: {
            singlecode() {
                const that = this;
                axios.get('/xinadmin/single', {}).then(function (res) {
                    if (res.data) {
                        if (res.data.license) {
                            that.single = res.data;
                            that.companyName = res.data.company.name;
                            that.companyAddress = res.data.company.address;
                            that.companyIntroduce = res.data.company.introduce;
                        } else {
                            location.href = "index.jsp"
                        }
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            },
            checkLogin() {
                const token = sessionStorage.getItem("token");
                if (token == null) {
                    location.href = "login.jsp"
                } else {
                    const str = new Date().getTime()
                    if ((+token + (2 * 60 * 60 * 1000) < str)) {
                        location.href = "login.jsp"
                    }
                }
            },
            copy() {
                this.$refs.copy.select()
                document.execCommand('Copy')
                this.$message.success('已复制到剪贴板')
            },
            uploadfile() {
                this.$refs.upload.submit()
            },
            Success(response) {
                if (response.state === "success") {
                    this.dialogTableVisible = false;
                    this.$notify({
                        title: '成功',
                        duration: 2000,
                        message: '校验通过',
                        type: 'success'
                    });
                    const that = this;
                    this.$confirm('授权文件已更新，是否立即重启相关应用?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        axios.get('/xinadmin/adminstarter', {}).then(function () {
                            that.$notify({
                                title: '重启中',
                                duration: 2000,
                                message: '正在重启相关应用，请稍侯....',
                                type: 'info'
                            });
                            setTimeout(() => {
                                location.reload();
                            }, 2000);
                        }).catch(function (error) {
                            console.log(error)
                        })
                    }).catch(() => {
                        that.$notify({
                            title: '警告',
                            duration: 2000,
                            message: '应用尚未重启，授权尚未生效，请稍后手动重启',
                            type: 'warning'
                        });
                    });
                } else {
                    this.$notify.error({
                        title: '上传失败',
                        message: response.error
                    });
                }
            },
            showDetail(item) {
                this.rightDialogVisible = true;
                this.rightDialogTitle = item.name + "授权参数详情";
                let ary = [];
                let data = item.params;
                if (data != null) {
                    for (let i in data) {
                        let desc = data[i].name;
                        let value = data[i].value;
                        let valueType = data[i].valueType;

                        if (valueType === "number") {
                            if (value === -1)
                                value = "未限制数量";
                            else
                                value = "当前允许最大数量为: " + value + " , 请勿超出限制";
                        } else if (valueType === "boolean") {
                            if (value === data[i].falseDefault)
                                value = "未拥有此功能(或权限)";
                            else if (value === data[i].trueDefault)
                                value = "已拥有此功能(或权限)";
                        }

                        let param = {
                            code: i,
                            description: desc,
                            value: value,
                        };
                        ary.push(param);
                    }
                }
                this.tableData = ary;
            },
            closeDetail() {
                this.rightDialogVisible = false;
                this.rightDialogTitle = '';
                this.tableData = [];
            },
            openShow() {
                this.showPassChange = true;
            },
            closeShow() {
                this.form = {
                    pass: '',
                    editPass: '',
                    checkPass: ''
                }
                this.showPassChange = false
            },
            edit(user) {
                this.$refs[user].validate((valid) => {
                    if (valid) {
                        if (this.from.editPass === this.from.checkPass) {
                            const that = this;
                            axios.post('/xinadmin/edit', this.from, {
                                headers: {
                                    'token': sessionStorage.getItem("token")
                                }
                            }).then(function (res) {
                                if (res.data.state === "success") {
                                    that.$message.success('修改成功');
                                    setTimeout(() => {   //设置延迟执行
                                        location.href = "login.jsp";
                                    }, 2000);
                                } else {
                                    that.$message.error(res.data.mes ?? "密码错误");
                                }
                            }).catch(function (error) {
                                console.log(error)
                            })
                        } else {
                            this.$message.error("两次密码不一致")
                        }
                    }
                });
            },
            toSeeCode() {
                this.dialogCodeVisible = true
                if (!this.generalQrCode) {
                    setTimeout(() => {
                        generateQRCode("table", 200, 200, this.single.code);
                        this.generalQrCode = true;
                    }, 100)
                }
            },
            openUploadLicense() {
                this.dialogTableVisible = true;
            },
            openConfigSet() {
                const that = this;
                that.configSetVis = true;
            },
            closeConfigSet() {
                const that = this;
                that.configSetVis = false;
            },
            readFileInfo() {
                const that = this;
                that.configSetValue = '';
                that.apiReadFile = false;
                const params = {filePath: that.configSetPath}
                that.readBtnLoad = true;
                axios.post('/xinadmin/readConfigFile', params).then(function (res) {
                    if (res.status === 200) {
                        that.configSetValue = res.data.data;
                        that.apiReadFile = true;
                    } else {
                        that.$message.error(res.data.mes);
                    }
                }).finally(() => {
                    that.readBtnLoad = false;
                })
            },
            keepFileInfo() {
                const that = this;
                const params = {
                    filePath: that.configSetPath,
                    fileContent: that.configSetValue
                }
                that.keepBtnLoad = true;
                axios.post('/xinadmin/keepConfigSetFile', params).then(function (res) {
                    if (res.status === 200) {
                        that.$message.success('保存成功！');
                        that.closeConfigSet();
                    } else {
                        that.$message.error(res.data.mes);
                    }
                }).finally(() => {
                    that.keepBtnLoad = false;
                })
            },
        }
    })
</script>
</body>
</html>
