<template>
    <div class="login-container" @keyup.enter="handleLogin">
        <div class="particles">
            <vue-particles
                color="#dedede"
                shapeType="star"
                linesColor="#dedede"
                hoverMode="grab"
                clickMode="push"
                style="height: 100%"
            ></vue-particles>
        </div>
        <!-- <h1>士大夫士大夫士大夫但是{{ ip }}</h1> -->
        <div class="login-image"></div>
        <div class="login-container-form" >

            <div class="title-container">
                <div class="title">
                    <span style="font-size: 28px">{{ settings.title }}</span>
                </div>
            </div>
            <el-form
                ref="loginForm"
                :model="loginForm"
                :rules="loginRules"
                class="login-form"
                auto-complete="on"
                label-position="left"
            >
                <el-form-item prop="username">
                    <el-input
                        ref="username"
                        v-model="loginForm.username"
                        placeholder="用户名"
                        name="username"
                        type="text"
                        tabindex="1"
                        autocomplete="on"
                    >
                        <svg-icon slot="prefix" icon-class="user" />
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                        :key="passwordType"
                        ref="password"
                        style="margin-top: 10px"
                        v-model="loginForm.password"
                        :type="passwordType"
                        placeholder="密码"
                        name="password"
                        tabindex="2"
                        autocomplete="on"
                    >
                        <svg-icon slot="prefix" icon-class="password" />
                        <span slot="suffix" class="svg-container" @click="showPwd">
                            <!-- <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              /> -->
                            <!-- <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye'"
              /> -->
                        </span>
                    </el-input>
                </el-form-item>
                <span v-if="flagspan" style="float: left; margin-top: -5%; color: red">{{ message }}</span>
                <el-form-item v-show="show" class="yzm-form-item" prop="code">
                    <el-input
                        style="width: 248px; margin-top: 20px"
                        ref="code"
                        v-model="loginForm.imageCode"
                        placeholder="验证码"
                        name="code"
                        type="text"
                        tabindex="3"
                        autocomplete="on"
                    >
                        <svg-icon slot="prefix" icon-class="验证码" />
                    </el-input>
                    <div id="codeDiv" class="divIdentifyingCode" @click="updateCode" style="margin-top: 20px">
                        <img
                            id="codeDiv"
                            :src="tokenImg"
                            style="width: 150px; height: 40px; cursor: pointer"
                            alt="点击更换"
                            title="点击更换"
                        />
                    </div>
                </el-form-item>
                <div class="other-login">
                    <!-- <el-checkbox v-model="checked" class="checkbox">记住密码</el-checkbox> -->
                </div>
                <el-button
                    class="submit-btn"
                    size="medium"
                    :loading="loading"
                    type="info"
                    plain
                    style="margin-top: 20px"
                    @click.native.prevent="handleLogin"
                >
                    登 录
                </el-button>
            </el-form>
        </div>
        <div class="copy-right">
            <span>版权所有 @ 南京灿能电力自动化股份有限公司</span>
            <br />
            <el-image style="width: 20px; height: 20px; position: absolute" :src="jhui"></el-image>
            >
            <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;苏公网安备 32011502011902号</span>
        </div>
        <el-dialog
            :close-on-click-modal="false"
            title="修改密码"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose"
        >
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="新密码" prop="newPwd">
                    <el-input
                        v-model="ruleForm.newPwd"
                        clearable
                        size="small"
                        type="password"
                        style="width: 88%"
                    ></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPwd">
                    <el-input
                        v-model="ruleForm.confirmPwd"
                        clearable
                        size="small"
                        type="password"
                        style="width: 88%"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submintpass">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import VueParticles from 'vue-particles'
import { mapGetters } from 'vuex'
import defaultSettings from '@/settings'
import NProgress from 'nprogress'
import { setDictype, setSysConfig } from '@/utils/auth'
import { gongkey, CodeSr, menulist, updateFirstPassword, dictypeData, getSysConfig } from '@/api/user'
import { sm3Digest } from '@/assets/commjs/sm3'
import { sm2, encrypt } from '@/assets/commjs/sm2.js'
export default {
    name: 'login',
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'))
            } else {
                if (this.ruleForm.confirmPwd !== '') {
                    this.$refs.ruleForm.validateField('confirmPwd')
                }
                callback()
            }
        }
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.ruleForm.newPwd) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        //  var validatePass3 = (rule, value, callback) => {
        //    if(value != ''){

        //    }
        //   if (value === '') {
        //     callback(new Error('请输入密码'));
        //   }else{
        //     callback(new Error(this.message));
        //   }
        // };
        return {
            ip: '',
            show: false,
            dialogVisible: false,
            logourl: window.sessionStorage.logo,
            flagspan: false,
            newPwdpassword: '',
            logo: require('../../assets/login/logo.png'),
            logo2: require('../../assets/login/njcn.png'),
            jhui: require('../../assets/login/jhui.png'),
            title: defaultSettings.title,
            //activeTab: '1',
            flag: process.env.VUE_APP_MODE === 'cgyqr',
            number: 0,
            code: '',
            tokenImg: '',
            loginForm: {
                username: '',
                password: '',
                grant_type: 'captcha',
                client_secret: 'njcndnzl',
                client_id: 'njcn',
                imageCode: ''
            },
            loginjmForm: {
                username: '',
                password: '',
                publicKey: '',
                grant_type: 'captcha',
                client_secret: 'njcndnzl',
                client_id: 'njcn',
                imageCode: '',
                verifyCode: 0
            },
            checked: '',
            loginRules: {
                username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
                password: [{ required: true, trigger: 'blur', message: '请输入密码' }]
            },
            loading: false,
            passwordType: 'password',
            redirect: undefined,
            NProgress: NProgress,
            changePwdDialog: false, //修改密码弹框
            ruleForm: {
                newPwd: '',
                confirmPwd: ''
            },
            message: '',
            rules: {
                newPwd: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 16,
                        message: '长度在 6 到 16 个字符',
                        trigger: 'blur'
                    },
                    { validator: validatePass, trigger: 'blur' }
                ],
                confirmPwd: [
                    { required: true, message: '请确认密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 16,
                        message: '长度在 6 到 16 个字符',
                        trigger: 'blur'
                    },
                    { validator: validatePass2, trigger: 'blur', required: true }
                ]
            },
            menulists: [],
            path: ''
        }
    },
    watch: {
        $route: {
            handler: function (route) {
                this.redirect = route.query && route.query.redirect
            },
            immediate: true
        }
    },
    computed: {
        ...mapGetters(['settings', 'menu'])
    },
    created() {},
    mounted() {
        //获取ip
        // this.getUserIP((ip) => {
        //     this.ip = ip;
        //   });
        //particlesJS('particles', particlesJson.particle,);

        if (this.loginForm.username === '') {
            this.$refs.username.focus()
        } else if (this.loginForm.password === '') {
            this.$refs.password.focus()
        }
        //this.getIdentifyingCode ()
        this.updateCode()
        //this.SysConfig();
        // 绑定监听事件
        window.addEventListener('keydown', this.keyDown)
        // this.getmuen()
    },
    destroyed() {
        // 销毁事件
        window.removeEventListener('keydown', this.keyDown, false)
    },

    methods: {
        // getUserIP(onNewIP) {
        //   debugger
        //     let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
        //     let pc = new MyPeerConnection({
        //         iceServers: []
        //       });
        //     let noop = () => {
        //       };
        //     let localIPs = {};
        //     let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
        //     let iterateIP = (ip) => {
        //       if (!localIPs[ip]) onNewIP(ip);
        //       localIPs[ip] = true;
        //     };
        //     pc.createDataChannel('');
        //     pc.createOffer().then((sdp) => {
        //       sdp.sdp.split('\n').forEach(function (line) {
        //         if (line.indexOf('candidate') < 0) return;
        //         line.match(ipRegex).forEach(iterateIP);
        //       });
        //       pc.setLocalDescription(sdp, noop, noop);
        //     }).catch((reason) => {
        //     });
        //     pc.onicecandidate = (ice) => {
        //       if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
        //       ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
        //     };
        //   },

        SysConfig() {
            getSysConfig().then(res => {
                const sysdata = res.data
                setSysConfig(JSON.stringify(sysdata))
            })
            this.dictdata()
        },
        dictdata() {
            dictypeData().then(response => {
                const dictType = response.data
                setDictype(JSON.stringify(dictType))
            })
            //this.getmuenlist()
        },
        updateCode() {
            // this.tokenImg = process.env.VUE_APP_URL + '/pqs-oauth2/oauth/getImgCode?random=' + Math.random()
            if (window.sessionStorage.getItem('cntoken')) {
                window.sessionStorage.removeItem('cntoken')
                window.sessionStorage.removeItem('cnrtoken')
            }
            CodeSr().then(response => {
                let blob = new Blob([response], { type: 'image/jpg' })
                let url = window.URL.createObjectURL(blob)
                this.tokenImg = url
            })
        },
        showPwd() {
            if (this.passwordType === 'password') {
                //this.passwordType = "";
                this.passwordType = 'password'
            } else {
                this.passwordType = 'password'
            }
            this.$nextTick(() => {
                this.$refs.password.focus()
            })
        },
        jiami() {
            this.loginjmForm.password = ''
            var username = encrypt(this.loginForm.username)
            window.loginName = username
            this.loginjmForm.username = username
            this.loginjmForm.imageCode = this.loginForm.imageCode
            //获取公钥
            gongkey({ loginName: window.loginName }).then(response => {
                window.publicKey = response.data
                window.localStorage.setItem('publicKey', response.data)

                var sm3Pwd = sm3Digest(this.loginForm.password)
                var jiamipassword = ''
                jiamipassword = sm2(sm3Pwd + '|' + this.loginForm.password, publicKey, 0)
                this.loginjmForm.password = jiamipassword

                this.$store
                    .dispatch('user/login', this.loginjmForm)
                    .then(response => {
                        if (response.code === 'A0101' && response.message === '登录认证,密码失效，请重置') {
                            this.dialogVisible = true
                            //this.$message.warning(response.message)
                            CodeSr().then(response => {
                                let blob = new Blob([response], { type: 'image/jpg' })
                                let url = window.URL.createObjectURL(blob)
                                this.tokenImg = url
                            })
                            this.loading = false
                        } else if (response.code === 'A0101') {
                            this.flagspan = true
                            this.code = 'A0101'
                            this.message = response.message
                            if (this.number == 3 && this.code == 'A0101') {
                                this.show = true
                                this.loginjmForm.verifyCode = 1
                            }

                            CodeSr().then(response => {
                                let blob = new Blob([response], { type: 'image/jpg' })
                                let url = window.URL.createObjectURL(blob)
                                this.tokenImg = url
                            })
                            this.loading = false
                            setTimeout(() => {
                                this.flagspan = false
                            }, 8000)
                        }
                        if (response.code === 'A0000') {
                            let strings = response.data.access_token.split('.') //截取token，获取载体
                            // console.log(escape, atob)
                            var userInfo = JSON.parse(
                                decodeURIComponent(escape(atob(strings[1].replace(/-/g, '+').replace(/_/g, '/'))))
                            )
                            // console.log('++++++++++++++++++++++++++++++++++++++++++++++======',userInfo)
                            // console.log('++++++++++++++------------======',userInfo.authorities[0])
                            this.code = 'A0000'
                            this.loginjmForm.verifyCode = 0
                            this.SysConfig()
                            // if(userInfo.authorities[0]=='root'){
                            //   this.$router.push({
                            //   path: this.redirect || "/harmonic-boot/area/powerAssessment",
                            // });
                            // this.loading = false;
                            // }
                            //  debugger
                            // this.$router.push({ path: this.redirect || '/dashboard/index' })

                            // if(response.data.nickname==='系统管理员'){
                            //   this.$router.push({
                            //   path: this.redirect || "/user-boot/user/list",
                            // });
                            // this.loading = false;
                            // }else if(response.data.nickname==='业务管理员'){
                            //   this.$router.push({
                            //   path: this.redirect || "/BusinessAdministrator/TerminalManagement/FrontManagement",
                            // });
                            // this.loading = false;
                            // }else if(response.data.nickname==='审核管理员'){
                            //   this.$router.push({
                            //   path: this.redirect || "/user/checkUserListview",
                            // });
                            // this.loading = false;
                            // }else if(response.data.nickname==='审计管理员'){
                            //   this.$router.push({
                            //   path: this.redirect || "/BusinessAdministrator/Audit/Operations/Management",
                            // });
                            // this.loading = false;
                            // }else{
                            //   this.$router.push({
                            //   //path: this.redirect || "/harmonic-boot/area/powerAssessment",
                            //   // path: this.redirect || "/jbei/QualityOverview",
                            //    path: this.redirect || "/dashboard/index",
                            // });
                            //  this.loading = false;
                            // }
                            this.$store.dispatch('user/getmenu').then(response => {
                                //console.log("++++====",response)
                                // console.log(response.data)
                                this.menulists = response.data
                                this.getmuen(this.menulists[0])
                                this.$router.push({
                                    path: this.redirect || this.path
                                })
                                this.loading = false
                            })
                        }
                    })
                    .catch(error => {
                        //alert(error)
                        //this.dialogVisible = true
                        this.loading = false
                        CodeSr().then(response => {
                            let blob = new Blob([response], { type: 'image/jpg' })
                            let url = window.URL.createObjectURL(blob)
                            this.tokenImg = url
                        })
                    })
            })
        },
        getmuen(data) {
            if (data.children.length == 0) {
                this.path = data.routePath
            } else {
                this.getmuen(data.children[0])
            }
        },
        submintpass() {
            // var jiaminewPwdpassword=''
            gongkey({ loginName: window.loginName }).then(response => {
                if (response.code == 'A0000') {
                    window.publicKey = response.data
                    var sm3Pwd = sm3Digest(this.ruleForm.newPwd)
                    var jiaminewPwdpassword = ''
                    jiaminewPwdpassword = sm2(sm3Pwd + '|' + this.ruleForm.newPwd, publicKey, 0)
                    this.newPwdpassword = jiaminewPwdpassword
                    var userPasswordParam = {
                        name: window.loginName,
                        password: this.newPwdpassword
                    }
                    this.dialogVisible = false
                    updateFirstPassword(userPasswordParam).then(res => {
                        if (res.code === 'A0000') {
                            this.$message.success('修改成功')
                        }
                    })
                }
            })
        },
        handleLogin() {
            if (this.number == 3 && this.code == 'A0000') {
                this.number = 0
            } else {
                this.number++
            }
            //  if(!window.sessionStorage.getItem('imgcode')){
            //    this.updateCode()
            //  }
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true
                    this.jiami()
                } else {
                    return false
                }
            })
        },
        handleClose() {
            this.dialogVisible = false
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-button--info.is-plain {
    color: #fff;
    background: $themeColor_8;
    border-color: $themeColor_8;
}

.login-container {
    position: relative;
    width: 100%;
    min-height: 100%;
    overflow: hidden;
    color: #5a5e66;
    background-color: $themeColor;
    background-image: url(https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg);
    //background-image: url('../../assets/login/login.png');
    background-position: center 110px;
    background-repeat: repeat;
    background-size: 100%;
}
.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
    margin-bottom: 20px !important;
    height: 36px !important;
    padding: 0 !important;
}
.login-image {
    position: absolute;
    top: 50%;
    left: 20%;
    width: 45%;
    height: 80%;
    background: url('../../assets/login/login2.png') no-repeat center center;
    background-size: contain;
    border-radius: 30px;
    transform: translate(-15%, -50%);
    box-shadow: 0 0 0 #011b2bab;
}
.copy-right {
    position: absolute;
    bottom: 10px;
    width: 100%;
    font-size: 14px;
    color: rgb(233, 229, 229);
    text-align: center;
}
.login-container-form {
    position: absolute;
    top: 50%;
    left: 85%;
    width: 500px;
    height: auto;
    border-radius: 30px;
    transform: translate(-85%, -50%);
    box-shadow: 3px 3px 2px 2px #011b2bab;
}
.title-container {
    position: relative;
    width: 398px;
    max-width: 100%;
    padding: 20px 0 0;
    margin: 0 auto;
    .title {
        margin-bottom: 20px;
        font-size: 33px;
        font-weight: 600;
        color: rgba(255, 255, 255, 0.85);
        text-align: center;
        & ::v-deep .svg-icon {
            color: $themeColor;
        }
        .logo {
            width: 46px;
            height: 46px;
            margin-right: 10px;
            vertical-align: middle;
        }
    }
}
.divIdentifyingCode {
    position: relative;
    top: 0;
    right: 0;
    left: 10px;
    z-index: 5;
    width: 150px; /* 设置图片显示的宽 */
    height: 40px; /* 图片显示的高 */
    margin: 0;
    background: #cddcddb2;
}
.submit-btn {
    width: 100%;
    margin-top: 0px;
    margin-bottom: 20px;
    background: rgba(1, 42, 53, 0.157);
    border-radius: 0;
}
.checkbox {
    color: rgb(251, 253, 253);
}
.svg-container {
    display: inline-block;
    width: 40px;
    color: $themeColor;
    vertical-align: middle;
    cursor: pointer;
}
.yzm-form-item {
    & ::v-deep .el-form-item__content {
        display: flex;
        .el-button {
            margin-left: 10px;
            border-radius: 0;
        }
    }
}
.other-login {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 368px;
    max-width: 100%;
    margin: 0 auto;
    font-size: 14px;
    & ::v-deep .svg-icon {
        margin-left: 10px;
        font-size: 24px;
        vertical-align: -0.25em;
    }
}
.login-form {
    position: relative;
    width: 368px;
    max-width: 100%;
    //padding: 20px 0 0;

    margin: 0 auto;
    margin-bottom: 20px;
    overflow: hidden;
    & ::v-deep .el-input {
        input {
            height: 40px;
            padding-right: 40px;
            padding-left: 40px;
            line-height: 40px;
            border-radius: 5px;
        }
        .el-input__prefix,
        .el-input__suffix {
            width: 40px;
            line-height: 40px;
            color: $themeColor;
            .svg-icon {
                font-size: 16px;
                vertical-align: -0.25em;
            }
        }
        .el-input__prefix {
            left: 0;
        }
        .el-input__suffix {
            right: 0;
        }
    }
}
</style>
<style lang="less" scoped>
::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 20px;
}
</style>
<style lang="scss" scoped>
#particles {
    position: absolute;
    width: 100%;
    height: 100vh;
    // background: radial-gradient(ellipse at top left, #006565b5 0%,#ffffff93 57%);
    // background: radial-gradient(ellipse at top left, $themeColor 0%,#ffffff93 57%);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 50% 50%;
}
.particles {
    position: absolute;
    top: 0;
    left: 0;
    height: 100vh;
    width: 100%;
    z-index: 0;
    /* background: radial-gradient(ellipse at top left, rgba(105, 155, 200, 1) 0%,rgba(181, 197, 216, 1) 57%); */
    //background: radial-gradient(ellipse at top left, #006565b5 5%,#ffffff93 87%);
}
</style>
