<template>
  <el-dialog
    v-model="visible"
    :title="L['loginDialog']['登录']"
    width="500px"
    :before-close="handleClose"
    align-center
    modal-class="login-dialog-model"
  >
    <div class="login-form">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-position="top"
      >
        <el-form-item class="login-contact" :label="L['loginDialog']['邮箱']" prop="email" v-if="contactType==='email'">
          <el-input v-model="ruleForm.email" clearable />
          <div v-if="contactExistMsg" class="login-contact-error">{{ contactExistMsg }}</div>
        </el-form-item>

        <el-form-item class="login-contact" :label="L['loginDialog']['手机']" prop="mobile" v-if="contactType==='mobile'">
          <el-input v-model="ruleForm.mobile" clearable />
          <div v-if="contactExistMsg" class="login-contact-error">{{ contactExistMsg }}</div>
        </el-form-item>

        <el-form-item
          class="item-password"
          :label="L['loginDialog']['密码']"
          prop="password"
        >
          <el-input v-model="ruleForm.password" show-password type="password" />
          <div class="actions">
            <el-button type="text" @click="onForgotPassword">{{
              L["忘记密码"]
            }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="login-bottom">
      <el-button
        class="login-btn"
        :loading="loginLoading"
        @click="onLogin"
        round
        >{{ L["loginDialog"]["登录"] }}</el-button
      >
      <el-button
        type="default"
        class="register-btn"
        @click="onRegister"
        round
        >{{ L["注册"] }}</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineExpose } from "vue";
import { getCurLanguage, checkEmail } from "@/composables/common.js";
import { useFiltersStore } from "@/store/filter.js";
import { getContactType } from "../utils/common";

const filtersStore = useFiltersStore();

const contactType = getContactType();

const L = getCurLanguage();

const emit = defineEmits(["login", "register", "forgot", "close"]);

const visible = ref(false);
const loginLoading = ref(false);
const contactExistMsg = ref('')

const ruleFormRef = ref();

const ruleForm = reactive({
  email: "",
  mobile: "",
  password: "",
});

const checkEmailFun = (rule, value, callback) => {
  if (checkEmail(value) !== true) {
    callback(new Error(checkEmail(value)));
  }
  callback();
};

const checkMobileFun = (rule, value, callback) => {
  if (checkPhone(value) !== true) {
    callback(new Error(checkPhone(value)));
  }
  callback();
};

const rules = reactive({
  email: [
    { required: true, message: L["请输入邮箱"], trigger: "blur" },
    { validator: checkEmailFun, trigger: "blur" },
  ],
  mobile: [
    { required: true, message: L["请输入手机号"], trigger: "blur" },
    { validator: checkMobileFun, trigger: "blur" },
  ],
  password: [
    {
      required: true,
      message: L["请输入密码"],
      trigger: "change",
    },
  ],
});

const open = () => {
  visible.value = true;
};

const close = () => {
  visible.value = false;
};

// 关闭弹窗
const handleClose = () => {
  close();
  emit("close");
};

const login = () => {
  loginLoading.value = true;
  post("v3/frontLogin/oauth/token", {
    username: contactType === 'email' ? ruleForm.email : ruleForm.mobile,
    password: ruleForm.password,
    loginType: 1,
  })
    .then((res) => {
      if (res.state == 200) {
        //将用户信息存缓存，并跳转到首页
        filtersStore.setLoginStatus(true);
        filtersStore.setToken(res.data.access_token);
        filtersStore.setRefreshToken(res.data.refresh_token);
        filtersStore.setTime(new Date().getTime().toString()); //存储refresh_token更新时间
        //获取用户信息，并同步信息到pinia
        contactExistMsg.value = ''
        return res;
      }
      contactExistMsg.value = res.msg;
      return Promise.reject();
    })
    .then(() => {
      return get("v3/member/front/member/getInfo");
    })
    .then((res) => {
      if (res.state == 200) {
        filtersStore.setMemberInfo(res.data);
        showMessage({
          message: L['loginDialog']['登录成功'],
          type: "success",
        });
        close()
      } else {
        showMessage({
          message: res.msg,
          type: "error",
        });
      }
    })
    .finally(() => {
      loginLoading.value = false;
    });
};

// 登陆操作
const onLogin = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      return login();
    }
  });
};

// 注册
const onRegister = () => {
  emit("register");
  close();
};

// 忘记密码
const onForgotPassword = () => {
  emit("forgot");
};

defineExpose({ open });
</script>

<style lang="scss">
.login-dialog-model {
  .el-dialog__body {
    padding: 20px 40px;
  }
}
</style>
<style lang="scss" scoped>
.login-form {
  display: flex;
  justify-content: center;

  :deep(.el-input) {
    width: 300px;
  }

  :deep(.el-input__inner) {
    height: 35px;
  }

  .item-password {
    position: relative;

    .actions {
      position: absolute;
      right: 0;
      top: -35px;

      .el-button {
        color: #606266;
      }
    }
  }

  .login-contact {
    position: relative;
    margin-bottom: 25px;
    &-error {
      position: absolute;
      left: 0;
      bottom: -30px;
      color: red;
    }
  }
}

.login-bottom {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  :deep(.el-button) {
    width: 300px;
    height: 35px;
    margin-left: 0;
    margin-top: 10px;
  }

  .login-btn {
    background-color: $colorMain;
    color: #fff;
  }

  .register-btn {
    &:hover {
      color: $colorMain;
    }
  }
}
</style>
