<template>
    <div class="license-wrap">
        <div class="logo-wrap">
            <!-- <img class="icon" src="@/assets/images/logo-no-word-blue.png" />
            <span class="text">蜂信物联</span> -->
        </div>
        <pre class="introduce-text">物联网平台授权认证</pre>
        <div class="img-wrap">
            <img style="width: 100%; height: 100%" src="@/assets/images/cover.png" />
        </div>
        <div class="box-wrap">
            <!-- 账号登录 -->
            <div class="form-box">
                <div class="title-wrap">
                    <div class="name">授权认证</div>
                </div>
                <div v-if="visible && !isUpload" class="fixed-message" :class="messageClass">提示: {{ message }}</div>
                <div v-if="visible && isUpload" class="fixed-message" :class="messageClass">提示: {{ installMessage }}</div>
                <div v-if="visible && isUpload" class="fixed-message" style="color: #000; margin-top: 80px; font-size: 14px">服务器信息: {{ serverList }}</div>
                <!-- 上传文件 -->
                <el-form ref="form" :model="form" label-width="0px" :rules="rules">
                    <el-row style="margin-top: 100px; display: flex" v-if="!isUpload">
                        <el-form-item label="" prop="fileName">
                            <el-input v-model="form.fileName" placeholder="请上传.lic文件" disabled style="width: 250px" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="">
                            <el-upload :action="uploadImgUrl" :on-change="handleChange" :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :before-upload="handleBeforeUpload" accept=".lic">
                                <el-button size="small" type="primary" style="margin-left: 10px" icon="el-icon-plus">上传许可文件</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-row>
                </el-form>
                <el-button size="small" style="margin-top: 20px" type="primary" :plain="true" @click="nextStep" v-if="!isUpload" :disabled="isShowNextBtn">
                    下一步
                    <i class="el-icon-right"></i>
                </el-button>
                <!-- 填写授权相关信息并安装 -->
                <el-form class="form-wrap" ref="installForm" :model="installForm" label-width="0px" :rules="installRules" v-if="isUpload">
                    <el-form-item label="" prop="type">
                        <el-select v-model="installForm.type" placeholder="请选择授权类型" style="width: 280px" @change="handleTypeChange" :clearable="true">
                            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="" prop="subject">
                        <el-input v-model="installForm.subject" placeholder="请输入证书名称" style="width: 280px"></el-input>
                    </el-form-item>

                    <el-form-item label="" prop="company" v-if="installForm.type === 2">
                        <el-input v-model="installForm.company" placeholder="请输入公司名称" style="width: 280px"></el-input>
                    </el-form-item>
                    <div style="display: flex; justify-content: space-between">
                        <el-button size="small" type="primary" @click="startInstallation">开始安装</el-button>
                        <el-button size="small" type="primary" :plain="true" @click="returnStep">上一步</el-button>
                    </div>
                </el-form>
            </div>

            <el-dialog title="提示" :visible.sync="dialogVisible" append-to-body width="300px">
                <div>安装成功，三秒后跳转登录页...</div>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="redirectToLogin">确认</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { installLicense, getServerInfo, getLicenseInfo } from '@/api/license';

export default {
    name: 'Lincense',
    data() {
        return {
            isUpload: false, //上传状态，false:待上传，true:已上传
            form: {
                fileName: '',
            },
            fileType: ['lic'],
            isShowNextBtn: false, //按钮是否可以点击
            visible: true,
            message: '认证过期或者未认证，请上传文件进行认证！', // 提示信息内容
            serverList: '选择授权类型后将显示服务器信息...',
            installMessage: '请点击安装', // 安装提示信息内容
            messageClass: 'error', // 提示框的样式类
            file: null,
            uploadImgUrl: process.env.VUE_APP_BASE_API + '/license/upload', // 上传的图片服务器地址
            //授权类型
            options: [
                {
                    value: 2,
                    label: '公司',
                },
                {
                    value: 3,
                    label: '个人',
                },
                {
                    value: 4,
                    label: '试用',
                },
            ],
            //证书安装表单
            installForm: {
                subject: '',
                type: '',
                region: '',
                company: '',
            },
            dialogVisible: false, //提示框
            rules: {
                fileName: [{ required: true, message: '请上传文件', trigger: 'blur' }],
            },
            installRules: {
                subject: [{ required: true, message: '请输入证书名称', trigger: 'blur' }],
                type: [{ required: true, message: '请选择授权类型', trigger: 'blur' }], // 2:公司 3:个人 4:试用
                region: [{ required: true, message: '请输入地域编码', trigger: 'blur' }],
                company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
            },
        };
    },
    mounted() {
        this.getLicense(); //直接访问授权页面时，校验是否已经认证过
    },
    methods: {
        getLicense() {
            //是否已经认证过
            getLicenseInfo()
                .then((res) => {
                    if (res.code === 200) {
                        if (res.data === true) {
                            this.$router.push('/login');
                        }
                    }
                })
                .catch(() => {});
        },
        // 下一步
        nextStep() {
            this.$refs.form.validate((valid) => {
                this.installMessage = '请填写授权信息并点击安装！';
                this.messageClass = 'success';
                if (valid) {
                    this.isUpload = true;
                    this.reset();
                }
            });
        },
        // 上传前校检格式
        handleBeforeUpload(file) {
            // 校检文件类型
            if (this.fileType) {
                const fileName = file.name.split('.');
                const fileExt = fileName[fileName.length - 1];
                const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
                if (!isTypeOk) {
                    this.$modal.msgError('文件格式不正确，请上传.lic文件！');
                    this.isShowNextBtn = true;
                    return false;
                } else {
                    this.isShowNextBtn = false;
                    return true;
                }
            }
        },
        //获取服务器信息
        getServerMsg(value) {
            const params = {
                type: Number(value),
            };
            getServerInfo(params)
                .then((response) => {
                    if (response.code === 200) {
                        const serverData = JSON.parse(response.msg);
                        if (value === 2) {
                            this.serverList = 'ip：' + serverData.ip + ' ; ' + '城市：' + serverData.city + ' ; ' + '城市编码：' + serverData.cityCode;
                        } else if (value === 3 || value === 4) {
                            this.serverList = 'ip：' + serverData.ip + ' ; ' + 'mac地址：' + serverData.mac;
                        }
                    } else {
                        this.serverList = '暂无服务器信息';
                    }
                })
                .catch((error) => {});
        },
        //校验表单
        validateForm() {
            const { subject, type, region, company } = this.installForm;
            if (type === 2) {
                if (!subject || !region || !company) {
                    return false;
                }
            } else if (type === 3) {
                if (!subject) {
                    return false;
                }
            }
            return true;
        },
        // 当type变化时，手动清空某些字段以不影响验证
        handleTypeChange(value) {
            this.installForm.company = value === 2 ? this.installForm.company : '';
            this.installForm.region = value === 2 ? this.installForm.region : '';
            this.installForm.subject = '';
            this.getServerMsg(value);
        },
        // 上一步
        returnStep() {
            this.isUpload = false;
            this.message = '请上传文件进行认证！'; // 成功提示信息
            this.messageClass = 'success';
            this.serverList = '选择授权类型后将显示服务器信息...';
        },
        handleChange(file, fileList) {
            this.form.fileName = file.name;
        },
        handleSuccess(response, file) {
            if (response.code === 200) {
                this.visible = true; // 显示提示信息
                this.message = '上传成功，可以点击下一步进行安装了'; // 成功提示信息
                this.messageClass = 'success';
            } else {
                this.visible = true;
                this.handleError(response);
            }
        },
        handleError(error) {
            this.message = error.msg || '上传失败';
            this.messageClass = 'error';
        },
        //开始安装
        startInstallation() {
            this.visible = true; // 显示提示信息
            this.$refs.installForm.validate((valid) => {
                if (valid) {
                    this.install();
                }
            });
        },
        //安装方法
        install() {
            installLicense(this.installForm)
                .then((response) => {
                    if (response.code === 200) {
                        this.installMessage = response.msg || '安装成功，请登录';
                        this.messageClass = 'success';
                        this.dialogVisible = true;
                        // 3秒后自动跳转
                        setTimeout(() => {
                            this.dialogVisible = false;
                            this.redirectToLogin();
                        }, 3000);
                    } else {
                        this.installMessage = response.msg || '安装失败，请重试';
                        this.messageClass = 'error'; // 样式类
                    }
                })
                .catch((error) => {
                    this.installMessage = error.message || '证书安装失败';
                    this.messageClass = 'error';
                });
        },
        // 跳转登录页
        redirectToLogin() {
            this.$router.push('/login');
        },
        reset() {
            this.installForm = {
                type: '',
                subject: '',
                region: '',
                company: '',
            };
        },
        handleClose() {
            this.visible = false;
        },
    },
};
</script>

<style lang="scss" scoped>
.license-wrap {
    user-select: none;
    height: 100vh;
    max-width: 100%;
    width: 100vw;
    display: flex;

    .logo-wrap {
        position: absolute;
        top: 80px;
        left: 80px;
        display: flex;
        flex-direction: row;
        align-items: center;

        .icon {
            width: 42px;
            height: 46px;
        }

        .text {
            font-size: 36px;
            font-weight: 500;
            margin-left: 12px;
            color: #486ff2;
        }
    }

    .introduce-text {
        position: absolute;
        font-weight: 400;
        font-size: 14px;
        color: #909399;
        line-height: 20px;
        text-align: left;
        font-style: normal;
        top: 146px;
        left: 80px;
    }

    .img-wrap {
        flex: 1;
        background: #0f73ee;
    }

    .box-wrap {
        position: relative;
        width: 608px;
        align-items: center;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        justify-content: center;

        .form-box {
            margin-top: -8%; // 上移35下面留宽一点
            width: 300px;

            .title-wrap {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .name {
                    font-weight: 600;
                    font-size: 24px;
                    color: #303133;
                }

                .lang {
                    cursor: pointer;

                    ::v-deep .el-dropdown {
                        font-weight: 400;
                        font-size: 14px;
                        color: #909399;
                    }
                }
            }

            .demo-account {
                font-weight: 400;
                font-size: 14px;
                color: #909399;
                margin: 40px 0 0;
            }

            .form-wrap {
                margin-top: 124px;
                width: 300px;
                padding: 20px 20px 0 0;
                border-radius: 5px;

                ::v-deep .el-form-item {
                    margin-bottom: 21px;

                    .el-form-item__content {
                        line-height: 14px;
                    }
                }

                .item-wrap {
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                    align-items: center;

                    .input-wrap {
                        display: flex;
                        flex-direction: row;
                        justify-content: space-between;
                        border-radius: 4px;
                        border: 1px solid #dcdfe6;
                        padding: 11px 16px;
                        width: 100%;

                        .inner {
                            background: none;
                            border: none;
                            box-sizing: border-box;
                            flex-grow: 1;
                            font-size: inherit;
                            outline: none;
                            padding: 0;
                            width: 100%;
                            color: #303133;
                        }

                        .icon {
                            color: #303133;
                            cursor: pointer;
                        }
                    }

                    .input-append {
                        width: 112px;
                        height: 40px;
                        margin-left: 8px;
                        border-radius: 4px;
                        cursor: pointer;
                    }
                }

                .other-link {
                    margin-top: 17px;
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                    align-items: center;
                }

                .text {
                    color: #909399;
                    font-size: 14px;
                    text-align: left;
                    white-space: nowrap;
                    cursor: pointer;
                }

                .other-license {
                    margin-top: 40px;
                    display: flex;
                    flex-direction: row;
                    align-items: center;

                    .icon {
                        width: 16px;
                        height: 16px;
                        margin: 0 12px 0 8px;
                        cursor: pointer;
                    }
                }
            }

            .btn {
                margin-top: 26px;
                width: 100%;
                height: 40px;
            }

            .mess-text {
                font-weight: 400;
                font-size: 14px;
                line-height: 24px;
                color: #ed2525;
            }
        }

        .copyright-wrap {
            position: absolute;
            bottom: 24px;
            font-weight: 400;
            font-size: 12px;
            color: #909399;
            line-height: 20px;
        }
    }
}

@media screen and (min-width: 1920px) {
    .license-wrap .box-wrap {
        width: 811px;
    }
}

@media screen and (max-width: 1180px) {
    .license-wrap .box-wrap {
        width: 498px;

        .form-box {
            width: 246px;
        }
    }

    .license-wrap .logo-wrap {
        top: 66px;
        left: 66px;

        .icon {
            width: 34px;
            height: 38px;
        }

        .text {
            font-size: 29px;
            margin-left: 10px;
            color: #486ff2;
        }
    }

    .license-wrap .introduce-text {
        font-size: 11px;
        top: 120px;
        left: 66px;
    }
}

@media screen and (max-width: 968px) {
    .license-wrap .img-wrap {
        display: none;
    }

    .license-wrap .logo-wrap {
        display: none;
    }

    .license-wrap .introduce-text {
        display: none;
    }

    .license-wrap .box-wrap {
        width: 100%;

        .copyright-wrap {
            position: absolute;
            bottom: 10px;
            padding: 0 10px;
            text-align: center;
        }
    }
}
::v-deep .el-progress-bar__innerText {
    display: block;
    margin: 5px;
}
.fixed-message {
    position: fixed;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    margin-top: 50px;
    border-radius: 4px;
    font-size: 13px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    transition: opacity 0.3s; /* 增加渐变效果 */
}

.success {
    background-color: #dff0d8;
    color: #3c763d;
}

.error {
    background-color: #f2dede;
    color: #a94442;
}
</style>
