<template>
  <view class="admin-page">
    <view class="filter-card">
      <view class="filter-row">
        <view class="filter-item">
          <text class="label">搜索：</text>
          <input class="filter-input" placeholder="请输入姓名、UID" v-model="searchQuery" @confirm="onSearch" />
        </view>
        <view class="filter-btns">
          <button class="btn primary" @click="onSearch">查询</button>
          <button class="btn" @click="onReset">重置</button>
        </view>
      </view>
    </view>
    <view class="content-card">
      <view class="tabs-row">
        <view v-for="(tab, index) in tabOptions" :key="index" class="tab-item" :class="{ active: activeTabIndex === index }" @click="onTabChange(index)">
          <text>{{ tab.label }}</text>
        </view>
      </view>
      <view class="table-container">
        <!-- Loading 遮罩 -->
        <view v-if="isLoading" class="loading-mask">
          <text class="loading-text">数据加载中...</text>
        </view>

        <view class="table-header">
          <view class="col col-uid"><text>用户UID</text></view>
          <view class="col col-name"><text>代理商名称</text></view>
          <view class="col col-phone"><text>代理商电话</text></view>
          <view class="col col-dept"><text>事业部名称</text></view>
          <view class="col col-img"><text>申请图片</text></view>
          <view class="col col-time"><text>申请时间</text></view>
          <view class="col col-status"><text>申请状态</text></view>
          <view class="col col-code"><text>邀请码</text></view>
          <view class="col col-ops"><text>操作</text></view>
        </view>
        <view class="table-body">
          <view v-if="applyList.length === 0 && !isLoading" class="empty-row">
            <text>暂无申请记录</text>
          </view>
          <view v-for="item in applyList" :key="item.id" class="table-row">
            <view class="col col-uid"><text class="td-txt-small">{{ item.uid }}</text></view>
            <view class="col col-name"><text>{{ item.name }}</text></view>
            <view class="col col-phone"><text>{{ item.phone || '-' }}</text></view>
            <view class="col col-dept"><text>{{ item.dept_name }}</text></view>
            <view class="col col-img">
              <image v-if="item.proof_images != null && item.proof_images!.length > 0" class="table-img" :src="item.proof_images![0]" mode="aspectFill" />
              <view v-else class="img-placeholder"><text>无</text></view>
            </view>
            <view class="col col-time"><text class="td-txt-small">{{ formatDateTime(item.time) }}</text></view>
            <view class="col col-status">
              <view class="status-tag" :class="getStatusClass(item.status)"><text>{{ getStatusText(item.status) }}</text></view>
            </view>
            <view class="col col-code"><view class="code-box"><text>{{ item.invite_code }}</text></view></view>
            <view class="col col-ops">
              <template v-if="item.status === 'pending'">
                <text class="op-link" @click="handleProcess(item, 'approved')">同意</text>
                <text class="op-divider">|</text>
                <text class="op-link danger" @click="handleProcess(item, 'rejected')">拒绝</text>
              </template>
              <text v-else class="op-disabled">-</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 分页 -->
      <view class="pagination">
        <view class="pager-btns">
          <button class="btn small" :disabled="page <= 1" @click="onPrevPage">上一页</button>
          <text class="page-num">第 {{ page }} 页</text>
          <button class="btn small" :disabled="applyList.length < pageSize" @click="onNextPage">下一页</button>
        </view>
        <text class="page-info">共 {{ applyList.length }} 条记录</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import { getAgentApplyList, processAgentApply, type AgentApply } from '@/services/admin/distributionService.uts'

const isLoading = ref(false)
const applyList = ref<AgentApply[]>([])
const searchQuery = ref('')
const page = ref(1)
const pageSize = 20

const activeTabIndex = ref(0)
const tabOptions = [
  { label: '全部', value: 'all' },
  { label: '申请中', value: 'pending' },
  { label: '已同意', value: 'approved' },
  { label: '已拒绝', value: 'rejected' }
]

onMounted(() => {
  loadData()
})

async function loadData() {
  isLoading.value = true
  try {
    const status = tabOptions[activeTabIndex.value].value
    const res = await getAgentApplyList(status, searchQuery.value || null, page.value, pageSize)
    applyList.value = res
  } catch (e) {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    isLoading.value = false
  }
}

function onSearch() {
  page.value = 1
  loadData()
}

function onReset() {
  searchQuery.value = ''
  page.value = 1
  loadData()
}

function onTabChange(index : number) {
  activeTabIndex.value = index
  page.value = 1
  loadData()
}

async function handleProcess(item : AgentApply, status : string) {
  const actionText = status === 'approved' ? '同意' : '拒绝'
  
  if (status === 'rejected') {
    uni.showModal({
      title: '拒绝申请',
      editable: true,
      placeholderText: '请输入拒绝原因',
      success: async (res) => {
        if (res.confirm) {
          await doProcess(item.id, status, res.content)
        }
      }
    })
  } else {
    uni.showModal({
      title: '提示',
      content: `确定要 ${actionText} 该申请吗？`,
      success: async (res) => {
        if (res.confirm) {
          await doProcess(item.id, status, null)
        }
      }
    })
  }
}

async function doProcess(id : string, status : string, reason : string | null) {
  isLoading.value = true
  try {
    const success = await processAgentApply(id, status, reason)
    if (success) {
      uni.showToast({ title: '处理成功', icon: 'success' })
      loadData()
    }
  } finally {
    isLoading.value = false
  }
}

function onPrevPage() {
  if (page.value > 1) {
    page.value--
    loadData()
  }
}

function onNextPage() {
  if (applyList.value.length < pageSize) return
  page.value++
  loadData()
}

function getStatusText(status : string) : string {
  if (status === 'pending') return '申请中'
  if (status === 'approved') return '已同意'
  if (status === 'rejected') return '已拒绝'
  return status
}

function getStatusClass(status : string) : string {
  if (status === 'pending') return 'pending'
  if (status === 'approved') return 'approved'
  if (status === 'rejected') return 'rejected'
  return ''
}

function formatDateTime(dateStr : string) : string {
  return dateStr.substring(0, 16).replace('T', ' ')
}
</script>

<style scoped lang="scss">
.admin-page { padding: 0; }
.filter-card { background: #fff; padding: 24px; margin-bottom: 16px; border-radius: 4px; }
.filter-row { display: flex; flex-direction: row; align-items: center; gap: 24px; }
.label { font-size: 14px; color: #333; }
.filter-input { border: 1px solid #d9d9d9; height: 32px; width: 220px; padding: 0 12px; font-size: 14px; border-radius: 4px; }
.btn { height: 32px; padding: 0 16px; font-size: 14px; border: 1px solid #d9d9d9; background: #fff; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 4px; }
.btn.primary { background: #1890ff; border-color: #1890ff; color: #fff; }
.btn.small { height: 28px; padding: 0 12px; font-size: 13px; }

.content-card { background: #fff; border-radius: 4px; position: relative; }
.tabs-row { display: flex; flex-direction: row; padding: 0 24px; border-bottom: 1px solid #f0f0f0; }
.tab-item { padding: 16px 20px; cursor: pointer; position: relative; text { font-size: 15px; color: #666; } &.active { text { color: #1890ff; font-weight: 500; } &::after { content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 2px; background: #1890ff; } } }

.table-container { padding: 24px; min-height: 200px; }
.table-header { display: flex; flex-direction: row; background: #f8faff; border-bottom: 1px solid #f0f0f0; padding: 12px 0; }
.table-row { display: flex; flex-direction: row; border-bottom: 1px solid #f0f0f0; padding: 12px 0; align-items: center; &:hover { background: #fafafa; } }
.col { padding: 0 8px; font-size: 14px; color: #333; display: flex; align-items: center; }

.col-uid { width: 80px; } .col-name { width: 120px; } .col-phone { width: 120px; } .col-dept { width: 120px; } .col-img { width: 80px; justify-content: center; } .col-time { width: 160px; justify-content: center; } .col-status { width: 100px; justify-content: center; } .col-code { width: 100px; justify-content: center; } .col-ops { flex: 1; justify-content: flex-end; }

.td-txt-small { font-size: 12px; color: #666; }
.table-img { width: 32px; height: 32px; border-radius: 2px; background: #f5f5f5; }
.img-placeholder { width: 32px; height: 32px; background: #f5f5f5; display: flex; align-items: center; justify-content: center; text { font-size: 12px; color: #ccc; } }

.status-tag { border: 1px solid #d9d9d9; color: #666; padding: 2px 8px; border-radius: 4px; font-size: 12px; background: #fafafa; 
  &.pending { border-color: #1890ff; color: #1890ff; background: #e6f7ff; }
  &.approved { border-color: #52c41a; color: #52c41a; background: #f6ffed; }
  &.rejected { border-color: #f5222d; color: #f5222d; background: #fff1f0; }
}

.code-box { border: 1px solid #d9d9d9; padding: 2px 8px; border-radius: 4px; font-size: 12px; background: #fafafa; }
.op-link { color: #1890ff; cursor: pointer; &.danger { color: #ff4d4f; } }
.op-divider { color: #e8e8e8; margin: 0 8px; }
.op-disabled { color: #ccc; font-size: 14px; }

.pagination { padding: 16px 24px; border-top: 1px solid #f0f0f0; display: flex; flex-direction: row; align-items: center; justify-content: space-between; }
.pager-btns { display: flex; flex-direction: row; align-items: center; gap: 12px; }
.page-num { font-size: 14px; color: #333; }
.page-info { font-size: 14px; color: #999; }

.loading-mask { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.7); display: flex; align-items: center; justify-content: center; z-index: 10; }
.loading-text { color: #1890ff; font-size: 14px; }
.empty-row { padding: 40px 0; text-align: center; color: #999; font-size: 14px; }
</style>
