<template>
  <div>
    <div class="proLoading-box" v-if="proLoading"></div>
    <div v-else>
      <div class="login-title">{{ $t('login.phoneLogin') }}</div>
      <el-form :model="loginForm" :rules="loginRules" ref="loginForm" class="login-form">
        <el-form-item prop="username">
          <el-input size="small" style="margin-top: 20px; margin-bottom:10px;"
                    @keyup.enter.native="handleLogin"
                    v-model="loginForm.username"
                    :auto-complete="off"
                    placeholder="请输入您的账号">
            <i slot="prefix" class="icon-yonghu"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="small" style="margin-top: 20px; margin-bottom:10px;"
                    type="password"
                    @keyup.enter.native="handleLogin"
                    v-model="loginForm.password"
                    :auto-complete="off"
                    placeholder="请输入您的密码">
            <i slot="prefix" class="icon-mima"/>
          </el-input>
        </el-form-item>
        <!--        <el-form-item v-if="this.website.captchaMode" prop="code">-->
        <!--          <el-input size="small"  style="margin-top: 20px; margin-bottom:10px;"-->
        <!--                    @keyup.enter.native="handleLogin"-->
        <!--                    v-model="loginForm.code"-->
        <!--                    auto-complete="off"-->
        <!--                    placeholder="请输入图形验证码"-->
        <!--                    class="code-input">-->
        <!--            <i slot="prefix" class="icon-yanzhengma"/>-->
        <!--          </el-input>-->
        <!--          <div class="login-code" >-->
        <!--            <img :src="loginForm.image" class="login-code-img" @click="refreshCode" />-->
        <!--          </div>-->
        <!--        </el-form-item>-->
        <div>
          <el-button
            size="small"
            type="primary"
            @click.native.prevent="handleLogin"
            class="login-submit"
          >{{ $t('login.submit') }}
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import topLang from "@/page/index/top/top-lang";
// import { info } from "@/api/system/tenant";
import {getCaptcha} from "@/api/user";

if (/(^http)(s?):\/\/([a-z0-9].+)(\/manage$)/.test(location.href)) {
  window.location.href = 'http://10.160.7.216:9920/casserver/login?service=http://10.165.0.77/manage/login&stService=http%3A%2F%2F10.165.0.77%2Fmanage%2Flogin'
}
if (/(\/login\?)(.*)/ig.test(location.href)) {
  const obj = {}
  const query = location.href.split('?')[1].replace(/\?/, '').split('&')
  query.forEach((item) => {
    const a = item.split('=');
    obj[a[0]] = a[1]
  })
  window.sessionStorage.setItem('query_session', JSON.stringify(obj))
} else {
  window.sessionStorage.removeItem('query_session')
}

export default {
  name: "login",
  components: {
    topLang,
  },
  data() {
    return {
      loginForm: {
        //租户ID
        tenantId: "000000",
        //用户名
        username: "",
        //密码
        password: "",
        //账户类型
        type: "account",
        //验证码的值
        code: "",
        //验证码的索引
        key: "",
        //预加载白色背景
        image: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
        //工作站loginTpye值为2
        loginType: 'Type-T'
      },
      loginRules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 1, message: "密码长度最少为6位", trigger: "blur"}
        ]
      },
      passwordType: "password",
      proLoading: false,
      loading: null,
      ticket: ''
    };
  },
  watch: {},
  created() {
    // this.getTenant();
    const {ticket} = JSON.parse(window.sessionStorage.getItem('query_session') || "{}")
    window.sessionStorage.removeItem('query_session')
    console.log(ticket)
    if (ticket) {
      this.proLoading = true
      this.ticket = ticket
      this.handleLogin()
    } else {
      console.log('刷新1')
      this.refreshCode();
    }
  },
  mounted() {
  },
  computed: {
    ...mapGetters(["website", "tagWel"])
  },
  props: [],
  methods: {
    handelGoReg() {
      this.$router.push({path: "/reg"});
    },
    refreshCode() {
      getCaptcha().then(res => {
        const data = res.data;
        this.loginForm.key = data.key;
        this.loginForm.image = data.image;
      })
    },
    showPassword() {
      this.passwordType === ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    handleLogin() {
      if (this.proLoading) {
        let params = {
          ...this.loginForm,
          username: "admin",
          password: "111111",
          ticket: this.ticket
        }
        this.ByUsernameCallback(params)
        return
      }
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.ByUsernameCallback()
        }
      });
    },
    ByUsernameCallback(params) {
      const loading = this.$loading({
        lock: true,
        text: '登录中,请稍后。。。',
        spinner: "el-icon-loading"
      });
      let obj = this.loginForm
      if (params) {
        obj = params
      }
      this.$store.dispatch("LoginByUsername", obj).then(() => {
        this.$store.dispatch('jlHelpShow', false)
        this.$router.push({path: this.tagWel.value});
        loading.close();
        this.proLoading = false
      }).catch(() => {
        if (obj.ticket) {
          return window.location.href = process.env.VUE_APP_LOGIN_ERROR
        }
        this.proLoading = false
        loading.close();
        this.refreshCode();
      });
    }
    // getTenant () {
    //   let domain = window.location.href.split("/#/")[0];
    //   // 临时指定域名，方便测试
    //   info(domain).then(res => {
    //     const data = res.data;
    //     if (data.success && data.data.tenantId) {
    //       this.tenantMode = false;
    //       this.loginForm.tenantId = data.data.tenantId;
    //       this.$parent.$refs.login.style.backgroundImage = `url(${data.data.backgroundUrl})`;
    //     }
    //   })
    // }
  }
};
</script>

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

.proLoading-box {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #FFFFFF;
}
</style>
