<!--登录界面-->
<template>
    <div class="login" ref="login"
         :style="{backgroundColor: `#${loginJson[0] ? loginJson[0].BrackgroupStr.slice(3) : ''}`}">
        <section class="login-content" :style="{
            width: loginJson[0] ? loginJson[0].Width + 'px' : '',
            height: loginJson[0] ? loginJson[0].Height + 'px' : '',
            left:loginJson[0] ? loginJson[0].Left + 'px' : '',
            top:loginJson[0] ? loginJson[0].Top + 'px' : '',
            zIndex: loginJson[0] ? loginJson[0].ZIndex : '',
            border: `1px solid #${loginJson[0] ? loginJson[0].BorderStr.slice(3) : ''}`,
            backgroundColor: `#${loginJson[0] ? loginJson[0].ForegroundStr.slice(3) : ''}`}"
        >
            <h2>用户登录</h2>
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="55px" class="login-form">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="ruleForm.username" prefix-icon="el-icon-user" autofocus @keyup.enter.native="submitForm('ruleForm')"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="ruleForm.password" autocomplete="off"
                              prefix-icon="el-icon-lock" @keyup.20.native="testCapsLock" @keyup.enter.native="submitForm('ruleForm')" show-password></el-input>
                </el-form-item>
                <el-checkbox v-model="checked" :checked="checked" class="checkedBox">记住用户名和密码</el-checkbox>
                <el-form-item>
                    <el-button type="primary"
                               :style="{backgroundColor: `#${loginJson[0] ? loginJson[0].BTNForegroundStr.slice(3) : ''}`}"
                               @click="submitForm('ruleForm')">提交
                    </el-button>
                    <el-button type="primary"
                               :style="{backgroundColor: `#${loginJson[0] ? loginJson[0].BTNForegroundStr.slice(3) : ''}`}"
                               @click="resetForm('ruleForm')">重置
                    </el-button>
                </el-form-item>
            </el-form>
        </section>
        <!--最小化和关闭按钮-->
        <div class="mini" @click="miniWindow">－</div>
        <div class="close" @click="closeWindow">×</div>
    </div>
</template>

<script>
    import {
        reqBigScreen,
        reqConfigBigScreen,
        reqConfigDevice,
        reqDevice,
        reqLogin,
        reqLogout,
        reqPreviewSourceList
    } from "../api"
    import {getStaticFile} from "../../utils/tools"
    import storageUtils from "../../utils/storageUtils"
    import axios from "axios"

    export default {
        data() {
            const checkUsername = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('用户名不能为空'))
                }
            }
            const validatePasswrod = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'))
                }
            }
            return {
                ruleForm: {
                    username: '',
                    password: '',
                },
                rules: {
                    username: [
                        {validator: checkUsername, trigger: 'blur'}
                    ],
                    password: [
                        {validator: validatePasswrod, trigger: 'blur'}
                    ]
                },
                loginJson: [],
                staticUrl: this.$store.state.staticUrl,
                flag:false, // 大写开启状态
                checked:storageUtils.getStatus(), // 记住用户名和密码的状态
                user:storageUtils.getUser(), // 本地存储的用户数据
            }
        },

        async beforeCreate() {
            this.loginJson = await getStaticFile('EnityLogin.Data')
        },

        mounted() {
          // 如果status为true，对表单进行赋值
          if(storageUtils.getStatus() === 'true'){
              this.ruleForm.username = this.user.name
              this.ruleForm.password = this.user.password
          }else {
              this.ruleForm.username = ''
              this.ruleForm.password = ''
              this.checked = false
          }
        },

        updated() {
            // 添加背景图片
            const backIcon = this.loginJson[0] ? this.loginJson[0].BackIcon : ''
            this.$refs.login.style.backgroundImage = backIcon ? 'url(' + `${this.staticUrl}/Data/${backIcon}` + ')' : null
        },

        methods: {
            // 提交表单，登录
            async submitForm() {
                const {username, password} = this.ruleForm
                if (username === '' || password === '') {
                    this.$message.warning('请输入用户名和密码！')
                    return
                }
                const userInfo = {"name": username, "password":password}

                // 登录之前先判断本地是否有用户，有的话先退出登录
                if(this.user){
                    // 退出登录
                    await reqLogout(this.user)
                }

                // 请求登录
                const res = await reqLogin(userInfo, 'login')
                if (res.token) {
                    // 将user保存到vuex的state，同时保存到本地
                    this.$store.dispatch('saveUser', userInfo)
                    // 保存记住用户名和密码的状态
                    storageUtils.saveStatus(this.checked)
                    // 将token保存到会议存储
                    storageUtils.saveToken(res.token)
                    // 跳转到管理界面
                    this.$router.replace('/admin')

                    // 上传配置数据和获取接口数据
                    axios.get('static/Data/EnityBigScreen.Data').then(async res => {
                        if (res.status === 200) {
                            const result = await reqConfigBigScreen(res.data)
                            if(result[0].ID){
                                console.log('上传大屏配置文件成功!')
                            }
                        }
                    })

                    axios.get('static/Data/EnityDevice.Data').then(async res => {
                        if (res.status === 200) {
                            const result = await reqConfigDevice(res.data)
                            if(result[0].ID){
                                console.log('上传设备配置文件成功!')

                                const windowJson = await getStaticFile('EnityWindow.Data')
                                const arr = windowJson.filter(item => item.IsVisibility === true)
                                const homeJson = arr[0]
                                this.$store.dispatch('updateHomeJson',homeJson)

                                // 获取大屏,信号源，设备数据，label数据并保存到vuex中
                                const bigScreenJson = await reqBigScreen()
                                const signalListJson = await reqPreviewSourceList()
                                const deviceJson = await reqDevice()
                                const labelJson = await getStaticFile('EnityLable.Data')
                                this.$store.dispatch('updateLabelJson',labelJson)
                                this.$store.dispatch('saveBigscreen',bigScreenJson)
                                this.$store.dispatch('saveSignalList',signalListJson)
                                this.$store.dispatch('saveDevice',deviceJson)
                            }
                        }
                    })


                } else {
                    this.$message.error('用户名或密码错误！')
                }
            },

            // 重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields()
            },

            // 监视开启和关闭大写
            testCapsLock() {
                this.flag = !this.flag
                if(this.flag){
                    this.$message({
                        message: '大写开启',
                        type: 'success'
                    })
                }else {
                    this.$message('大写关闭')
                }
            },

            // 最小化窗口
            miniWindow() {
                require('electron').ipcRenderer.send('window-min')
            },

            // 关闭窗口
            async closeWindow() {
                // 需要先退出登录
                // await reqLogout(this.user)
                require('electron').ipcRenderer.send('window-close')
            }
        }
    }
</script>

<style lang="less">
    html, body {
        margin: 0;
        padding: 0;

        .login {
            width: 100vw;
            height: 100vh;
            background-size: 100% 100%;
            position: relative;

            .login-content {
                position: absolute;

                h2 {
                    text-align: center;
                    font-weight: bold;
                    margin-bottom: 20px;
                }

                .el-input {
                    width: 90%;
                }

                .login-form {
                    .login-form-button {
                        width: 100%;
                    }

                    .checkedBox {
                        margin:0 0 10px 55px;
                    }
                }
            }

            // 最小化和关闭按钮
            .mini {
                .miniclose(30px,20px);
                &:hover {
                    background-color: #ccc;
                }
            }
            .close {
                .miniclose(0,28px);
                &:hover {
                    background-color: #ccc;
                }
            }
        }

        // 带参数的混合
        .miniclose(@right,@fontSize) {
            position: absolute;
            width: 30px;
            height: 30px;
            top: 0;
            right:@right;
            text-align: center;
            line-height: 30px;
            font-size:@fontSize;
            cursor:default;
            font-weight: 600;
            color: #000;
        }
    }
</style>
