<template>
  <div class="my-mappings-container">
    <div class="header">
      <h2>平台账号管理</h2>
      <div class="header-actions">
        <el-input 
            v-model="searchQuery" 
            placeholder="搜索应用名称" 
            style="width: 250px; margin-right: 10px;"
            clearable
            @clear="fetchMappings"
            @keyup.enter="handleSearch"
        >
            <template #append>
              <el-button icon="Search" @click="handleSearch" />
            </template>
        </el-input>

        <el-button type="primary" @click="fetchMappings">
          <el-icon style="margin-right: 4px"><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <el-table :data="mappings" v-loading="loading" stripe border style="width: 100%">
      <el-table-column prop="app_name" label="应用名称" min-width="150" />
      <el-table-column prop="mapped_key" label="映射账号" min-width="150" />
      <el-table-column prop="mapped_email" label="映射邮箱" min-width="180">
        <template #default="scope">
          {{ scope.row.mapped_email || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="is_active" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
            {{ scope.row.is_active ? '正常' : '已禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            :disabled="!scope.row.is_active"
            :loading="loginLoading[scope.row.app_id]"
            @click="handleSsoLogin(scope.row)"
          >
            进入
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { Refresh, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import api from '../utils/request'
import { ssoLogin } from '../api/public'

interface Mapping {
  app_name: string
  app_id: string
  protocol_type: string
  mapped_key: string
  mapped_email: string
  is_active: boolean
}

const mappings = ref<Mapping[]>([])
const loading = ref(false)
const searchQuery = ref('')
const loginLoading = reactive<Record<string, boolean>>({})

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const fetchMappings = async () => {
  loading.value = true
  try {
    const params: any = {
        skip: (currentPage.value - 1) * pageSize.value,
        limit: pageSize.value
    }
    if (searchQuery.value) params.app_name = searchQuery.value
    
    const res = await api.get('/simple/me/mappings', { params })
    if (res.data) {
        mappings.value = res.data.items
        total.value = res.data.total
    }
  } catch (e) {
    // handled
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
    currentPage.value = 1
    fetchMappings()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchMappings()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchMappings()
}

const handleSsoLogin = async (mapping: Mapping) => {
  if (!mapping.is_active) {
    ElMessage.warning('该账号已禁用，无法登录')
    return
  }

  loginLoading[mapping.app_id] = true
  
  try {
    // 统一通过后端 /simple/sso-login 获取 redirect_url
    // SIMPLE_API: 返回带 ticket 的业务系统 URL
    // OIDC: 返回 Hydra 授权 URL
    const res = await ssoLogin(
      { app_id: mapping.app_id, username: '', password: '' },
      { 
        // 发送认证 token（如果已登录 UAP 平台则走会话模式）
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`
        }
      }
    )
    
    if (res.data && res.data.redirect_url) {
      // 在新标签页中打开目标应用
      window.open(res.data.redirect_url, '_blank')
      ElMessage.success('正在新标签页中打开应用...')
    } else {
      ElMessage.error('SSO 登录失败：未返回跳转地址')
    }
  } catch (error: any) {
    console.error('SSO 登录失败:', error)
    ElMessage.error(error.response?.data?.detail || 'SSO 登录失败')
  } finally {
    loginLoading[mapping.app_id] = false
  }
}

onMounted(() => {
  fetchMappings()
})
</script>

<style scoped>
.my-mappings-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.header-actions {
  display: flex;
  align-items: center;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
