<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="loginAction()" />
      </el-form-item>
      <el-form-item prop="code">
        <div class="msg-code">
          <el-input
            v-model="loginForm.code"
            placeholder="请输入验证码"
            @keyup.enter="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 menu from "../router/function";
import { generateRoutes } from "../router/index";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

const router = useRouter();

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 store = useStore();
const loginFormRef = ref(null);

const getMsgCode = () => {
  loginFormRef.value.validateField("mobile", (valid) => {
    if (valid) {
      axios.post("/v1/api/user/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(`/v1/api/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(`/v1/api/user/getUserInfo`);
};
const getMenu = (search) => {
  return axios.get(`/v1/api/menu/user/tree?search=${search}`);
};
const getUser = () => {
  Promise.all([getUserInfo(), getMenu("1e99371c-187f-4966-94cf-32f116f42ce6")]).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();
      router.push("/forewarning/list");
    }
  });
};

const getMenuObj = (menu, parentRowPath, menuObj) => {
  menu.forEach((e, idx) => {
    e.rowPath = parentRowPath + "." + idx;
    menuObj[e.path] = e;
    if (e.children && e.children.length) {
      getMenuObj(e.children, e.rowPath, menuObj);
    }
  });
};

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>
