<template>
  <el-container :style="backStyle">
    <!-- <div class="mask"></div> -->
    <el-header height="30PX">
      <div class="logo-container" v-if="showTenant"></div>
    </el-header>
    <el-main>
      <div class="login-card__container fullheight">
        <el-card shadow="never" class="login-card">
          <div :style="totemStyle" class="totem-div">
            <h2>{{ companyName }}</h2>
          </div>
          <div class="login-div">
            <el-form
              class="login-form"
              :model="principal"
              :rules="rules"
              ref="principal"
            >
              <!-- <div class="welcome-title">欢迎登陆</div> -->

              <el-form-item prop="account">
                <el-input
                  size="medium"
                  clearable
                  prefix-icon="icon-account"
                  v-model="principal.account"
                ></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  show-password
                  clearable
                  prefix-icon="icon-password"
                  @keyup.enter.native="submitForm('principal')"
                  @focus="inputGetFocus"
                  size="medium"
                  v-model="principal.password"
                ></el-input>
              </el-form-item>

              <el-form-item prop="remberPwd">
                <el-checkbox
                  title="有效期为7天"
                  v-model="principal.remberPwd"
                  :true-label="1"
                  :false-label="0"
                  >记住密码</el-checkbox
                >
              </el-form-item>
              <el-form-item class="btns" style="text-align: right">
                <el-button
                  size="medium"
                  type="primary"
                  @focus="inputGetFocus"
                  @click="submitForm('principal')"
                  class="login-btn"
                  :loading="loading"
                  >登录</el-button
                >
                <!-- <el-button
                  size="medium"
                  @click="resetForm('principal')"
                  :disabled="loading"
                  >重置</el-button
                > -->
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-main>
    <!-- <div class="mask" v-if="hasMask">
            <i
                class="el-icon-loading"
                style="font-size: 90PX; color: rgba(255, 255, 255, 0.5)"
            ></i>
        </div> -->
  </el-container>
</template>

<script>
import Cookie from 'js-cookie'
import portal from '@/api/portal.js'
import {mapState} from 'vuex'
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`,
      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.jpg')}) center / 100% 100% no-repeat`
      },

      totemStyle: {
        width: '420PX',
        height: '420PX',
        float: 'left',
        // backgroundColor: "rgb(169 187 205 / 13%)",
        backgroundColor: '#282b33',
        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.$router.push({
                  //   path: `/frontPlat/${res[0].alias}`
                  // })
                  // if (window.context.railway) {
                  //   this.$router.push({
                  //     path: `/frontPlat/${res[0].alias}`
                  //   })
                  // } else {
                    // this.$router.push({
                    //   path: `/unfinished`
                    // })
                  // }
                  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
        }
      })
    },
    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';
.mask {
  /*background-color: #1a1a1a;*/
  /*opacity: .5;*/
  /*position: fixed;*/
  /*height: 100vh;*/
  /*width: 100vw;*/
  /*z-index: 1;*/
}
.login-card__container {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -o-box;
  display: flex;
  display: -webkit-flex; /* Safari */
  display: flex;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
}

.logo-container {
  margin-top: 10PX;
  /*display: inline-block;*/
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 200PX;
  margin-left: 30PX;
}
.container-header {
  position: absolute;
  right: 0;
  padding: 20PX;
  a {
    color: #5b9dff;
    font-size: 13PX;
    text-decoration: none;
    cursor: pointer;
  }
}

.logo-container > i.icon-hotent-H-c {
  font-size: 36PX;
  // background-image: linear-gradient($--color-secondary, $--color-primary);
  //background-clip: text;
  //-webkit-background-clip: text;

  color: #fff;
  margin-right: -5PX;
}
.logo-container > .logos {
  display: inline-block;
  width: 60PX;
  height: 50PX;
  background: url('~@/assets/img/logo.png') no-repeat center / 100%;
}

.v-line {
  color: #fbfbfb;
  margin: 0 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);
}

.logo-container > span.pre-word {
  font-size: 26PX;
  font-weight: bold;
  color: $--color-primary;
}

.logo-container > span.tail-word {
  font-size: 24PX;
  font-weight: bold;
  color: #bdbfc2;
}

.logo-container > .logo-divider {
  margin: 0 25PX 11PX 25PX;
  height: 18PX;
}

.logo-container > .system-name {
  color: #fff;
  font-weight: bold;
  font-size: 16PX;
}

.site-div {
  float: right;

  margin-top: 25PX;
  margin-right: 40PX;
}

.site-div > a {
  color: #5b9dff;
  font-size: 12PX;
  text-decoration: none;
}

.site-div > a > i {
  font-weight: bold;
  margin-right: 5PX;
}

.login-card {
  width: 420PX;
  height: 420PX;
  border: 0;
  background: transparent;
  box-shadow: 0 0 120PX rgba(0, 109, 167, 0.6);
}

.totem-div {
  /*-moz-box-shadow: 2PX 2PX 5PX #999;*/
  /*-webkit-box-shadow: 2PX 2PX 5PX #999;*/
  /*box-shadow: 2PX 2PX 5PX #999;*/
  display: flex;
  justify-content: center;
  align-items: center;
  align-items: start;
  > div {
    width: 100%;
    padding: 0 40PX;
  }
  h2 {
    font-size: 24PX;
    text-align: center;
    color: #fff;
    font-weight: 600;
    letter-spacing: 2PX;
    padding-top: 36PX;
    /*padding-left: 60PX;*/
  }

  >>> .el-divider {
    margin: 15PX auto;
    background-color: #373b46;
    .el-divider__text {
      color: #6c7079;
      background-color: #282b33;
    }
  }
}

.login-div {
  width: 340PX;
  // height: 420PX;
  float: right;
  background: rgba(255, 255, 255, 0.2);
  -webkit-backdrop-filter: blur(8px);
  backdrop-filter: blur(8px);
  border-radius: 25px;
  box-shadow:inset 0 0 6px rgba(255, 255, 255, 0.2);
  position: absolute;
  top: 55%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.welcome-title {
  color: #000;
  min-height: 20PX;
  margin-top: 40PX;
  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 /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: 400PX;
  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;
    margin: 30PX;
}
/deep/ .el-card__body{
    padding: 0 !important;
}
</style>
