<template>
  <div class="flex-row">
    <!-- <img src="@/assets/login_page.png" class="img" /> -->
    <div
      class="flex-column"
      style="width: 100%; height: 100vh; justify-content: center"
    >
      <div style="width: 600px; margin-left: 150px">
        <div class="aaa">欢迎使用</div>
        <div class="bbb">城市匠人管理系统</div>
        <div style="height: 50px"></div>

        <a-form class="user-layout-login" @submit="handleSubmit" :form="form">
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="帐户名或邮箱地址"
              v-decorator="[
                'username',
                {
                  initialValue: '',
                  rules: [
                    { required: true, message: '请输入用户名' },
                    { validator: this.handleUsernameOrEmail },
                  ],
                },
              ]"
            >
              <a-icon
                slot="prefix"
                type="user"
                :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input
              size="large"
              type="password"
              autocomplete="false"
              placeholder="密码"
              v-decorator="[
                'password',
                { rules: [{ required: true, message: '请输入密码' }] },
              ]"
            >
              <a-icon
                slot="prefix"
                type="lock"
                :style="{ color: 'rgba(0,0,0,.25)' }"
              />
            </a-input>
          </a-form-item>

          <a-form-item style="margin-top: 24px">
            <a-button
              size="large"
              type="primary"
              htmlType="submit"
              class="login-button"
              :loading="loginBtn"
              :disabled="disableLoginBtn()"
              >确定
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { initRouterTree } from "@/router/router.config";
import notification from "ant-design-vue/es/notification";

export default {
  data() {
    return {
      customActiveKey: "tab1",
      loginBtn: false,
      loginType: 1,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        smsSendBtn: true,
      },
      formLogin: {
        username: "",
        password: "",
        captcha: "",
        mobile: "",
        rememberMe: false,
      },
    };
  },
  created() {},
  methods: {
    ...mapActions(["Login", "Logout"]),
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const regex =
        /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (regex.test(value)) {
        this.loginType = 0;
      } else {
        this.loginType = 1;
      }
      callback();
    },
    disableLoginBtn() {
      if (this.customActiveKey === "tab2") {
        return true;
      }
      return this.loginBtn;
    },
    handleTabClick(key) {
      this.customActiveKey = key;
      // this.form.resetFields()
    },
    handleSubmit(e) {
      e.preventDefault();
      let loginParams = {
        rememberMe: this.formLogin.rememberMe,
      };
      let flag = false;

      // 使用账户密码登陆
      if (this.customActiveKey === "tab1") {
        this.form.validateFields(
          ["username", "password"],
          { force: true },
          (err, values) => {
            if (!err) {
              flag = true;
              loginParams[!this.loginType ? "email" : "username"] =
                values.username;
              loginParams.password = values.password;
            }
          }
        );
        // 使用手机号登陆
      } else {
        this.form.validateFields(
          ["mobile", "captcha"],
          { force: true },
          (err, values) => {
            if (!err) {
              flag = true;
              loginParams = Object.assign(loginParams, values);
            }
          }
        );
      }
      if (!flag) return;

      this.loginBtn = true;

      this.Login(loginParams)
        .then((response) => {
          if (response.code == SYS_CONST.REQUEST.SUCCEED) {
            this.loginSuccess();
          } else {
            this.showErrorMsg(response.resultMsg);
          }
        })
        .catch(() => {
          this.requestFailed();
        });
    },

    loginSuccess() {
      this.$store
        .dispatch("GetInfo")
        .then((res) => {
          console.log("========", res);
          let menuList = res.data.menuList;
          if (menuList.length > 0) {
            this.$store
              .dispatch("GenerateRoutes", initRouterTree(menuList))
              .then(() => {
                this.$router.addRoutes(this.$store.getters.addRouters);
                let redirectPath = this.$route.query.redirect;
                if (redirectPath) {
                  this.$router.push({ path: redirectPath });
                } else {
                  this.$router.push({ path: "/" });
                }
              });
          } else {
            notification.error({
              message: "错误",
              description: "当前登录用户没有任何权限，请联系管理员增加权限",
            });
            this.$store.dispatch("Logout");
          }
          this.loginBtn = false;
        })
        .catch((e) => {
          console.info(e)
          notification.error({
            message: "错误",
            description: "加载用户信息或初始化路由失败，请联系管理员",
          });
          this.$store.dispatch("Logout");
          this.loginBtn = false;
        });
    },
    requestFailed() {
      this.loginBtn = false;
    },
    showErrorMsg(msg) {
      this.$notification["error"]({
        message: "错误",
        description: msg,
        duration: 4,
      });
      this.loginBtn = false;
    },
  },
};
</script>

<style lang="less" scoped>
.flex-row {
  background-image: url('/login-bg.png');
  background-size: cover;
}

.left-side-text {
  position: absolute;
  color: aliceblue;
  font-family: PingFangSC-Regular, PingFang SC;
  top: 33vh;
  left: 19vh;
  letter-spacing: 4px;
  font-size: 2vh;
}
.aaa {
  font-size: 30px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #3e3e3e;
}
.bbb {
  font-size: 40px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 600;
  color: #3e3e3e;
}
.img {
  height: 100vh;
}

.user-layout-login {
  label {
    font-size: 14px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>