<!-- 登录页面 -->
<template>
  <el-container :style="backStyle" class="container">
    <el-header height="30PX">
      <div v-if="showTenant" class="logo-container">
        <div class="header-title">训练数据库管理系统</div>
        <div class="text">
          Training Database Management System
        </div>
      </div>
    </el-header>
    <el-main>
      <div class="login-container fullheight">
        <div class="login-left-ball">
          <div class="ball"></div>
        </div>
        <el-card class="login-card" shadow="never">
          <div class="login-div">
            <el-form
              ref="principal"
              :model="principal"
              :rules="rules"
              class="login-form"
            >
              <div class="welcome-title">用户名登录</div>

              <el-form-item prop="account">
                <el-input
                  v-model="principal.account"
                  clearable
                  placeholder="请输入账号"
                  prefix-icon="icon-account"
                >
                  <template slot="prepend"
                    ><i class="el-icon-user"></i
                  ></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="principal.password"
                  clearable
                  placeholder="请输入密码"
                  prefix-icon="icon-password"
                  show-password
                  @focus="inputGetFocus"
                  @keyup.enter.native="submitForm('principal')"
                >
                  <template slot="prepend"
                    ><i class="el-icon-lock"></i
                  ></template>
                </el-input>
              </el-form-item>

              <el-form-item prop="remberPwd">
                <el-checkbox
                  v-model="principal.remberPwd"
                  :false-label="0"
                  :true-label="1"
                  title="有效期为7天"
                  >记住密码
                </el-checkbox>
              </el-form-item>
              <el-form-item class="btns">
                <el-button
                  :loading="loading"
                  class="login-btn"
                  round
                  type="primary"
                  @click="submitForm('principal')"
                  @focus="inputGetFocus"
                  >登录
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import Cookie from 'js-cookie'
import portal from '@/api/portal.js'

export default {
  name: 'login',
  props: ['tenant'],
  data() {
    var checkAccount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入账号'))
      }
      if (/^[a-zA-Z0-9_-]{2,20}$/.test(value)) {
        return callback()
      } else {
        return callback(new Error('账号格式不符合规范'))
      }
    }
    return {
      fullscreenLoading: true,
      hasMask: true,
      logoSrc: require('../assets/logo.png'),
      codeUrl: `${window.location.origin}/mobilevue`,
      frontBase: `${window.location.origin}`,
      logo: '',
      name: 'EDP',
      showTenant: false,
      showLogo: false,
      companyName: '',
      tenantName: '',
      principal: {
        account: '',
        password: '',
        remberPwd: 0
      },
      rules: {
        // account: [{validator: checkAccount, trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}]
      },
      responseError: '',
      loading: false,
      backStyle: {
        width: '100%',
        height: '100%',
        background: `url(${require('@/assets/img/bg.png')}) center / 100% 100% no-repeat`
      },

      totemStyle: {
        // backgroundColor: '#fff',
        // background: `url(${require('@/assets/img/loginImg.jpg')}) no-repeat center / 100% 100%`
        // background: `#1975FF url(${require("@/assets/img/totem.png")}) center / 100% auto no-repeat`
        // background: `transparent url(${require("@/assets/img/totem1.png")}) no-repeat center 30% / 100% 70% `
      },
      //负责的是登录页授权文件相关数据变量
      isIeExplorer: false,
      dialogVisible: false,
      downLoading: false,
      accept: '.lic',
      files: [],
      uploadingFiles: {}
    }
  },
  mounted() {
    if (!this.$route.query || !this.$route.query.tokenKey) {
      this.hasMask = false
      this.fullscreenLoading = false
    }
    window.webSocket && window.webSocket.close()
    this.setDefaultValue()
    //获取租户信息
    let tenant = this.tenant ? this.tenant : 'platform'
    if (tenant) {
      let url = '${uc}/uc/tenantManage/v1/getTenantByCode?code=' + tenant
      let _this = this
      this.$http.get(url).then(resp => {
        if (resp.data) {
          let tenantManage = resp.data
          _this.showTenant = true
          _this.companyName = tenantManage.nameFront
          if (tenant != 'platform') {
            _this.principal.tenantId = resp.data.id
          }
          if (tenantManage.ico) {
            let ico = JSON.parse(tenantManage.ico)
            if (ico && ico.length > 0) {
              _this.showLogo = true
              _this.logo =
                window.context.portal +
                '/system/file/v1/getLogoFile?logoType=front&tenantId=' +
                tenantManage.id
            }
          }
        }
      })
    } else {
      //不是租户
      this.sysSetting()
    }
  },
  methods: {
    //如果记住密码则默认表单赋值
    setDefaultValue() {
      let account = Cookie.get('account'),
        remberPwd = Number(Cookie.get('remberPwd')),
        password = Cookie.get('accountPwd')
      if (remberPwd) {
        // 如果有记住密码 取密文解密放进输入框
        let Base64 = require('js-base64').Base64
        password = Base64.decode(password)
      }
      this.principal = {
        ...this.principal,
        ...{account, password, remberPwd}
      }
    },
    //获取系统默认配置 系统Logo、名称
    sysSetting() {
      const _this = this
      let url =
        window.context.portal + '/sys/sysProperties/v1/getDecryptBySysSetting'
      this.$http.get(url).then(response => {
        if (response && response.data && response.data.value) {
          _this.showTenant = true
          let sysSettingData = JSON.parse(response.data.value)
          if (sysSettingData.frontName == '') {
            _this.companyName = _this.name
          } else {
            _this.companyName = sysSettingData.frontName
          }
          if (sysSettingData.ico.length > 0) {
            let ico = sysSettingData.ico
            _this.showLogo = true
            _this.logo =
              window.context.portal +
              '/system/file/v1/downloadFile?fileId=' +
              ico[0].id
          }
        }
      })
    },
    querySearch(queryString, cb) {
      if (!queryString) {
        cb([])
        return
      }
      let queryFilter = {}
      queryFilter.pageBean = {
        page: 1,
        pageSize: 20,
        total: 0,
        showTotal: true
      }
      let query = {
        property: 'name_',
        value: queryString,
        group: 'main',
        operation: 'LIKE',
        relation: 'AND'
      }
      if (!queryFilter.querys) {
        queryFilter.querys = []
      }
      queryFilter.querys.push(query)

      this.$http
        .post(`${window.context.uc}/uc/tenantManage/v1/listJson`, queryFilter)
        .then(res => {
          // 调用 callback 返回建议列表的数据
          cb(res.data.rows)
        })
    },
    handleSelect(item) {
      this.tenantName = item.name
      this.principal.tenantId = item.id
    },
    setRouterPath() {
      this.$store.dispatch('login/actionLoginAccount', this.principal.account)
      localStorage.setItem(
        this.principal.account + 'loginRoutePath',
        this.$route.path
      )
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.inputGetFocus()
          this.setRouterPath()
          this.loading = true
          console.log(this.principal, 'login')
          this.$store
            .dispatch('login/loginByPrincipal', this.principal)
            .then(loginStatus => {
              if (loginStatus && loginStatus == true) {
                this.$router.push({
                  path: this.$route.query.redirect
                    ? this.$route.query.redirect
                    : '/'
                })
                this.$store.dispatch('menu/actionSysMenus')
                //获取前台页面
                this.$store.dispatch('menu/actionFrontMenus').then(res => {
                  // this.loading = false
                  this.jumpIn(res)
                  // this.$router.push({
                  //     path: `/bizPlat/${res[0].alias}`,
                  // })
                  // if (window.context.railway) {
                  //   this.$router.push({
                  //     path: `/frontPlat/${res[0].alias}`
                  //   })
                  // } else {
                  // this.$router.push({
                  //     path: `/bizPlat/gis`,
                  // })
                  // }
                  this.loading = false
                })
                // 连接websocket
                this.$bus.$emit('login')
                this.getAllDict()
              } else if (loginStatus == false) {
                this.$router.push({
                  name: 'resetPwdView',
                  params: {account: this.principal.account}
                })
              }
            })
            .catch(msg => {
              this.loading = false
              if (msg.startsWith('timeout of')) {
                msg = '登录超时'
              }
              this.responseError = msg
            })
        } else {
          return false
        }
      })
    },
    jumpIn(menus) {
      this.$router.push('/frontPlat/examKhMenu/dataVisualizationAnalysis')
      // let path = ''
      // let firstMenu = menus[0]
      // if (firstMenu.children.length !== 0) {
      //   let firstPath = firstMenu.alias
      //   let childrens = firstMenu.children
      //   let subPath = childrens[0].alias
      //   if (childrens[0].children && childrens[0].children.length !== 0) {
      //     let threeChildrens = childrens[0].children
      //     let threePath = threeChildrens[0].alias
      //     path = '/frontPlat/' + firstPath + '/' + subPath + '/' + threePath
      //   } else {
      //     path = '/frontPlat/' + firstPath + '/' + subPath + '/'
      //   }
      // } else {
      //   path = '/frontPlat/' + firstPath
      // }

      // this.$router.push({path})
    },
    getAllDict() {
      portal.getSysDict().then(data => {
        // console.log(data, '字典')
        if (data) {
          sessionStorage.setItem('dict_data', JSON.stringify(data))
        }
      })
    },
    inputGetFocus() {
      this.responseError = ''
    },
    resetForm(formName) {
      this.responseError = ''
      this.$refs[formName].resetFields()
    },
    onResize() {
      this.isShowTotem = document.body.offsetWidth > 500
    }
  },
  created() {
    let USER_AGENT = navigator.userAgent.toLowerCase()
    let isChrome = /.*(chrome)\/([\w.]+).*/
    if (!isChrome.test(USER_AGENT)) {
      this.isIeExplorer = true
    }
    this.isShowTotem = document.body.offsetWidth > 500
    window.addEventListener('resize', this.onResize)
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';
// @import '@/assets/css/element-custom.scss';
$text-color: #12bae7;
@font-face {
  font-family: 'PingFang';
  src: url('../assets/fonts/PingFang Medium.otf');
}

// 顶部标题文字
.logo-container {
  width: 100%;
  color: #12bae7;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  .header-title {
    //重庆登录标题
    text-align: center;
    font-size: 30px;
    color: #ffffff;
    // background: url('../assets/img/login-header-title.png') no-repeat center /
    //   100%;
    height: 34px;
    width: 540px;
    margin-top: 3.7%;
  }

  .text {
    text-transform: uppercase;
    // width: 543px;
    height: 20px;
    font-family: PingFang;
    font-size: 14px;
    color: #d3dfff;
    letter-spacing: 0;
    position: relative;
    top: 10px;
  }
}

// 表单&图
.login-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

// 左边球图
.login-left-ball {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  height: 100%;
  width: 39.5%;
  position: relative;
  right: 10%;

  .ball {
    height: 100%;
    width: 100%;
    background: url('../assets/img/left-ball.png') no-repeat center / 100%;
  }
}

.login-card {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  right: 20%;
  border: 0;
  background: #ffffff;
}

.login-div {
  width: 448px;
  height: 490px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo-container > i.icon-hotent-H-c {
  font-size: 36px;
  color: #fff;
  margin-right: -5px;
}

.logo-container > i.icon-hotent-H-ie {
  font-size: 36px;
  //background-clip: text;
  //-webkit-background-clip: text;
  //color: $--color-primary;
  //margin-right: -5PX;
}

.logo-container:hover > i.icon-hotent-H-c {
  background-image: linear-gradient($--color-primary, $--color-secondary);
}

/**自动填充为透明背景色 */
::v-deep .el-input__inner {
  background-color: transparent !important;
  // border-color: $text-color;
  // color: $text-color;
}

::v-deep .el-input__inner:-internal-autofill-previewed,
::v-deep .el-input__inner:-internal-autofill-selected {
  -webkit-text-fill-color: #14b0e5 !important;
  transition: background-color 5000s ease-in-out 0s !important;
}

::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: $text-color;
  border-color: $text-color;
}

::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: $text-color;
}

.welcome-title {
  color: #12bae7;
  min-height: 20px;
  margin-top: 20px;
  font-size: 18px;
  margin-bottom: 50px;
  /*color: #fff;*/
  letter-spacing: 2px;
  // font-weight: 600;
  text-align: center;
  font-family: Roboto, Microsoft YaHei, Sans-serif;
}

.copyright {
  color: #fff;
  font-size: 13px;
  text-align: center;
}

> .el-card__body {
  padding: 0;
}

.login-card ::v-deep .el-alert__content {
  padding: 5px;
}

.btns > .el-form-item__content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.main-header {
  /*position: absolute;*/
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  /*left: 50%;
    transform: translate(-50%, 0);
    top: 28%;*/
  color: #fff;
}

.main-header .logos {
  display: inline-block;
  width: 80px;
  height: 55px;
  /*background: url("~@/assets/img/logo.png") no-repeat center / 100% ;*/
  background: url('~@/assets/img/logo.png') no-repeat center / 100%;
}

.main-header .system-name {
  font-family: Roboto, Microsoft YaHei, Sans-serif;
  font-size: 20px;
  font-weight: bold;
  /*color:#fff;*/
  letter-spacing: 5px;
}

.main-header .driver {
  margin: auto 10px;
}

.main-header .subTit {
  font-weight: bold;
  font-size: 16px;
  letter-spacing: 2px;
}

.infoTip {
  display: block;
  width: 360px;
  color: rgba(255, 0, 0, 0.7);
  font-size: 16px;
  text-align: center;
  margin-left: 30px;
}

.login-btn {
  // width: 220PX;
  width: 100%;
  border: 1px solid #2182f7;
  background-color: #2182f7;
}

> .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #2182f7;
  border-color: #2182f7;
}

.login-form {
  // margin: 40px 50px;
  width: 308px;
}

::v-deep .el-card__body {
  padding: 0 !important;
}

.container {
  position: relative;

  .app {
    position: absolute;
    right: 20px;
    top: 20px;
  }
}
</style>
