<template>
  <div class="login-container">
    <template v-if="type == 1">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

        <div class="title-container">
          <h3 class="title">佛山交科4A统一身份安全管理平台</h3>
        </div>

        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon style="color:#606266;" icon-class="user" />
          </span>
          <el-input ref="username" v-model.trim="loginForm.username" placeholder="请输入账号" name="username" type="text" tabindex="1" auto-complete="on" />
        </el-form-item>

        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon style="color:#606266;" icon-class="password" />
          </span>
          <el-input ref="password" v-model="loginForm.password" show-password placeholder="请输入密码" name="password" tabindex="1" auto-complete="on" />
        </el-form-item>

        <div class="flex-wrap">
          <el-form-item class="flex1" prop="identify">
            <el-input ref="identify" v-model.trim="loginForm.identify" placeholder="请输入验证码" name="identify" tabindex="1" auto-complete="on" @keyup.enter.native="handleLogin" />
          </el-form-item>
          <Identify @changeCode="changeCode" :identifyCode="loginForm.CheckCode" style="margin-left: 24px;" />
        </div>

        <el-button :loading="loading" type="primary" style="width:100%;margin-top:18px;height:42px;" @click.native.prevent="handleLogin">登录</el-button>

        <div class="forgetPwd">
          <span @click="handleClick" class="fpwd">忘记密码</span>
        </div>

      </el-form>
    </template>
    <template v-else>
      <Dialog :flag="flag" customClass="dormancyDialog" width="496px">
        <div class="dormancy">
          <div class="title">忘记密码</div>
          <div class="content">
            <p style="font-size: 16px;font-weight: 400;color: #303133;">{{PwdMessage}}</p>
            <div style="display: flex;justify-content: flex-end;">
              <el-button size="small" type="primary" @click="onSubmit">
                确定
              </el-button>
            </div>
          </div>
        </div>
      </Dialog>
    </template>
  </div>
</template>

<script>
import Identify from './identify.vue';
import Dialog from "@/layout/components/Dialog/index.vue";
import { GetCheckCode, getToken } from '@/api/login';
import { GetSystemSet } from "@/api/systemConfiguration";
import { setCodeToken, setToken } from '@/utils/auth';
import { getAuthListByUser } from '@/api/Account';
export default {
  name: 'Login',
  components: { Identify, Dialog },
  data () {
    return {
      type: 1,
      flag: false,
      PwdMessage: null,
      loginForm: {
        username: '',
        password: '',
        identify: '',
        CheckCode: null
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入账号' }],
        password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        identify: [{ required: true, trigger: 'blur', message: '请输入验证码' }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  async created () {
    // this.getCheckCode();
    // this.getSystemSet();
    try {
      const res = await getToken({
        'appID': PLATFROM_CONFIG.appId
      })
      if (res.code == 0 && res.returnData.token) {
        setCodeToken(res.returnData.token);
        setTimeout(() => {
          this.getCheckCode();
          this.getSystemSet();
        }, 100);
      } else {
        this.$message.error(res.message);
      }
    } catch (error) {
      console.log(error);
    }
  },
  methods: {
    showPwd () {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      })
    },
    // 登录
    handleLogin () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          const params = {
            LoginName: this.loginForm.username,
            LoginPwd: this.loginForm.password,
            CheckCode: this.loginForm.identify
          }
          this.$store
            .dispatch("user/login", params)
            .then(() => {
              this.$store.dispatch("app/toggleOutcheck", false);
              sessionStorage.setItem("userName", params.LoginName);
              setTimeout(() => {
                const UserId = this.$store.getters.UserId;
                const UserType = this.$store.getters.UserType;
                getAuthListByUser({
                  UserId: UserId,
                  UserType: UserType
                }).then(res => {
                  if (res.code == 0) {
                    //res.returnData.push('account_menu');
                    const datas = res.returnData
                    if (datas && datas.length) {
                      const arrs = [];
                      for (const item of datas) {
                        if (item.AuthIdent) {
                          arrs.push(item.AuthIdent);
                        }
                      }
                      arrs.push('dashboard'); //进入首页手动添加权限
                      sessionStorage.setItem('userAuthList', JSON.stringify(arrs));
                      this.$store.dispatch('user/setPowerList', arrs);
                      this.$router.push({ path: '/dashboard' || "/" });
                    } else {
                      sessionStorage.setItem('userAuthList', []);
                      this.$store.dispatch('user/setPowerList', []);
                      this.$router.push('/');
                    }
                  } else {
                    this.loading = false;
                    this.$store.dispatch("user/logout");
                    this.$message.error('当前用户获取权限失败，请联系管理员');
                  }
                }).catch(err => {
                  this.loading = false;
                  this.$store.dispatch("user/logout");
                  this.$message.error('当前用户获取权限失败，请联系管理员');
                })
              }, 100);
              this.loading = false;
            })
            .catch(() => {
              this.getCheckCode();
              this.loginForm.password = '';
              this.loginForm.identify = '';
              this.loading = false;
            });
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 忘记密码确定
    onSubmit () {
      this.flag = false;
      this.type = 1;
      this.getCheckCode();
    },
    //获取动态验证码
    async getCheckCode () {
      const res = await GetCheckCode({});
      if (res.code === 0) {
        this.loginForm.CheckCode = res.returnData;
      } else {
        this.$message.error(res.message);
      }
    },
    //获取系统设置
    getSystemSet () {
      GetSystemSet({}).then(response => {
        const { returnData } = response;
        const { PwdMessage } = returnData
        this.PwdMessage = PwdMessage
        this.$store.dispatch("app/getSystemSet", returnData);
      }).catch(error => {
        reject(error)
      })
    },
    // 忘记密码
    handleClick () {
      this.flag = true
      this.type = 2
    },
    //验证码重新获取
    changeCode () {
      this.getCheckCode()
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      // caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #f5f7fa inset !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  background-image: url("../../assets/loginpage/bg.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  ::v-deep .login-form {
    position: relative;
    width: 496px;
    max-width: 100%;
    height: 463px;
    padding: 48px;
    margin: 0 auto;
    overflow: hidden;
    background: #ffffff;
    box-shadow: 0px 7px 18px 0px rgba(0, 0, 0, 0.5);
    border-radius: 16px;
    .el-form-item__content {
      height: 40px;
      background: #f5f7fa;
      border-radius: 6px;
      .el-input {
        height: 40px;
        input {
          height: 40px;
          color: #303133;
        }
      }
    }
  }
  .forgetPwd {
    display: flex;
    justify-content: flex-end;
    margin-top: 22px;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    text-decoration: underline;
    color: #6f81bc;
    .fpwd {
      cursor: pointer;
    }
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    vertical-align: middle;
    width: 55px;
    display: inline-block;
    text-align: center;
  }

  .title-container {
    position: relative;
    .title {
      font-size: 24px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #303133;
      margin: 0;
      margin-bottom: 44px;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
