<template>
  <div class="login" id="loginBox">
    <div class="logopositon">
<!--      <img src="../assets/images/yunlian_logo.png" alt="">-->
    </div>
    <div class="login-con">
      <div class="img-box">
        <div class="imgline1">
          一站式私域平台
        </div>
        <div class="imgline2">
          助力企业打造自主客户资产池!
        </div>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <div class="title">总后台管理</div>
        <div class="title-line"></div>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号" class="username" >
            <img slot="prefix" src="../assets/images/user.png" class="input-icon "/>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :type="passwordtype"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
            class="password"
          >
            <!-- <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" /> -->
            <img slot="prefix" src="../assets/images/pass.png" class="input-icon" />
            <img slot="suffix" src="../assets/images/eyeoff.png" class="input-icon2" v-if="ispassword" @click.stop="changetype()"/>
            <img slot="suffix" src="../assets/images/eyeopen.png" class="input-icon2" v-else @click.stop="changetype()"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaOnOff">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleLogin"

          >
            <!-- <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/> -->
            <img slot="prefix" src="../assets/images/code.png" class="input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>{{companyName}}</span>
      <a :href="icpUrl" target="_bank">{{icpRecord}}</a>
    </div>

    <!-- 微信扫码弹框 -->
    <WechatLoginDialog
      ref="wechatDialog"
      :ticket="loginForm.username"
      :visible.sync="wechatDialogVisible"
      @loginSuccess="handleWechatLoginSuccess"
      :redirect="redirect"
    />
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import WechatLoginDialog from "@/views/WechatLoginDialog.vue";
import { setToken } from "@/utils/auth";
import {getConfigByKey} from "@/api/system/config";
import { buildRuntimeConfigFromAdminUi } from '@/utils/adminUiConfig'
import Vue from 'vue'
export default {
  name: "Login",
  components: { WechatLoginDialog },
  data() {
    return {
      codeUrl: "",
      vueAppTitle: process.env.VUE_APP_TITLE,
      companyName: process.env.VUE_APP_COMPANY_NAME,
      icpRecord: process.env.VUE_APP_ICP_RECORD,
      icpUrl: process.env.VUE_APP_ICP_URL,
      cookiePassword: "",
      wechatDialogVisible: false,
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
      },
      captchaOnOff: true,
      loading: false,
      redirect: undefined,
      passwordtype:'password',
      ispassword:true
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  mounted () {

  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
// 重新加载运行时配置
    async reloadRuntimeConfig() {

      try {
        const res = await getConfigByKey('his.adminUi.config')

        const configValue = res?.data?.configValue
        if (!configValue) return

        // 后端配置 JSON
        const form = JSON.parse(configValue)

        Vue.prototype.$runtimeConfig = buildRuntimeConfigFromAdminUi(form)

      } catch (error) {
        console.error('重新加载运行时配置异常:', error)
      }
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: '',
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          Cookies.remove('tenantCode');
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove('rememberMe');
          }
          this.$store
            .dispatch("Login", {...this.loginForm, captchaOnOff: this.captchaOnOff})
            .then(res => {
              if (res.needSms){
                this.wechatDialogVisible = true;
                // 等 visible 更新后，直接调用弹窗 open()
                this.$nextTick(() => {
                  if (this.$refs.wechatDialog) {
                    this.$refs.wechatDialog.open(this.loginForm.username);
                  }
                });
              } else {
                this.$router.push({ path: this.redirect || "/" });
              }
              this.reloadRuntimeConfig()

            })
            .catch(() => {
              this.loading = false;
              this.getCode();
            });
        }
      });
    },
    changetype(){
      this.ispassword=!this.ispassword
      if(this.ispassword){
        this.passwordtype="password"
      }else{
        this.passwordtype="text"
      }
    },
    // 微信扫码成功回调
    handleWechatLoginSuccess(token) {
      this.loading = false
      this.$store.commit("SET_TOKEN", token);
      setToken(token);
      this.$router.push({ path: this.redirect || "/" });
    },
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  .logopositon{
    position: fixed;
    left: 30px;
    top: 30px;
  }
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-image: (url(../assets/images/login_bg.png) );
  background-size: 100% 100%;
  background-size: cover;

  .login-con{
    width: 880px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 10px;


    .img-box{
      width: 440px;
      height: 500px;
      background-image: url(../assets/images/login_left.png);
      background-size: 100% 100%;
      color: #FFFFFF;
      .imgline1{
        font-size: 34px;
        font-weight:400;
        margin-left: 38px;
        margin-top: 38px;
        letter-spacing: 2px;
      }
      .imgline2{
        margin-left: 38px;
        font-size: 16px;
        margin-top: 6px;
        letter-spacing: 1px;
      }

    }
  }
}
.title {
  margin: 0px auto 15px auto;
  text-align: center;
  color: #202124;
  font-weight: 500;
  font-size: 20px;
}
.title-line{
  width: 40px;
  border-bottom: 2px solid #4F46E5;
  margin: 0px auto 30px auto;
}
.login-form {
  box-sizing: border-box;
  background: #ffffff;
  width: 440px;
  height: 500px;
  padding: 40px 25px 5px 25px;
  box-shadow:4px -4px 10px rgba(79, 70, 229, 0.15);
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 20px;
    width: 20px;
    margin-left: 2px;
    margin-top: 10px;
  }
  .input-icon2{
    height: 20px;
    width: 20px;
    margin-right: 4px;
    margin-top: 10px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}


</style>
