<template>
  <div class="app-sync-container">
    <div class="page-header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> 数据同步 </span>
        </template>
        <template #extra>
          <div class="flex items-center">
            <span v-if="app" class="app-name">应用: {{ app.app_name }}</span>
          </div>
        </template>
      </el-page-header>
    </div>

    <el-card class="sync-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>同步配置</span>
        </div>
      </template>

      <el-form :model="form" label-width="120px">
        <el-form-item label="同步范围">
          <el-radio-group v-model="form.mode">
            <el-radio label="ALL">所有用户</el-radio>
            <el-radio label="SELECTED">选择用户</el-radio>
          </el-radio-group>
        </el-form-item>

        <div v-if="form.mode === 'SELECTED'" class="user-selection-area">
          <!-- 添加搜索框 -->
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户（姓名、手机号、英文名）"
              clearable
              style="width: 300px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #append>
                <el-button @click="handleSearch">搜索</el-button>
              </template>
            </el-input>
            <div class="selected-count" v-if="selectedUserIds.size > 0">
              已选择 {{ selectedUserIds.size }} 个用户
            </div>
          </div>

          <!-- 已选择用户列表 -->
          <div v-if="selectedUsersList.length > 0" class="selected-users-panel">
            <div class="panel-header">
              <span class="panel-title">已选择的用户 ({{ selectedUsersList.length }})</span>
              <el-button type="danger" size="small" text @click="clearAllSelection">
                <el-icon><Delete /></el-icon>
                清空全部
              </el-button>
            </div>
            <div class="selected-users-list">
              <el-tag
                v-for="user in selectedUsersList"
                :key="user.id"
                closable
                @close="removeUser(user.id)"
                class="user-tag"
              >
                {{ user.name || user.english_name || user.mobile }}
                <span class="user-mobile">({{ user.mobile }})</span>
              </el-tag>
            </div>
          </div>

          <el-table
            ref="userTableRef"
            :data="users"
            style="width: 100%"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="english_name" label="英文名" width="120" />
            <el-table-column prop="mobile" label="手机号" width="150" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'info'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <el-form-item label="邮箱设置">
          <el-checkbox v-model="form.init_email">初始化默认域名邮箱</el-checkbox>
          <div v-if="form.init_email" class="email-domain-input">
            <el-input 
              v-model="form.email_domain" 
              placeholder="请输入域名 (例如: @example.com)" 
              style="width: 300px"
            >
              <template #prepend>账号 (英文名) + </template>
            </el-input>
            <div class="form-tip">
              勾选后，将为没有映射邮箱的用户生成邮箱：english_name@domain
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handlePreSync" :disabled="form.mode === 'SELECTED' && selectedUserIds.size === 0">
            开始同步
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Confirmation Dialog -->
    <el-dialog
      v-model="confirmDialogVisible"
      title="同步确认"
      width="500px"
    >
      <div class="confirm-content">
        <el-alert
          title="安全验证"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 20px"
        >
          <p>请确认同步信息并进行安全验证。</p>
        </el-alert>
        
        <div class="summary-item">
          <span class="label">同步目标应用：</span>
          <span class="value">{{ app?.app_name }}</span>
        </div>
        <div class="summary-item">
          <span class="label">同步用户数量：</span>
          <span class="value highlight">{{ syncCount }} 人</span>
        </div>
        <div class="summary-item">
          <span class="label">同步字段：</span>
          <span class="value">
            账号 (英文名/手机号), 手机号, 状态
            <span v-if="form.init_email">, 邮箱 ({{ form.email_domain }})</span>
          </span>
        </div>

        <el-divider />

        <el-form :model="securityForm" label-width="0">
           <el-form-item>
             <div class="verify-code-container">
                <el-input v-model="securityForm.verificationCode" placeholder="请输入手机验证码" />
                <el-button type="primary" :disabled="timer > 0" @click="sendCode">
                  {{ timer > 0 ? `${timer}s` : '发送验证码' }}
                </el-button>
             </div>
           </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSync" :loading="syncing">
            确认同步
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getApp, Application, syncAppUsersV2 } from '../../api/apps'
import { getUsers, User } from '../../api/users'
import { sendImportVerificationCode } from '../../api/mapping' // Reusing the send verification code API
import { ElMessage } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const appId = Number(route.params.id)

const app = ref<Application | null>(null)
const loading = ref(false)
const syncing = ref(false)

// Form
const form = reactive({
  mode: 'ALL',
  init_email: false,
  email_domain: '@hnyunzhu.com'
})

// User Table Data
const users = ref<User[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')

// 使用 Set 保存所有已选择的用户ID（跨页保存）
const selectedUserIds = ref<Set<number>>(new Set())
// 使用 Map 保存已选择用户的详细信息
const selectedUsersMap = ref<Map<number, User>>(new Map())
const userTableRef = ref()

// Security
const confirmDialogVisible = ref(false)
const securityForm = reactive({
  verificationCode: ''
})
const timer = ref(0)

// Computed - 已选择用户列表（用于显示）
const selectedUsersList = computed(() => {
  return Array.from(selectedUsersMap.value.values())
})

// Computed
const syncCount = computed(() => {
  if (form.mode === 'ALL') return total.value // Approximation if we don't fetch all. Ideally backend tells us, but for now we use total.
  return selectedUserIds.value.size
})

// 监听 mode 变化，切换模式时清空选择
watch(() => form.mode, (newMode) => {
  if (newMode === 'ALL') {
    selectedUserIds.value.clear()
    selectedUsersMap.value.clear()
  }
})

onMounted(async () => {
  if (!appId) {
    ElMessage.error('Invalid App ID')
    router.push({ name: 'AppList' })
    return
  }
  await fetchApp()
  await fetchUsers()
})

const fetchApp = async () => {
  try {
    const res = await getApp(appId)
    app.value = res.data
  } catch (e) {
    // handled by interceptor
  }
}

const fetchUsers = async () => {
  loading.value = true
  try {
    const params: any = {
      skip: (page.value - 1) * pageSize.value,
      limit: pageSize.value
    }
    
    // 添加搜索关键词
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value.trim()
    }
    
    const res = await getUsers(params)
    users.value = res.data.items
    total.value = res.data.total
    
    // 数据加载完成后，恢复选择状态
    await nextTick()
    restoreSelection()
  } catch (e) {
    // error
  } finally {
    loading.value = false
  }
}

// 恢复表格选择状态
const restoreSelection = () => {
  if (!userTableRef.value) return
  
  // 清空当前选择
  userTableRef.value.clearSelection()
  
  // 遍历当前页的用户，如果ID在 selectedUserIds 中，则选中
  users.value.forEach((user) => {
    if (selectedUserIds.value.has(user.id)) {
      userTableRef.value.toggleRowSelection(user, true)
      // 确保用户信息也在 Map 中
      if (!selectedUsersMap.value.has(user.id)) {
        selectedUsersMap.value.set(user.id, user)
      }
    }
  })
}

const handleSelectionChange = (val: User[]) => {
  // 获取当前页所有用户的ID
  const currentPageUserIds = new Set(users.value.map(u => u.id))
  
  // 先移除当前页的所有选择（因为可能取消选择了某些项）
  currentPageUserIds.forEach(id => {
    selectedUserIds.value.delete(id)
    selectedUsersMap.value.delete(id)
  })
  
  // 再将当前页新选中的用户ID添加到 selectedUserIds，并保存用户信息
  val.forEach(user => {
    selectedUserIds.value.add(user.id)
    selectedUsersMap.value.set(user.id, user)
  })
}

// 移除单个用户
const removeUser = (userId: number) => {
  selectedUserIds.value.delete(userId)
  selectedUsersMap.value.delete(userId)
  
  // 如果该用户在当前页，需要更新表格选择状态
  const currentUser = users.value.find(u => u.id === userId)
  if (currentUser && userTableRef.value) {
    userTableRef.value.toggleRowSelection(currentUser, false)
  }
}

// 清空所有选择
const clearAllSelection = () => {
  selectedUserIds.value.clear()
  selectedUsersMap.value.clear()
  
  // 清空表格选择状态
  if (userTableRef.value) {
    userTableRef.value.clearSelection()
  }
}

const handleSearch = () => {
  page.value = 1 // 搜索时重置到第一页
  fetchUsers()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  page.value = 1 // 改变每页数量时重置到第一页
  fetchUsers()
}

const handleCurrentChange = (val: number) => {
  page.value = val
  fetchUsers()
}

const goBack = () => {
  router.push({ name: 'AppList' })
}

const validateDomain = (domain: string) => {
  // Allow optional starting @, then standard domain regex
  // ^@? indicates optional @ at start
  // [a-zA-Z0-9] starts the domain part
  // (?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])? middle part
  // \. dot
  // [a-zA-Z]{2,} TLD
  const regex = /^@?([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/
  return regex.test(domain)
}

const handlePreSync = () => {
  if (form.init_email) {
      if (!form.email_domain) {
          ElMessage.warning('请输入邮箱域名')
          return
      }
      if (!validateDomain(form.email_domain)) {
          ElMessage.warning('邮箱域名格式不正确 (例如: @hnyunzhu.com)')
          return
      }
  }
  
  if (form.mode === 'SELECTED' && selectedUserIds.value.size === 0) {
    ElMessage.warning('请选择要同步的用户')
    return
  }
  
  securityForm.verificationCode = ''
  confirmDialogVisible.value = true
}

const sendCode = async () => {
  try {
    await sendImportVerificationCode() // Using the existing endpoint which sends to current user
    ElMessage.success('验证码已发送')
    timer.value = 60
    const interval = setInterval(() => {
      timer.value--
      if (timer.value <= 0) clearInterval(interval)
    }, 1000)
  } catch (e) {
    // error
  }
}

const confirmSync = async () => {
  if (!securityForm.verificationCode) {
    ElMessage.warning('请输入验证码')
    return
  }
  
  syncing.value = true
  try {
    // 将 Set 转换为数组
    const userIds = form.mode === 'SELECTED' ? Array.from(selectedUserIds.value) : []
    
    const res = await syncAppUsersV2(appId, {
      mode: form.mode as 'ALL' | 'SELECTED',
      user_ids: userIds,
      init_email: form.init_email,
      email_domain: form.email_domain,
      verification_code: securityForm.verificationCode
    })
    
    ElMessage.success(res.data.message)
    confirmDialogVisible.value = false
    // Maybe go back or stay?
    // User might want to see logs?
    // Let's stay but refresh selection?
    // Or go back to app list.
    // Let's offer to go to logs or close.
    // For now, simple success message.
  } catch (e) {
    // error
  } finally {
    syncing.value = false
  }
}
</script>

<style scoped>
.app-sync-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.sync-card {
  max-width: 1000px;
  margin: 0 auto;
}
.user-selection-area {
  margin-top: 20px;
  margin-bottom: 20px;
}
.search-container {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 15px;
}
.selected-count {
  color: #409EFF;
  font-weight: 500;
}
/* 已选择用户面板样式 */
.selected-users-panel {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.panel-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}
.selected-users-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.user-tag {
  margin: 0;
}
.user-mobile {
  margin-left: 5px;
  color: #909399;
  font-size: 12px;
}
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
.email-domain-input {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
}
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
.confirm-content {
  padding: 10px;
}
.summary-item {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}
.summary-item .label {
  font-weight: bold;
  color: #606266;
}
.summary-item .value {
  color: #303133;
}
.summary-item .value.highlight {
  color: #409EFF;
  font-weight: bold;
}
.verify-code-container {
  display: flex;
  gap: 10px;
  width: 100%;
}
</style>

