<template>
  <div class="mobile-login-container">
    <div class="login-header">
      <img src="/logo.png" alt="Logo" class="logo-img" />
      <h2>统一登录平台</h2>
      <div v-if="ssoAppName" class="sso-tag">正在登录 {{ ssoAppName }}</div>
    </div>
    
    <div class="login-content">
      <!-- Tabs if SMS enabled and NO SSO context (or simple check) -->
      <el-tabs v-if="smsEnabled" v-model="activeTab" class="login-tabs" stretch>
        <el-tab-pane label="密码登录" name="password">
            <el-form :model="loginForm" label-width="0px" class="login-form">
                <el-form-item>
                <el-input v-model="loginForm.mobile" placeholder="手机号" :prefix-icon="Iphone" size="large" />
                </el-form-item>
                <el-form-item>
                <el-input 
                    v-model="loginForm.password" 
                    type="password" 
                    placeholder="密码" 
                    :prefix-icon="Lock" 
                    show-password
                    size="large"
                />
                </el-form-item>
                <el-form-item>
                <el-checkbox v-model="loginForm.remember_me">记住我 (一年免登录)</el-checkbox>
                </el-form-item>
                <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleLogin" style="width: 100%" size="large">
                    登录
                </el-button>
                </el-form-item>
                <div class="login-links">
                <router-link to="/mobile/reset-password">忘记密码？</router-link>
                </div>
            </el-form>
        </el-tab-pane>
        <el-tab-pane label="验证码登录" name="sms">
            <el-form :model="smsForm" label-width="0px" class="login-form">
                <el-form-item>
                    <el-input v-model="smsForm.mobile" placeholder="手机号" :prefix-icon="Iphone" size="large" />
                </el-form-item>
                <el-form-item>
                    <el-row :gutter="10" style="width: 100%">
                        <el-col :span="15">
                             <el-input v-model="smsForm.code" placeholder="验证码" :prefix-icon="Key" size="large" />
                        </el-col>
                        <el-col :span="9">
                            <el-button @click="handleSendCode" :disabled="countdown > 0" style="width: 100%" size="large">
                                {{ countdown > 0 ? `${countdown}s` : '发送' }}
                            </el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-model="smsForm.remember_me">记住我 (一年免登录)</el-checkbox>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :loading="loading" @click="handleSmsLogin" style="width: 100%" size="large">
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
        </el-tab-pane>
      </el-tabs>

      <!-- Fallback / SSO Layout -->
      <el-form v-else :model="loginForm" label-width="0px" class="login-form">
        <el-form-item>
          <el-input v-model="loginForm.mobile" placeholder="手机号" :prefix-icon="Iphone" size="large" />
        </el-form-item>
        <el-form-item>
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="密码" 
            :prefix-icon="Lock" 
            show-password
            size="large"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.remember_me">记住我 (一年免登录)</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" style="width: 100%" size="large">
            登录
          </el-button>
        </el-form-item>
        <div class="login-links">
          <router-link to="/mobile/reset-password">忘记密码？</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../../store/auth'
import { getAppPublicInfo, ssoLogin } from '../../api/public'
import { getPublicConfigs } from '../../api/systemConfig'
import { sendSmsCode, loginWithSms } from '../../api/smsAuth'
import { ElMessage } from 'element-plus'
import { Iphone, Lock, Key } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const activeTab = ref('password')
const smsEnabled = ref(false)
const countdown = ref(0)
let timer: any = null

const loginForm = reactive({
  mobile: '',
  password: '',
  remember_me: true
})

const smsForm = reactive({
  mobile: '',
  code: '',
  remember_me: true
})

const loading = ref(false)
const ssoAppId = ref('')
const ssoAppName = ref('')

const handleSendCode = async () => {
    if (!smsForm.mobile) {
        ElMessage.warning('请输入手机号')
        return
    }
    try {
        await sendSmsCode(smsForm.mobile, 'mobile')
        ElMessage.success('验证码已发送')
        countdown.value = 60
        timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
                clearInterval(timer)
            }
        }, 1000)
    } catch (e) {
        // handled
    }
}

const handleSmsLogin = async () => {
    if (!smsForm.mobile || !smsForm.code) {
        ElMessage.warning('请输入手机号和验证码')
        return
    }
    loading.value = true
    try {
        const res = await loginWithSms({
            mobile: smsForm.mobile,
            code: smsForm.code,
            platform: 'mobile',
            remember_me: smsForm.remember_me
        })
        
        // Manual login success handling since authStore.login is for password
        const token = res.data.access_token
        authStore.token = token
        localStorage.setItem('token', token)
        await authStore.fetchUser()
        
        // SSO Redirect Check
        if (ssoAppId.value) {
             const ssoRes = await ssoLogin({
                app_id: ssoAppId.value,
                username: '',
                password: ''
            })
            if (ssoRes.data.redirect_url) {
                ElMessage.success('登录成功，正在跳转...')
                window.location.href = ssoRes.data.redirect_url
                return
            }
        }

        ElMessage.success('登录成功')
        router.push('/mobile/dashboard')
    } catch (e) {
        // handled
    } finally {
        loading.value = false
    }
}

const handleLogin = async () => {
  if (!loginForm.mobile || !loginForm.password) {
    ElMessage.warning('请输入手机号和密码')
    return
  }
  
  loading.value = true
  try {
    if (ssoAppId.value) {
      // SSO Login Flow
      const res = await ssoLogin({
        app_id: ssoAppId.value,
        username: loginForm.mobile,
        password: loginForm.password
      })
      if (res.data.redirect_url) {
        ElMessage.success('登录成功，正在跳转...')
        window.location.href = res.data.redirect_url
      }
    } else {
      // Platform Login Flow
      await authStore.login({
        mobile: loginForm.mobile,
        password: loginForm.password,
        remember_me: loginForm.remember_me
      })
      ElMessage.success('登录成功')
      router.push('/mobile/dashboard')
    }
  } catch (error) {
    // Error handled in interceptor
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  const appid = route.query.appid as string || route.query.app_id as string
  
  // Fetch Config
  try {
      const configRes = await getPublicConfigs()
      if (configRes.data) {
          const mobileConfig = configRes.data.find((c: any) => c.key === 'sms_login_mobile_enabled')
          if (mobileConfig && mobileConfig.value === 'true') {
              smsEnabled.value = true
              activeTab.value = 'sms'
          }
      }
  } catch(e) {
      console.error("Failed to fetch public config", e)
  }

  if (appid) {
    try {
      const appInfo = await getAppPublicInfo(appid)
      ssoAppId.value = appid
      ssoAppName.value = appInfo.data.app_name
      
      // Try Auto-Login (SSO)
      try {
          const res = await ssoLogin({
            app_id: appid,
            username: '',
            password: ''
          }, { skipGlobalErrorHandler: true })
          
          if (res.data.redirect_url) {
            ElMessage.success(`检测到已登录，正在跳转到 ${appInfo.data.app_name}...`)
            window.location.href = res.data.redirect_url
            return
          }
      } catch (e) {
          // Auto-login failed, user needs to login manually
          console.log("Auto-login failed, showing login form")
      }
    } catch (e) {
      ElMessage.error('无效的应用ID')
    }
  }
})
</script>

<style scoped>
.mobile-login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 100vh;
  background-color: #fff;
  padding: 0 30px;
}

.login-header {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  margin-bottom: 40px;
}

.sso-tag {
  color: #67C23A;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 16px;
  margin-top: 5px;
}

.logo-img {
  height: 80px;
  object-fit: contain;
}

.login-content {
  width: 100%;
}

.login-links {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

/* Custom Large Input Styles */
:deep(.el-input--large .el-input__wrapper) {
  padding: 8px 15px;
  border-radius: 8px;
}

:deep(.el-input--large .el-input__inner) {
  font-size: 18px;
  font-weight: 500;
  height: 40px;
}

:deep(.el-button--large) {
  height: 48px;
  font-size: 18px;
  border-radius: 8px;
}

/* Tabs Styles */
:deep(.el-tabs__item) {
    font-size: 16px;
}
</style>
