<template>
  <el-dialog
    v-model="dialogVisible"
    :title="''"
    width="420px"
    center
    custom-class="login-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <!-- 登录标题 -->
    <div class="login-header">
      <h2 class="login-title">{{ $t('common.login') }}</h2>
      <!-- <p class="login-subtitle">请登录您的账号</p> -->
    </div>
    
    <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="login-tabs">
      <el-tab-pane :label="$t('login.smsLogin')" name="sms">
        <el-form ref="smsFormRef" :model="smsForm" :rules="smsRules" label-width="0">
          <el-form-item prop="account" class="login-form-item">
            <el-input
              v-model="smsForm.account"
              :placeholder="$t('login.placeholderPhoneOrEmail')"
              prefix-icon="User"
              clearable
              class="login-input"
            />
          </el-form-item>
          <el-form-item prop="smsCode" class="login-form-item">
            <el-input
              v-model="smsForm.verifyCode"
              :placeholder="$t('login.placeholderCaptcha')"
              prefix-icon="Message"
              clearable
              class="login-input"
            >
              <template #append>
                <el-button
                  :disabled="smsCountdown > 0"
                  @click="sendSmsCode"
                  style="width:140px"
                  :class="{'countdown-btn': smsCountdown > 0}"
                  size="small"
                >
                  {{ smsCountdown > 0 ? `${smsCountdown}s` : $t('login.sendCaptcha') }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="login-form-item">
            <el-button 
              type="primary" 
              @click="handleSmsLogin" 
              :loading="loading" 
              class="login-button gradient"
              size="large"
            >
              {{ $t('common.login') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane :label="$t('login.passwordLogin')" name="password">
        <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="0">
          <el-form-item prop="account" class="login-form-item">
            <el-input
              v-model="passwordForm.account"
              :placeholder="$t('login.placeholderAccount')"
              prefix-icon="User"
              clearable
              class="login-input"
            />
          </el-form-item>
          <el-form-item prop="password" class="login-form-item">
            <el-input
              v-model="passwordForm.password"
              type="password"
              :placeholder="$t('login.placeholderPassword')"
              prefix-icon="Lock"
              show-password
              class="login-input"
            />
          </el-form-item>
          <!-- 增加动态验证码图片 -->
          <el-form-item prop="captcha" class="login-form-item">
            <el-input
              v-model="passwordForm.captcha"
              :placeholder="$t('login.placeholderCaptcha')"
              prefix-icon="Lock"
              class="login-input"
            >
            <template #append>
              <img :src="captchaImg" alt="验证码" class="captcha-img" @click="getCaptchaFn">
            </template>
            </el-input>
          </el-form-item>

          <el-form-item class="login-form-item remember-item">
            <!-- <el-checkbox v-model="passwordForm.remember" class="remember-checkbox">
              <span class="remember-text">记住密码</span>
            </el-checkbox> -->
            <el-link type="primary" href="#" :underline="false" class="forgot-link" @click="activeTab = 'reset'">{{ $t('login.forgetPassword') }} ?</el-link>
          </el-form-item>
          <el-form-item class="login-form-item">
            <el-button 
              type="primary" 
              @click="handlePasswordLogin" 
              :loading="loading" 
              class="login-button gradient"
              size="large"
            >
              {{ $t('common.login') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      
      <el-tab-pane :label="$t('login.resetPassword')" name="reset">
        <el-form ref="resetFormRef" :model="resetForm" :rules="resetRules" label-width="0">
          <el-form-item prop="account" class="login-form-item">
            <el-input
              v-model="resetForm.account"
              :placeholder="$t('login.placeholderPhoneOrEmail')"
              prefix-icon="User"
              clearable
              class="login-input"
            />
          </el-form-item>
          <el-form-item prop="smsCode" class="login-form-item">
            <el-input
              v-model="resetForm.verifyCode"
              :placeholder="$t('login.placeholderCaptcha')"
              prefix-icon="Message"
              clearable
              class="login-input"
            >
              <template #append>
                <el-button
                  :disabled="passwordresetCountdown > 0"
                  @click="sendPasswordresetCode"
                  style="width:140px"
                  :class="{'countdown-btn': passwordresetCountdown > 0}"
                  size="small"
                >
                  {{ passwordresetCountdown > 0 ? `${passwordresetCountdown}s` : $t('login.sendCaptcha') }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="newPassword" class="login-form-item">
            <el-input
              v-model="resetForm.newPassword"
              :placeholder="$t('login.placeholderNewPassword')"
              prefix-icon="Lock"
              show-password
              class="login-input"
            />
          </el-form-item>
          <el-form-item prop="confirmPassword" class="login-form-item">
            <el-input
              v-model="resetForm.confirmPassword"
              :placeholder="$t('login.placeholderConfirmPassword')"
              prefix-icon="Lock"
              show-password
              class="login-input"
            />
          </el-form-item>
          <el-form-item class="login-form-item">
            <el-button 
              type="primary" 
              @click="handleResetPassword" 
              :loading="loading" 
              class="login-button gradient"
              size="large"
            >
              {{ $t('common.login') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 其他登录方式 -->
    <div class="other-login">
      <div class="divider">
        <span class="divider-text">{{ $t('login.otherLogin') }}</span>
      </div>
      <div class="social-login">
        <el-button
          type="default"
          @click="handleWechatLogin"
          class="social-btn wechat-btn"
        >
          <img :src="WeChatIcon" alt="微信登录" style="width: 24px; height: 24px;">
        </el-button>
        <el-button
          type="default"
          @click="handleQqLogin"
          class="social-btn qq-btn"
        >
          <img :src="QQIcon" alt="微信登录" style="width: 24px; height: 24px;">
        </el-button>
      </div>
    </div>
    <div class="flex-center mt20">
      <div>
        <span class="gray999">{{ $t('login.loginAgreement') }}</span>
        <span class="cursor-pointer link"
        @click="router.push({name:'Agreement',query:{type:'privacy_policy'}});dialogVisible=false;">
          《{{ $t('agreement.privacy_policy') }}》
        </span>
      </div>
    </div>
    
    <!-- 注册链接 -->
    <!-- <div class="register-link">
      <span>还没有账号？</span>
      <el-link type="primary" href="#" :underline="false">立即注册</el-link>
    </div> -->
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import DGTMessage from '@/utils/message'
import QQIcon from '@/assets/imgs/QQ.png'
import WeChatIcon from '@/assets/imgs/WeChat.png'
import { getCaptcha, loginUsername, loginPhone, loginEmail, getSmsCode, getEmailCode, resetPassword, getPasswordresetCode } from '@/api/auth.js'
import { useAppStore } from '@/pinia/appStore'
const appStore = useAppStore();
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
import { useI18n } from 'vue-i18n' 
const { t } = useI18n() 
// 正则表达式
const PHONE_REGEX = /^1[3-9]\d{9}$/;
const EMAIL_REGEX = /^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$/;
const isPasswordPhone = computed(() => {
  return PHONE_REGEX.test(passwordForm.account);
});

const isPasswordEmail = computed(() => {
  return EMAIL_REGEX.test(passwordForm.account);
});


const emit = defineEmits(['login-success'])

// 对话框可见性
const dialogVisible = ref(false)
// 验证码图片
const captchaImg = ref('')


const open = () => {
  dialogVisible.value = true;
  appStore.showLoginDialog = false;
  getCaptchaFn()
}

const getCaptchaFn = async (type) => {
  try {
    const res = await getCaptcha()
    passwordForm.uuid = res.data?.uuid;
    if (res.data?.img.startsWith('data:image')) {
      captchaImg.value = res.data?.img;
    } else {
      captchaImg.value = 'data:image/jpeg;base64,' + res.data?.img;
    }
  } catch (error) {
    ElMessage.error(error.message || '验证码获取失败')
  }
}

// 当前激活的标签页
const activeTab = ref('sms')

// 密码登录表单
const passwordForm = reactive({
  account: '',//
  password: '',//
  captcha: '',
  uuid: ''
})

// 短信登录表单
const smsForm = reactive({
  account: '',
  verifyCode: ''
})

// 重置密码表单
const resetForm = reactive({
  account: '',
  verifyCode: '',
  newPassword: '',
  confirmPassword: ''
})



// 表单引用
const passwordFormRef = ref(null)
const smsFormRef = ref(null)
const resetFormRef = ref(null)

// 加载状态
const loading = ref(false)

// 验证码倒计时
const smsCountdown = ref(0)
const passwordresetCountdown = ref(0)
const emailCountdown = ref(0)

// 表单验证规则
const passwordRules = reactive({
  account: [
    { required: true, message: t('login.placeholderAccount'), trigger: 'blur' },
    { validator: (val) => isPasswordPhone.value || isPasswordEmail.value, message: t('login.placeholderPhoneOrEmailTip'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('login.placeholderPassword'), trigger: 'blur' },
    { min: 6, message: t('login.passwordMinLength'), trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: t('login.placeholderCaptcha'), trigger: 'blur' }
  ]
})

const smsRules = reactive({
  account: [
    { required: true, message: t('login.placeholderPhoneOrEmail'), trigger: 'blur' },
    { validator: (rule, val) => PHONE_REGEX.test(val) || EMAIL_REGEX.test(val), message: t('login.placeholderPhoneOrEmailTip'), trigger: 'blur' }

  ],
  verifyCode: [
    { required: true, message: t('login.placeholderCaptcha'), trigger: 'blur' },
    // { min: 6, max: 6, message: '验证码长度为6个字符', trigger: 'blur' }
  ]
})
// 重置密码表单验证规则
const resetRules = reactive({
  account: [
    { required: true, message: t('login.placeholderPhoneOrEmail'), trigger: 'blur' },
    { validator: (rule, val) => PHONE_REGEX.test(val) || EMAIL_REGEX.test(val), message: t('login.placeholderPhoneOrEmailTip'), trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: t('login.placeholderCaptcha'), trigger: 'blur' },
    // { min: 6, max: 6, message: '验证码长度为6个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: t('login.placeholderNewPassword'), trigger: 'blur' },
    { min: 6, message: t('login.passwordMinLength'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('login.placeholderConfirmPassword'), trigger: 'blur' },
    { validator: (rule, val) => val === resetForm.newPassword, message: t('login.passwordNotSame'), trigger: 'blur' }
  ]
})


// 处理标签页切换
const handleTabChange = () => {
  // 切换标签页时重置表单
  if (activeTab.value === 'password') {
    passwordFormRef.value?.resetFields()
  } else if (activeTab.value === 'sms') {
    smsFormRef.value?.resetFields()
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!smsForm.account) {
    ElMessage.warning(t('login.placeholderPhoneOrEmail'))
    return
  }

  // 验证手机号格式
  if (!PHONE_REGEX.test(smsForm.account) && !EMAIL_REGEX.test(smsForm.account)) {
    ElMessage.warning(t('login.placeholderPhoneOrEmailTip'))
    return
  }

  let res = null;
  if(PHONE_REGEX.test(smsForm.account)){
    res = await getSmsCode({
      phone: smsForm.account
    })
  } else if (EMAIL_REGEX.test(smsForm.account)){
    res = await getEmailCode({
      email: smsForm.account
    })
  }

  if(res.code !== 200){
    return
  }

  // 模拟发送验证码
  ElMessage.success(t('login.captchaSendSuccess'))
  
  // 开始倒计时
  smsCountdown.value = 60
  const timer = setInterval(() => {
    smsCountdown.value--
    if (smsCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 发送邮箱验证码
const sendEmailCode = () => {
  if (!emailForm.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }

  // 模拟发送验证码
  ElMessage.success(t('login.captchaSendSuccess'))
  
  // 开始倒计时
  emailCountdown.value = 60
  const timer = setInterval(() => {
    emailCountdown.value--
    if (emailCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 密码登录
const handlePasswordLogin = () => {
  passwordFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true
       const params = {};
      // 根据账号类型决定参数名
      if (isPasswordPhone.value) {
        params['phone'] = passwordForm.account;
      } else if (isPasswordEmail.value) {
        params['email'] = passwordForm.account;
      }
      
      params['password'] = passwordForm.password;
      params['captcha'] = passwordForm.captcha;
      params['uuid'] = passwordForm.uuid;
      const res = await loginUsername(params);
      loading.value = false
      if (res.code === 200) {
        ElMessage.success(t('login.loginSuccess'))
        // emit('login-success', { type: 'password', userInfo: passwordForm })
        dialogVisible.value = false;
        // 登录成功后，将token存储到localStorage
        setToken(res.token);
        //刷新当前页
        // window.location.reload();
      }
    }
  })
}

// 短信登录
const handleSmsLogin = () => {
  smsFormRef.value?.validate(async(valid) => {
    if (valid) {
      loading.value = true
      const params = {};
      let res = {};
      params['code'] = smsForm.verifyCode;
      // 根据账号类型决定参数名
      if (PHONE_REGEX.test(smsForm.account)) {
        params['phone'] = smsForm.account;
        res = await loginPhone(params);
      } else if (EMAIL_REGEX.test(smsForm.account)) {
        params['email'] = smsForm.account;
        res = await loginEmail(params);
      }
      loading.value = false
      if (res.code === 200) {
        ElMessage.success(t('login.loginSuccess'))
        // emit('login-success', { type: 'sms', userInfo: smsForm })
        dialogVisible.value = false;
        // 登录成功后，将token存储到localStorage
        setToken(res.token);
        //刷新当前页
        // window.location.reload();
      } 
    }
  })
}
// 发送重置密码验证码
const sendPasswordresetCode = async () => {
  if (!resetForm.account) {
    ElMessage.warning(t('login.placeholderPhoneOrEmail'))
    return
  }

  // 验证手机号格式
  if (!PHONE_REGEX.test(resetForm.account) && !EMAIL_REGEX.test(resetForm.account)) {
    ElMessage.warning(t('login.placeholderPhoneOrEmailTip'))
    return
  }

  let res = await getPasswordresetCode({
    account: resetForm.account
  })

  if(res.code !== 200){
    return
  }
  ElMessage.success(t('login.captchaSendSuccess'))
  // 开始倒计时
  passwordresetCountdown.value = 60
  const timer = setInterval(() => {
    passwordresetCountdown.value--
    if (passwordresetCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}
// 重置密码
const handleResetPassword = () => {
  resetFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true
      const res = await resetPassword(resetForm);
      loading.value = false
      if (res.code === 200) {
        ElMessage.success('密码重置成功')
        activeTab.value = 'password';
      } 
    }
  })
}



const setToken = (token) => {
  appStore.UPDATE_TOKEN(token);
  //获取当前路由 ，路由是/learn-note
  console.log(route.path)
  if(
    route.path.startsWith('/learn-note') ||
    route.path.startsWith('/mibi-shop')
  ){
    // 刷新当前页
    window.location.reload();
  }
  // window.location.reload();
}


// 微信登录
const handleWechatLogin = () => {
  ElMessage.info('微信登录功能开发中')
}

// QQ登录
const handleQqLogin = () => {
  ElMessage.info('QQ登录功能开发中')
}

defineExpose({
  open
});
</script>

<style scoped lang="scss">
/* 登录对话框容器 */
.login-dialog {
  .el-dialog__header {
    padding: 0;
  }
  
  .el-dialog__body {
    padding: 20px 30px 30px;
  }
  
  .el-dialog__footer {
    display: none;
  }
}

/* 登录标题 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-subtitle {
  font-size: 14px;
  color: #909399;
}

/* 标签页 */
.login-tabs {
  margin-bottom: 20px;
  
  .el-tabs__nav {
    justify-content: center;
  }
  
  .el-tabs__item {
    font-size: 15px;
    color: #606266;
    padding: 0 20px;
  }
  
  .el-tabs__item.is-active {
    color: #667eea;
    font-weight: 500;
  }
  
  .el-tabs__active-bar {
    background-color: #667eea;
    height: 3px;
  }
}

/* 表单样式 */
.login-form-item {
  margin-bottom: 20px;
}

/* 输入框样式 */
.login-input {
  height: 48px;
  border-radius: 24px;
  // border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
  font-size: 15px;
  
  &:hover {
    // border-color: #667eea;
    // box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
  }
  
  &.is-focus {
    // border-color: #667eea;
    // box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
  }
  
  .el-input__wrapper {
    box-shadow: none;
    background-color: #fafafa;
    border-radius: 24px;
  }
  
  .el-input__inner {
    background-color: transparent;
    border: none;
    height: 48px;
    line-height: 48px;
  }
}

/* 记住密码和忘记密码 */
.remember-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.remember-checkbox {
  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #667eea;
    border-color: #667eea;
  }
  
  .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #667eea;
  }
}

.remember-text {
  font-size: 14px;
  color: #606266;
}

.forgot-link {
  font-size: 14px;
  color: #667eea;
  transition: color 0.3s ease;
  
  &:hover {
    color: #5366d1;
  }
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 48px;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 500;
  border: none;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
  }
  
  &:active {
    transform: translateY(0);
  }
}

/* 其他登录方式 */
.other-login {
  margin-top: 30px;
}

.divider {
  position: relative;
  text-align: center;
  margin-bottom: 20px;
  
  &::before, &::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 40%;
    height: 1px;
    background-color: #ebeef5;
  }
  
  &::before {
    left: 0;
  }
  
  &::after {
    right: 0;
  }
}

.divider-text {
  display: inline-block;
  padding: 0 20px;
  font-size: 13px;
  color: #909399;
  background-color: #fff;
}

/* 社交登录按钮 */
.social-login {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.social-btn {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
  
  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  }
}

.wechat-btn {
  color: #67c23a;
  
  &:hover {
    border-color: #67c23a;
    background-color: rgba(103, 194, 58, 0.05);
  }
}

.qq-btn {
  color: #409eff;
  
  &:hover {
    border-color: #409eff;
    background-color: rgba(64, 158, 255, 0.05);
  }
}

/* 注册链接 */
.register-link {
  text-align: center;
  margin-top: 25px;
  font-size: 14px;
  color: #606266;
  
  .el-link {
    margin-left: 5px;
    color: #667eea;
    font-weight: 500;
    
    &:hover {
      color: #5366d1;
    }
  }
}

/* 验证码按钮 */
.countdown-btn {
  background-color: #f5f7fa;
  color: #909399;
  border-color: #e4e7ed;
  
  &:hover {
    background-color: #e4e7ed;
    border-color: #dcdfe6;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-dialog {
    width: 90% !important;
    margin: 0 auto;
    
    .el-dialog__body {
      padding: 20px;
    }
  }
  
  .login-title {
    font-size: 22px;
  }
  
  .login-input,
  .login-button {
    height: 44px;
  }
}
</style>