<template lang="pug">
    .login-page
      //- <!-- 表单部分 -->
      .form-group
          <!-- logo部分 -->
          .logo
            img(src="./login-img/logo2x.png" alt="logo")
          el-card(shadow="never")

              div.login-title 用户登录
              el-form(ref="loginForm", @keyup.enter.native="submit", label-position="top", :rules="rules", :model="formLogin" size="default")
                  el-form-item(prop="username" )
                      el-input(type="text" v-model="formLogin.username" class='userIput' placeholder="账户名")
                          span(slot="prepend" )
                              img.icon_img(src='./login-img/user-icon.png' )
                  el-form-item(prop="password" )
                      el-input(type="password" v-model="formLogin.password" class='passIput'  placeholder="密码")
                          span(slot="prepend" )
                              img.icon_img(src='./login-img/psw-icon.png' )
                  el-form-item(prop="code" )
                      el-row
                          el-col(:span='12')
                              el-input(type="text" v-model.trim="formLogin.code" class='authCode-input' placeholder="验证码")
                                  span(slot="prepend" )
                                      img.icon_img(src='./login-img/authCode-icon.png' )
                          el-col(:span='10'  )
                              img.login-code(:src="captchaPath" @click="getCaptcha()" alt="")
                  el-row.checkbox
                    el-col(:span='24' )
                      el-checkbox(v-model="formLogin.remember" checked) 记住密码
                  el-button(size="default" @click="submit" class='login-btn' :loading="loginLoad") 立即登录
      div.lFooter() Copyright (C) 2009-2010. XXXXX信息工程有限公司 蜀ICP备1202XXXX号-1 电话：86-028-6893XXXX 传真：86-028-6893XXXX
</template>

<script>
/* eslint-disable */
// 动态背景js
// require("particles.js");
import config from './config/default'
import { mapActions } from 'vuex'
import util from '@/libs/util.js'
import { getPermissions } from '@/util'
const Base64 = require('js-base64').Base64
import httpRequest from '@/plugin/axios'
import bcrypt from '@/util/bcrypt.js'
export default {
  data() {
    return {
      loginLoad: false,
      // 快速选择用户
      dialogVisible: false,
      users: [
        {
          name: '管理员',
          username: 'admin',
          password: 'admin'
        },
        {
          name: '编辑',
          username: 'editor',
          password: 'editor'
        },
        {
          name: '用户1',
          username: 'user1',
          password: 'user1'
        }
      ],
      // 表单
      formLogin: {
        username: '',
        password: '',
        remember: '',
        uuid: '',
        code: 'qweqwe'
      },
      // 校验
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      captchaPath: ''
    }
  },
  created() {
    //this.getCookie();
    let u = util.cookies.get('username')
    let p = util.cookies.get('password')
    if (u && p) {
      this.formLogin.username = bcrypt.decrypt(u)
      this.formLogin.password = bcrypt.decrypt(p)
    }
    this.getCaptcha()
    this.$parent.getDateList()
    this.$parent.getDateList2()
  },
  mounted() {
    // 初始化例子插件
    //particlesJS("login", config);
  },
  beforeDestroy() {
    // 销毁 particlesJS
    // thanks https://github.com/d2-projects/d2-admin/issues/65
    // ref https://github.com/VincentGarreau/particles.js/issues/63
    //if (pJSDom && pJSDom.length > 0) {
    //  pJSDom[0].pJS.fn.vendors.destroypJS();
    // pJSDom = [];
    //}
  },
  methods: {
    ...mapActions('d2admin/account', ['login']),
    ...mapActions('d2admin/page', ['closeAll']),

    // getType(){
    //   let type
    //    httpRequest({ url: httpRequest.adornUrl('/sysSystem/getSystem'), method: 'get' }).then((e) => {
    //     console.log(e, '类型')
    //   })
    //     return type
    // },

    /**
     * 获取uuid
     */
    getUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        return (c === 'x'
          ? (Math.random() * 16) | 0
          : 'r&0x3' | '0x8'
        ).toString(16)
      })
    },
    // 获取验证码
    getCaptcha() {
      this.formLogin.uuid = this.getUUID()
      this.captchaPath = this.$http.adornUrl(
        `/captcha.jpg?uuid=${this.formLogin.uuid}`
      )
    },
    /**
     * @description 接收选择一个用户快速登录的事件
     * @param {Object} user 用户信息
     */
    handleUserBtnClick(user) {
      this.formLogin.username = user.username
      this.formLogin.password = user.password
      this.submit()
    },
    /* setCookie(c_name, c_pwd, exdays) {
         var exdate = new Date();
         exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
         document.cookie = "userName=" + c_name + ";path=/;expires=" + exdate.toLocaleString()
         document.cookie = "userPwd=" + c_pwd + ";path=/;expires=" + exdate.toLocaleString()
     },
     //获取cookie
     getCookie: function() {
         if (document.cookie.length > 0) {
             var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
             // console.log(arr)
             for (var i = 0; i < arr.length; i++) {
                 var arr2 = arr[i].split('='); //再次切割
                 //判断查找相对应的值
                 if (arr2[0] == 'userName') {
                     this.formLoginusername = arr2[1]; //保存到保存数据的地方
                 } else if (arr2[0] == 'userPwd') {
                     this.formLogin.password = arr2[1];
                 }
             }
         }
     },
     //删除cookie
     clearCookie: function() {
         this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了

     },*/
    /**
     * @description 提交表单
     */
    // 提交登录信息
    clearCookie: function() {
      util.cookies.set('username', '')
      util.cookies.set('password', '')
    },
    submit() {
      // 防止重复提交
      if (this.loginLoad) return
      // 登录关闭所有tab
      this.closeAll()
      let u = bcrypt.encrypt(this.formLogin.username.trim())
      let p = bcrypt.encrypt(this.formLogin.password.trim())
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // this.login({
          //    vm: this,
          //    username: this.formLogin.username,
          //    password: this.formLogin.password,
          //    uuid: this.formLogin.uuid,
          //    captcha: this.formLogin.code
          // })
          // 先进行认证
          // 获取数据列表
          this.loginLoad = true
          this.$http({
            url: this.$http.authUrl('/oauth/token'),
            method: 'post',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: {
              grant_type: 'password',
              username: u,
              password: p,
              scope: 'all'
            }
          })
            .then((data) => {
              if (data.access_token) {
                // 登录
                // 注意 这里的演示没有传验证码
                // 具体需要传递的数据请自行修改代码
                util.cookies.set('authorization', data.access_token)

                this.$http({
                  url: this.$http.adornUrl('/sys/login'),
                  method: 'post',
                  data: {
                    uuid: this.formLogin.uuid,
                    username: u,
                    password: p,
                    captcha: this.formLogin.code
                  }
                })
                  .then((res) => {
                    if (res.msg == 'success') {
                      this.$message.success({
                        message: '登录成功',
                        duration: 800
                      })
                      // 设置 cookie 一定要存 uuid 和 token 两个 cookie
                      // 整个系统依赖这两个数据进行校验和存储
                      // uuid 是用户身份唯一标识 用户注册的时候确定 并且不可改变 不可重复
                      // token 代表用户当前登录状态 建议在网络请求中携带 token
                      // 如有必要 token 需要定时更新，默认保存一天
                      // util.cookies.set("uuid", res.uuid);
                      // util.cookies.set("token", res.token);
                      sessionStorage.setItem('uuid', res.uuid)
                      sessionStorage.setItem('token', res.token)
                      localStorage.setItem('userId', res.userId)
                      // 存储登陆用户权限信息
                      sessionStorage.setItem('permissions', res.permissions)
                      localStorage.setItem('sysSystem', res.sysSystem)
                      localStorage.setItem(
                        'sysSign',
                        JSON.parse(res.sysSystem || '{}').code
                      )
                      localStorage.setItem(
                        'stationId',
                        JSON.parse(res.sysSystem || '{}').code
                      )
                      localStorage.setItem(
                        'lineId',
                        JSON.parse(res.sysSystem || '{}').lineId
                      )
                      //设置被接管
                      let takeover = res.takeover
                      if (takeover && takeover.status === 1) {
                        // 弹出提示框
                        // this.$store.dispatch('d2admin/takeover/setTakeover', takeover)
                      } else if (takeover && takeover.status === 2) {
                        sessionStorage.setItem('takeover', true)
                      }

                      // 设置 vuex 用户信息
                      this.$store.dispatch(
                        'd2admin/user/set',
                        {
                          name: this.formLogin.username,
                          userName: res.userName
                        },
                        { root: true }
                      )
                      // 用户登录后从持久化数据加载一系列的设置
                      this.$store.dispatch('d2admin/account/load')
                      // 获取最新权限信息
                      getPermissions()
                      // 更新路由 尝试去获取 cookie 里保存的需要重定向的页面完整地址
                      const path = util.cookies.get('redirect')
                      // 根据是否存有重定向页面判断如何重定向

                      this.$http({
                        url: this.$http.adornUrl('/sys/menu/nav'),
                        method: 'get'
                      }).then((e) => {
                        let url = e.menuList[0].list[0].path
                        this.$router.replace({ path: url })
                      })
                      // this.$router.replace(path ? { path } : { name: "index" });
                      // 删除 cookie 中保存的重定向页面
                      util.cookies.remove('redirect')
                      if (this.formLogin.remember) {
                        //传入账号名，密码，和保存天数3个参数
                        //this.setCookie(this.formLogin.username, this.formLogin.password, 7);
                        util.cookies.set('username', u)
                        util.cookies.set('password', p)
                      } else {
                        console.log('清空Cookie')
                        //清空Cookie
                        this.clearCookie()
                      }
                      this.$parent.getDateList()
                      this.$parent.getDateList2()
                    } else {
                      sessionStorage.removeItem('uuid')
                      sessionStorage.removeItem('token')
                      this.$message.danger('账号或密码错误')
                    }
                  })
                  .catch((err) => {
                    this.loginLoad = false
                    this.getCaptcha()
                  })
              }
            })
            .catch((err) => {
              this.loginLoad = false
              this.getCaptcha()
            })
        } else {
          // 登录表单校验失败
          //  this.$message.error("表单校验失败");
        }
      })
    }
  }
}
</script>

<style lang="scss">
@import './style.scss';
</style>
