<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 flex-wrap">
          <div class="avitor"></div>
          <!-- <el-divider direction="vertical"></el-divider> -->
          <div class="content-box">
            <div class="title">国航行李数据整合及应用</div>
            <div class="title-en">AirChina.BDHUB</div>
          </div>
        </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="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="2" auto-complete="on" />
        </el-form-item>

        <div class="flex-wrap">
          <el-form-item class="flex1" prop="identify">
            <el-input ref="identify" v-model="loginForm.identify" placeholder="请输入验证码" name="identify" tabindex="3" 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;
            border-radius: 2px;
          " @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, GetSystemSet } from "@/api/newLogin";
import { Query } from "@/api/dataIntegration";
// import { GetCheckCode, gettoken,GetSystemSet } from "@/api/login";
// import { GetSystemSet } from "@/api/systemConfiguration";
import { setCodeToken, setToken, TokenKey, getCodeToken } from '@/utils/auth';
import { getAuthListByUser } from '@/api/Account';
import MD5 from 'blueimp-md5'
export default {
  name: "Login",
  components: { Identify, Dialog },
  data () {
    return {
      text: `<a onclick='("XSS")'>链接</a>`,
      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,
    },
    '$store.state.user.isLogin': {
      handler (val) {
        if (val) {
          this.noPwdLogin()
        }
      },
      deep: true
    }
  },
  async created () {
    // this.getCheckCode();
    // this.getSystemSet();
    try {
      const res = await gettoken({
        'appid': PLATFROM_CONFIG.appId,
        'appSecret': PLATFROM_CONFIG.appKeyString
      })
      if (res.code == 0 && res.data) {
        setCodeToken(res.data.appToken);
        setTimeout(() => {
          this.getCheckCode();
          this.getSystemSet();
        }, 100);
      } else {
        this.$message.error(res.message);
      }
    } catch (error) {
      this.$message.error(error.message);
    }
  },
  methods: {
    showPwd () {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    //免密登录
    noPwdLogin () {
      this.$store.dispatch("user/setPowerToken", "token");
      this.$store.dispatch("user/setPowerName", '匿名用户');
      this.$store.dispatch("app/toggleOutcheck", false);
      this.$store.dispatch('user/setPowerList', ['admin']);
      setToken(TokenKey, "token");
      setTimeout(() => {
        this.$store.dispatch('user/getInfo');
        sessionStorage.setItem('userAuthList', JSON.stringify(['admin']));
        sessionStorage.setItem("userName", '匿名用户');
        this.$router.push({ path: this.redirect || "/" });
        this.$store.dispatch("user/setIsLogin", false);
      }, 100);
    },
    // 登录
    handleLogin () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          const params = {
            username: this.loginForm.username.replace(/\s+/g, ""),
            password: MD5(this.loginForm.password.replace(/\s+/g, "")),
            // password: this.loginForm.password.replace(/\s+/g, ""),
            verificationCode: this.loginForm.identify.replace(/\s+/g, ""),
          };
          this.$store
            .dispatch("user/login", params)
            .then(async () => {
              this.$store.dispatch("app/toggleOutcheck", false);
              sessionStorage.setItem("userName", params.username);
              this.$router.push({ path: this.redirect || "/" });
              // try {
              //   const { roles } = await this.$store.dispatch('user/getInfo')
              //   if (roles && roles.length) {
              //     this.$router.push({ path: this.redirect || "/" });
              //   } else {
              //     this.$store.dispatch("user/logout");
              //     this.$message.error('当前用户获取权限失败，请联系管理员');
              //   }
              // } catch (error) {
              //   this.$store.dispatch("user/logout");
              //   this.$message.error('当前用户获取权限失败，请联系管理员');
              // }
              // setTimeout(async () => {
              // const UserType = this.$store.getters.UserType;
              // Query({
              //   id: DATACONTENT_ID.loginId,
              //   dataContent: [UserId]
              // }).then(res => {
              //   if (res.code == 0) {
              //     //res.returnData.push('account_menu');
              //     const { listValues } = res.returnData
              //     const datas = listValues
              //     if (datas && datas.length) {
              //       const arrs = [];
              //       for (const item of datas) {
              //         if (item.ident) {
              //           arrs.push(item.ident);
              //         }
              //       }
              //       // arrs.push('transit');
              //       sessionStorage.setItem('userAuthList', JSON.stringify(arrs));
              //       this.$store.dispatch('user/setPowerList', arrs);
              //     } else {
              //       sessionStorage.setItem('userAuthList', []);
              //       this.$store.dispatch('user/setPowerList', []);
              //     }
              //     this.$router.push({ path: this.redirect || "/" });
              //   } 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.loading = false;
            });
        } else {

          return false;
        }
      });
    },
    // 忘记密码确定
    onSubmit () {
      this.flag = false;
      this.type = 1;
    },
    //获取动态验证码
    async getCheckCode () {
      const res = await GetCheckCode({
        appToken: getCodeToken()
      });
      if (res.code == 0) {
        this.loginForm.CheckCode = res.data;
      } else {
        this.$message.error(res.message);
      }
    },
    //获取系统设置
    getSystemSet () {
      GetSystemSet({})
        .then((response) => {
          const { code, data } = response;
          if (code == 0) {
            this.$store.dispatch("app/getSystemSet", data);
          }
          this.PwdMessage = data.pwdMessage;
        })
        .catch((error) => {
          reject(error);
        });
    },
    // 忘记密码
    handleClick () {
      // this.flag = true;
      // this.type = 2;
      this.$message.warning('忘记密码，请联系管理员');
    },
    //验证码重新获取
    changeCode () {
      this.getCheckCode();
    },
  },
};
</script>

<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_001.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  ::v-deep .login-form {
    position: relative;
    width: 416px;
    height: 424px;
    margin-right: 337px;
    background: #ffffff;
    box-shadow: 0px 7px 18px 0px rgba(0, 0, 0, 0.5);
    border-radius: 8px;
    padding: 40px 48px 27px 48px;
    .el-form-item__content {
      height: 40px;
      background: #fff;
      border-radius: 6px;
      .el-input {
        height: 40px;
        border-radius: 2px;
        input {
          height: 40px;
          border: 1px solid #d2d6df;
          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: #2d67e3;
    .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;
    margin-bottom: 39px;
    line-height: 32px;
    .title {
      // height: 16px;
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #303133;
      margin: 0;
    }
    .title-en {
      position: absolute;
      top: 23px;
      left: 0;
      font-size: 12px;
    }
    .content-box {
      position: relative;
    }
    .avitor {
      width: 36px;
      height: 36px;
      margin-right: 20px;
      background: url("../../assets/logo/pic_logo.png") no-repeat;
      // border-radius: 50%;
      position: relative;
      top: 7px;
    }
    .el-divider {
      height: 20px;
      background: #101116;
      margin: 0 16px;
      position: relative;
      top: 5px;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
