<template>
  <div class="login-by-code">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules">
      <el-form-item prop="mobile">
        <el-input
          v-model="loginForm.mobile"
          autofocus="autofocus"
          placeholder="请输入手机号码"
          @keyup.enter.native="loginAction()" />
      </el-form-item>
      <el-form-item prop="code">
        <div class="msg-code">
          <el-input
            v-model="loginForm.code"
            placeholder="请输入验证码"
            @keyup.enter.native="loginAction()"
            style="width: 280px">
          </el-input>
          <div class="yzm_img">
            <el-button
              type="primary"
              :disabled="countDown > 0"
              @click.prevent="getMsgCode()"
              style="width: 100%; height: 34px">
              {{ countDown > 0 ? countDown + "秒后再次获取" : "发送验证码" }}
            </el-button>
            <!-- <a class="input-append disabled" v-if="false && countDown > 0">
                  {{ countDown }}秒后再次获取
                </a>
                <a class="input-append" @click="getMsgCode" v-else>
                  获取验证码
                </a> -->
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.prevent="loginAction()" style="width: 100%"> 登 录 </el-button>
      </el-form-item>
      <el-form-item>
        <el-button class="register_btn" @click.prevent="$emit('register')" style="width: 100%">
          还没有账号？前往注册
          <bg-icon icon="#bg-ic-arrow-right"></bg-icon>
        </el-button>
      </el-form-item>
      <div>
        <span class="fr forget_psd" @click.prevent="$emit('password')">忘记密码？</span>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onBeforeMount, nextTick } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";

const validatePhone = (rule, value, callback) => {
  const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;

  setTimeout(() => {
    if (!reg.test(value)) {
      callback(new Error("请输入正确的手机号码"));
    } else {
      callback();
    }
  });
};

const state = reactive({
  loginForm: {
    mobile: "",
    code: "",
  },
  loginFormRules: {
    mobile: [
      { required: true, message: "请输入手机号码", trigger: "blur" },
      { validator: validatePhone, trigger: "blur" },
    ],
    code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  },
  countDown: 0,
  countDownTimer: null,
});

const loginFormRef = ref(null);

const getMsgCode = () => {
  loginFormRef.value.validateField("mobile", (valid) => {
    if (valid) {
      axios.post("/apaas/system/v5/sms/verifyCode", { phone: state.loginForm.mobile }).then(({ data }) => {
        if (data.code == 200) {
          countDownAction();
        } else {
          ElMessage.error(data.data);
        }
      });
    }
  });
}; // 获取验证码
const countDownAction = () => {
  state.countDown = 60;

  if (state.countDownTimer) {
    clearInterval(state.countDownTimer);
  }

  state.countDownTimer = setInterval(() => {
    if (state.countDown > 0) {
      state.countDown--;
    } else {
      clearInterval(state.countDownTimer);
    }
  }, 1000);
};
const loginAction = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      axios
        .post(`/apaas/system/v5/user/phone/login`, {
          phone: state.loginForm.mobile,
          code: state.loginForm.code,
        })
        .then(({ data }) => {
          if (data.code == 200) {
            getUser();
          } else {
            ElMessage.error(data.data);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    }
  });
}; // 短信验证码登录

const getUserInfo = () => {
  return axios.get(`/apaas/system/v5/user/getUserInfo`);
};
const getMenu = (search) => {
  return axios.get(`/apaas/system/v5/menu/user/tree?search=${search}`);
};
const getUser = () => {
  Promise.all([getUserInfo(), getMenu("dadb2d3f-e263-48d1-9389-42acb9ea49f8")]).then((res) => {
    if (res[0].data.code == 200 && res[1].data.code == 200) {
      let data = (res[1].data.data && res[1].data.data[0].children) || [];
      store.commit("setUserInfo", res[0].data.data);
      // if (res.data.data.userType == 1) {
      //超管
      store.commit("setMenu", data);

      menu.menuToRouter(data);

      store.commit("setRoute", data);

      //存储菜单对象信息
      let menuObj = {};
      getMenuObj(data, "", menuObj);
      store.commit("setMenuObj", menuObj);
      // }
      generateRoutes();
      // this.$router.push("/");
      //跳转到工作台页面
      window.location.href = "/apaas/portal/ui/#/";
    }
  });
};

const { loginForm, loginFormRules, countDown, countDownTimer } = toRefs(state);
</script>

<style lang="scss" scoped>
.login-by-code {
  .msg-code {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    .yzm_img {
      flex: 1;
      margin-left: 20px;
    }
  }
  .el-form {
    .form-title {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      line-height: 20px;
      margin-bottom: 5px;

      > img {
        margin-left: 5px;
      }
    }
  }
}
</style>
