<template>
  <el-container :style="backStyle">
    <el-header height="30px" style="border: none;">
      <div class="logo-container" v-if="!showTenant">
        <i
          :class="
            isIeExplorer
              ? 'icon-hotent-H icon-hotent-H-ie'
              : 'icon-hotent-H icon-hotent-H-c'
          "
        />
        <span class="pre-word">O</span>
        <span class="tail-word">TENT</span>
        <el-divider class="logo-divider" direction="vertical"></el-divider>
        <span class="system-name">{{ name }}</span>
      </div>
      <div class="logo-container" v-if="showTenant">
        <a class="logo-link" v-if="showLogo">
          <img :src="logo" style="margin-top: 0; height: 48px" />
        </a>
        <i
          :class="
            isIeExplorer
              ? 'icon-hotent-H icon-hotent-H-ie'
              : 'icon-hotent-H icon-hotent-H-c'
          "
          v-if="!showLogo"
        />
        <span class="pre-word" v-if="!showLogo">O</span>
        <span class="tail-word" v-if="!showLogo">TENT</span>
        <el-divider class="logo-divider" direction="vertical"></el-divider>
        <span class="system-name">{{ companyName }}</span>
      </div>
      <div class="site-div">
        <a href="http://www.hotent.com" tabindex="-1">
          <i class="icon-guanwang"></i>宏天官网
        </a>
      </div>
    </el-header>
    <el-main>
      <div class="login-card__container fullheight">
        <el-card shadow="always" class="login-card">
          <div :style="totemStyle" class="totem-div"></div>
          <div class="login-div">
            <el-form
              style="margin: 20px"
              :model="principal"
              :rules="rules"
              ref="principal"
              v-if="!isTwoStepVerify"
            >
              <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"
                  @copy.native.capture.prevent="handlePaste"
                  size="medium"
                  v-model="principal.password"
                ></el-input>
              </el-form-item>
              <el-form-item
                v-if="isShowVerificationCode"
                prop="verificationCode"
              >
                <el-input
                  v-model.trim="principal.verificationCode"
                  tabindex="3"
                  size="large"
                  clearable
                  placeholder="请输入验证码"
                >
                  <div @click="flushVerCode" slot="append">
                    <img :src="captchaImage" class="ver-code" />
                  </div>
                </el-input>
              </el-form-item>

              <!--              <el-alert v-if="responseError" :title="responseError" type="error" :closable="false"></el-alert>-->
              <el-form-item style="text-align: center; margin-top: 10px">
                <el-button
                  size="medium"
                  type="primary"
                  @focus="inputGetFocus"
                  @click="submitForm('principal')"
                  :loading="loading"
                  >登录</el-button
                >
                <el-button
                  size="medium"
                  @click="resetForm('principal')"
                  :disabled="loading"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
            <template v-if="isTwoStepVerify">
              <div class="welcome-title" style="margin-left: 20px">
                欢迎登录
              </div>
              <div class="twoStepVerify-box">
                <el-input
                  v-model.trim="code"
                  clearable
                  size="medium"
                  placeholder="请输入验证码"
                  prefix-icon="icon-yikaiqi"
                  class="twoStepVerify-input"
                >
                </el-input>
                <p class="tips">请使用绑定的手机APP查看验证码</p>

                <el-button
                  class="login-btn twoStepVerify-btn"
                  type="primary"
                  @click="toVerify"
                >
                  验证
                </el-button>
                <el-button class="login-btn" plain @click="toBack">
                  返回登录
                </el-button>
              </div>
            </template>
          </div>
        </el-card>
      </div>
    </el-main>
    <el-footer class="copyright"
      >Copyright © 版权所有 宏天软件 {{ new Date().getFullYear() }}</el-footer
    >
  </el-container>
</template>

<script>
import uc from '@/api/uc.js'
import auth from '@/api/auth'
import {mapState} from 'vuex'
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 (/^[\u4E00-\u9FA5a-zA-Z0-9_-]{2,20}$/.test(value)) {
        return callback()
      } else {
        return callback(new Error('账号格式不符合规范'))
      }
    }
    const validateVerificationCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      logo: '',
      name: '宏天企业信息平台',
      showTenant: false,
      showLogo: false,
      companyName: '',
      tenantName: '',
      principal: {
        tenantId: '',
        account: '',
        password: '',
        verificationCode: '',
        verificationKey: '',
      },
      rules: {
        account: [{validator: checkAccount, trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        verificationCode: [
          {
            required: true,
            trigger: 'blur',
            validator: validateVerificationCode,
          },
        ],
      },
      responseError: '',
      loading: false,
      backStyle: {
        width: '100%',
        background: `url(${require('@/assets/img/back.jpg')}) center / 100% auto no-repeat`,
      },
      totemStyle: {
        width: '300px',
        height: '320px',
        float: 'left',
        background: `#1975FF url(${require('@/assets/img/totem.png')}) center / 100% auto no-repeat`,
      },
      isIeExplorer: false,
      isShowVerificationCode: false,
      captchaImage: '',
      verKey: '',
      code: '',
      isTwoStepVerify: false,
    }
  },
  computed: {
    ...mapState('login', ['loginValue', 'loginStatus']),
  },
  watch: {
    isShowVerificationCode(val) {
      if (val) {
        this.$nextTick(() => {
          //获取二维码图片
          this.flushVerCode()
        })
      }
    },
  },
  mounted() {
    //获取租户信息
    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.value) {
        let tenantManage = resp.data.value
        _this.showTenant = true
        _this.companyName = tenantManage.name
        if (tenant != 'platform') {
          _this.principal.tenantId = resp.data.value.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=manage&tenantId=' +
              tenantManage.id
          }
        }
        //是否启用图形验证码 0-不启用；1-启用且限制失败次数；2-一直启用
        if (tenantManage.captchaEnabled && tenantManage.captchaEnabled === 2) {
          this.isShowVerificationCode = true
        }
      }
    })
    //}else{
    //不是租户
    //this.sysSetting();
    //}
  },
  methods: {
    flushVerCode() {
      //获取二维码图片
      auth.getCaptcha().then((response) => {
        if (response && response.data) {
          this.verKey = response.data.key
          this.captchaImage = response.data.image
        }
      })
    },
    toVerify() {
      this.$store
        .dispatch('login/twoStepVerify', {
          code: this.code,
          token: this.loginValue,
          tenantId: this.principal.tenantId,
        })
        .then(() => {
          if (this.loginStatus) {
            this.$store.dispatch('menu/actionMenus').then((data) => {
              this.$router.push({
                path: this.$route.query.redirect
                  ? this.$route.query.redirect
                  : '/',
              })
            })
            this.$store.dispatch('menu/actionMenuBookmark').then(() => {
              this.$root.$emit('menuBookmarkChange')
            })
            this.isShowVerificationCode = false
          } else if (this.loginStatus == false) {
            this.$router.push({
              name: 'resetPwdView',
              params: {account: this.principal.account},
            })
            this.loading = false
          }
        })
        .catch((msg) => {
          this.loading = false
        })
    },
    // 禁止复制
    handlePaste() {},
    //获取系统默认配置 系统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.manageName == '') {
            _this.companyName = _this.name
          } else {
            _this.companyName = sysSettingData.manageName
          }
          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) {
        return cb([])
      }
      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 + 'manageLoginRoutePath',
        this.$route.path
      )
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.inputGetFocus()
          this.loading = true
          this.setRouterPath()
          this.principal.verificationKey = this.verKey
          this.$store
            .dispatch('login/loginByPrincipal', this.principal)
            .then((user) => {
              this.loading = false
              let {loginStatus, errorCode} = user
              if (errorCode && errorCode === '4012') {
                if (this.isShowVerificationCode) {
                  this.flushVerCode()
                }
                this.isShowVerificationCode = true
                return
              } else if (errorCode && errorCode === '2001') {
                this.isTwoStepVerify = true
                return
              } else if (errorCode && errorCode === '2002') {
                localStorage.setItem('loginData', JSON.stringify(user.value))
                this.$router.push({
                  name: 'security',
                  query: {
                    isTwoStepVerifyAndBind: true,
                  },
                })
                return
              }
              let hasMenu = false

              if (this.$route.query.redirect) {
                let alias = this.$route.query.redirect.replace('/', '')
                //预览 是本地路由  else 动态路由判断用户权限
                if (alias.substr(0, 15) == 'templatePreview') {
                  this.routerFrom(loginStatus, true)
                } else {
                  portal.getCurrentUserMenuByAlias(alias).then((res) => {
                    if (res && res.state && res.value) {
                      hasMenu = true
                    }
                    this.routerFrom(loginStatus, hasMenu)
                  })
                }
              } else {
                this.routerFrom(loginStatus, hasMenu)
              }
            })
            .catch((msg) => {
              this.loading = false
              if (msg.startsWith('timeout of')) {
                msg = '登录超时'
              }
              this.responseError = msg
            })
        } else {
          return false
        }
      })
    },
    routerFrom(loginStatus, hasMenu) {
      if (loginStatus && loginStatus == true) {
        this.$store.dispatch('menu/actionMenus').then((data) => {
          this.$router.push({
            path:
              this.$route.query.redirect && hasMenu
                ? this.$route.query.redirect
                : '/',
          })
        })
        this.$store.dispatch('menu/actionMenuBookmark').then(() => {
          this.$root.$emit('menuBookmarkChange')
        })
      } else if (loginStatus == false) {
        this.$router.push({
          name: 'resetPwdView',
          params: {account: this.principal.account},
        })
      }
    },
    inputGetFocus() {
      this.responseError = ''
    },
    resetForm(formName) {
      this.responseError = ''
      this.$refs[formName].resetFields()
    },
    toBack() {
      this.$router.push('/login')
      this.isTwoStepVerify = false
    },
  },
  created() {
    let USER_AGENT = navigator.userAgent.toLowerCase()
    let isChrome = /.*(chrome)\/([\w.]+).*/
    if (!isChrome.test(USER_AGENT)) {
      this.isIeExplorer = true
    }
  },
  components: {},
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.login-card__container {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -o-box;
  display: box;
  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;
  margin-left: 30px;
}

.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: transparent;
  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);
}

.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: #666;
  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: 600px;
  height: 320px;
}

.totem-div {
  -moz-box-shadow: 2px 2px 5px #999;
  -webkit-box-shadow: 2px 2px 5px #999;
  box-shadow: 2px 2px 5px #999;
}

.login-div {
  width: 300px;
  height: 320px;
  float: right;

  .ver-code {
    width: 80px;
    height: 38px;
    cursor: pointer;
  }
}

.welcome-title {
  margin-top: 40px;
  font-size: 18px;
  margin-bottom: 20px;
}

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

>>> .el-card__body {
  padding: 0;
}

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

.el-main {
  display: flex;
  justify-content: center;
  align-items: center;
}
.twoStepVerify-box {
  margin: 50px 20px 0 20px;
  .tips {
    margin-top: 12px;
    font-weight: 400;
    line-height: 20px;
    color: #999999;
    font-size: 14px;
  }
  .twoStepVerify-input {
    width: 250px;
  }
}
.twoStepVerify-btn {
  margin-top: 20px;
  width: 150px;
}
</style>
