<template>
  <div class="login">
    <div class="leftImg"><img src="../assets/images/left.png" style="width: 100%"></div>
    <div class="rightPart">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title"><img style="height: 50px" src="../assets/images/title.png"></h3>
        <h2 class="title" style="color: #E60012;font-weight: 600">{{$t('home.title')}}</h2>

        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            :placeholder="$t('home.placeholderNo')"
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            :placeholder="$t('home.placeholderPas')"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <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" />
          </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;">{{$t('home.rememberPassword')}}</el-checkbox>
        <el-form-item style="width:100%;">
          <el-button
            style=" border-radius: 25px;font-size: 20px;font-weight: 500;
            background: linear-gradient( 139deg, #DC0736 0%, #E60012 100%);"
            :loading="loading"
            size="medium"
            type="primary"
            class="loginButton"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">{{$t('home.login')}}</span>
            <span v-else>{{$t('home.logining')}}</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click" style="position: absolute;right: 15px;top: 15px">
        <div class="avatar-wrapper">
          <!--<img src="../assets/images/language2.png"  style="width: 25px">-->
          <img v-if="$i18n.locale == 'chinese' || !$i18n.locale" src="@/assets/images/CN.svg" style="width: 25px;background-color:red;">
          <img v-if="$i18n.locale == 'english'" src="@/assets/images/EN.svg" style="width: 25px;background-color:red;">
          <img v-if="$i18n.locale == 'russia'" src="@/assets/images/RU.svg" style="width: 25px;background-color:red;">
          <img v-if="$i18n.locale == 'spanish'" src="@/assets/images/ES.svg" style="width: 25px;background-color:red;">


          <!--<SvgIcon icon-class="wufujian" className="svg-wufujian" icon-color="red"/>-->
          <!--<SvgIcon className="svg-wufujian" v-if="$i18n.locale == 'chinese' || !$i18n.locale" icon-class="CN" icon-color="red"/>-->
          <!--<SvgIcon className="svg-wufujian" v-if="$i18n.locale == 'english'" icon-class="EN" icon-color="red"/>-->
          <!--<SvgIcon className="svg-wufujian" v-if="$i18n.locale == 'russia'" icon-class="RU" icon-color="red"/>-->
          <!--<SvgIcon className="svg-wufujian" v-if="$i18n.locale == 'spanish'" icon-class="ES" icon-color="red"/>-->
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="changeLanguage('chinese')">
            <!--            <span>{{$t('system.chinese')}}</span>-->
            <span>中文</span>
          </el-dropdown-item>
          <el-dropdown-item @click.native="changeLanguage('english')">
            <!--            <span>{{$t('system.english')}}</span>-->
            <span>English</span>
          </el-dropdown-item>
          <el-dropdown-item @click.native="changeLanguage('russia')">
            <!--            <span>{{$t('system.russia')}}</span>-->
            <span>Русский язык</span>
          </el-dropdown-item>
          <el-dropdown-item @click.native="changeLanguage('spanish')">
            <!--            <span>{{$t('system.spanish')}}</span>-->
            <span>Español</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>


    <!--  底部  -->
<!--    <div class="el-login-footer">-->
<!--      <span>Copyright © 2018-2024 ruoyi.vip All Rights Reserved.</span>-->
<!--    </div>-->
  </div>
</template>

<script>
import { getCodeImg, getInfo } from '@/api/login'
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import SvgIcon from "@/components/SvgIcon/index.vue";
import store from '@/store'
import { isRelogin } from '@/utils/request'
import router from '@/router'
import { Message } from 'element-ui'

export default {
  name: "Login",
  components: {SvgIcon},
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        timeZone:""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: this.$t('home.account') }
        ],
        password: [
          { required: true, trigger: "blur", message: this.$t('home.password') }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    if(localStorage.hasOwnProperty("local")){
      this.$i18n.locale = localStorage.getItem("local")
    }else {
      localStorage.setItem("local","chinese");
    }
    this.getCode();
    this.getCookie();
    this.getTimeZone()
  },
  methods: {
    getTimeZone(){
        const formatter = new Intl.DateTimeFormat();
        const options = formatter.resolvedOptions();
        const timeZone = options.timeZone;
        this.loginForm.timeZone = timeZone
        console.log(timeZone)
      },
    changeLanguage (val) {
      this.$i18n.locale = val
      localStorage.setItem("local",val)
      location.reload();
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm.username = username === undefined ? this.loginForm.username : username,
      this.loginForm.password = password === undefined ? this.loginForm.password : decrypt(password),
      this.loginForm.rememberMe= rememberMe === undefined ? false : Boolean(rememberMe)

    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(async() => {

            const response = await getInfo();
            // 销售角色（VP、区总、销售经理、代理商经理、代理商销售、销售支持），一进来跳转项目列表页
            const allowedRoles = ['sales_director', 'area_sales_director', 'sales_manager', 'agent_manager', 'agent_sales', 'sales_support']
            if (response.roles.some(role => allowedRoles.includes(role))) {
              console.log('跳转到项目')
              this.redirect = '/project'
            }

            // try {
            //   const res = await store.dispatch('GetInfo')
            //   store.dispatch('GetDicts')
            //   isRelogin.show = false
            //   store.dispatch('GenerateRoutes').then(accessRoutes => {
            //     // 根据roles权限生成可访问的路由表
            //     router.addRoutes(accessRoutes) // 动态添加可访问路由表
            //   })
            //   // 销售角色（VP、区总、销售经理、代理商经理、代理商销售、销售支持），一进来跳转项目列表页
            //   const allowedRoles = ['sales_director', 'area_sales_director', 'sales_manager', 'agent_manager', 'agent_sales', 'sales_support']
            //   if (res.roles.some(role => allowedRoles.includes(role))) {
            //     console.log('跳转到项目')
            //     this.redirect = '/project'
            //   }
            // } catch (e) {
            //   store.dispatch('LogOut').then(() => {
            //     Message.error(e)
            //   })
            // }

            this.$router.push({ path: this.redirect || "/" }).catch(() => {
            });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">

  .loginButton{
    width: 100%;
    height: 66px;
    box-shadow: 0px 4px 16px 0px rgba(226,104,114,0.71);

  }
  .rightPart{
    width: 50%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: url("../assets/images/right2.png");
    background-size: 308px 418px;
    background-repeat: no-repeat;
    background-position: right top;
  }
  .leftImg{
    width: 50%;
  }
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  /*background-image: url("../assets/images/login-background.jpg");*/
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 511px;
  height: 459px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 50px;
    input {
      font-size: 18px;
      padding-left: 35px;
      height: 50px;
      border-radius: 20px;
    }
  }
  .input-icon {
    height: 50px;
    width: 14px;
    margin-left: 10px;
  }
  .el-checkbox{
    .el-checkbox__label{
      font-weight: 400;
      font-size: 20px;
    }
  }

}
.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;
}

.avatar-wrapper {
  .svg-icon {
    width: 25px;
    height: 25px;
  }
}
</style>
