<template>
  <div>
    <h1 class="text-xl font-bold text-gray-800 mb-4">通讯录导入</h1>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :span="8">
        <el-card shadow="never" class="text-center">
          <div class="text-3xl font-bold text-blue-600">{{ stats.total }}</div>
          <div class="text-sm text-gray-500 mt-1">总计导入</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" class="text-center">
          <div class="text-3xl font-bold text-amber-500">{{ stats.pending }}</div>
          <div class="text-sm text-gray-500 mt-1">待匹配</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" class="text-center">
          <div class="text-3xl font-bold text-green-500">{{ stats.matched }}</div>
          <div class="text-sm text-gray-500 mt-1">已匹配</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 导入工具条 -->
    <el-card shadow="never" class="mb-4">
      <el-row :gutter="12" align="middle">
        <el-col>
          <input
            ref="fileInputRef"
            type="file"
            accept=".xlsx,.xls"
            style="display:none"
            @change="handleFileUpload"
          />
          <el-button type="success" :loading="uploading" @click="fileInputRef?.click()">
            {{ uploading ? '导入中...' : '上传 Excel 导入' }}
          </el-button>
          <span class="text-xs text-gray-400 ml-2">支持 .xlsx / .xls 格式，自动提取四川凌空员工</span>
        </el-col>
      </el-row>
    </el-card>

    <!-- 搜索/筛选栏 -->
    <el-card shadow="never" class="mb-4">
      <el-row :gutter="12" align="middle">
        <el-col :span="7">
          <el-input v-model="keyword" placeholder="搜索姓名/手机号" clearable />
        </el-col>
        <el-col :span="5">
          <el-select v-model="deptFilter" filterable placeholder="选择部门" clearable class="w-full" @change="doSearch">
            <el-option v-for="d in departments" :key="d.id" :label="d.name" :value="d.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="statusFilter" placeholder="状态" clearable class="w-full" @change="doSearch">
            <el-option label="全部" value="" />
            <el-option label="待匹配" value="pending" />
            <el-option label="已匹配" value="matched" />
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="doSearch">搜索</el-button>
        </el-col>
        <el-col :span="4" :push="2">
          <el-button type="warning" plain :loading="syncingAll" @click="handleSyncAll">一键同步</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 导入记录 -->
    <div class="bg-white rounded-xl shadow-sm border overflow-hidden">
      <div class="px-4 py-3 border-b">
        <h2 class="text-base font-semibold text-gray-700">导入记录</h2>
      </div>
      <el-table :data="list" stripe class="w-full" v-loading="loading">
        <el-table-column prop="real_name" label="姓名" min-width="100" />
        <el-table-column prop="phone" label="手机号" min-width="140" />
        <el-table-column prop="department_name" label="部门" min-width="140" />
        <el-table-column prop="position" label="职位" min-width="120">
          <template #default="{ row }">
            {{ row.position || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="dingtalk_user_id" label="钉钉UserId" min-width="160">
          <template #default="{ row }">
            <span class="text-sm text-gray-600">{{ row.dingtalk_user_id || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="90">
          <template #default="{ row }">
            <el-tag v-if="row.is_matched" type="success" size="small">已匹配</el-tag>
            <el-tag v-else type="warning" size="small">待匹配</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="匹配用户" min-width="100">
          <template #default="{ row }">
            <span v-if="row.matched_user_id" class="text-sm">#{{ row.matched_user_id }}</span>
            <span v-else class="text-gray-400 text-sm">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="matched_at" label="匹配时间" min-width="150">
          <template #default="{ row }">
            <span class="text-sm text-gray-500">{{ row.matched_at ? dayjs(row.matched_at).format('YYYY-MM-DD HH:mm') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :loading="matchingId === row.id"
              @click="handleMatch(row)"
            >{{ row.is_matched ? '重新同步' : '手动匹配' }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center p-4" v-if="total > pageSize">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[15, 30, 50, 100]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadData"
          @size-change="loadData(true)"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPendingEmployees, matchPendingEmployee, getPendingEmployeeStats, syncAllPendingEmployees, listAllDepartments } from '@/api'
import request from '@/utils/request'
import dayjs from 'dayjs'

const list = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(15)
const statusFilter = ref('')
const keyword = ref('')
const deptFilter = ref<number | undefined>(undefined)
const departments = ref<any[]>([])
const stats = ref({ total: 0, pending: 0, matched: 0 })
const matchingId = ref<number | null>(null)
const syncingAll = ref(false)
const uploading = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)
const loading = ref(false)

async function loadData(reset = false) {
  // reset 可能是布尔值或页码数字（来自 pagination 事件）
  if (reset === true) {
    page.value = 1
  }
  loading.value = true
  try {
    const res = await getPendingEmployees({
      page: page.value,
      page_size: pageSize.value,
      status: statusFilter.value || undefined,
      keyword: keyword.value || undefined,
      department_id: deptFilter.value || undefined,
    })
    const data = res as any
    list.value = data?.data?.list || []
    total.value = data?.data?.total || 0
  } catch {
    // request.ts 已自动弹出错误
  } finally {
    loading.value = false
  }
}

async function loadStats() {
  try {
    const res = await getPendingEmployeeStats() as any
    stats.value = res?.data || { total: 0, pending: 0, matched: 0 }
  } catch { /* ignore */ }
}

function doSearch() {
  loadData(true)
}

async function handleSyncAll() {
  await ElMessageBox.confirm('将一键同步所有待确认员工的信息到已绑定手机号的用户，确定执行？', '确认', {
    type: 'warning',
    confirmButtonText: '确定同步',
    cancelButtonText: '取消',
  })
  syncingAll.value = true
  try {
    const res = await syncAllPendingEmployees() as any
    const d = res?.data
    ElMessage.success(`同步完成：成功 ${d?.synced || 0} 人，跳过 ${d?.skipped || 0} 人（共 ${d?.total || 0} 人）`)
    await Promise.all([loadData(), loadStats()])
  } catch {
    // request.ts 已自动弹出错误
  } finally {
    syncingAll.value = false
  }
}

async function handleFileUpload(e: Event) {
  const input = e.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await request.Post('/v1/admin/employees/import-excel', formData) as any
    const d = res?.data || {}
    ElMessage.success(`导入完成：成功 ${d.imported || 0} 人，更新 ${d.updated || 0} 人，未匹配部门 ${d.noDept || 0} 人`)
    await Promise.all([loadData(true), loadStats()])
  } catch {
    // request.ts 已自动提示
  } finally {
    uploading.value = false
    input.value = '' // 清空 input 以便重新选择同一个文件
  }
}

async function handleMatch(row: any) {
  matchingId.value = row.id
  try {
    const res = await matchPendingEmployee(row.id) as any
    ElMessage.success(`匹配成功：${res?.data?.real_name || ''}（${res?.data?.phone || ''}）`)
    await Promise.all([loadData(), loadStats()])
  } catch {
    // request.ts 已自动弹出错误提示
  } finally {
    matchingId.value = null
  }
}

onMounted(async () => {
  const deptRes = await listAllDepartments()
  departments.value = (deptRes as any)?.data || []
  loadData()
  loadStats()
})
</script>
